text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as UI from '../../ui/legacy/legacy.js';
import playerPropertiesViewStyles from './playerPropertiesView.css.js';
import type * as Protocol from '../../generated/protocol.js';
const UIStrings = {
/**
*@description The type of media, for example - video, audio, or text. Capitalized.
*/
video: 'Video',
/**
*@description The type of media, for example - video, audio, or text. Capitalized.
*/
audio: 'Audio',
/**
*@description A video or audio stream - but capitalized.
*/
track: 'Track',
/**
*@description A device that converts media files into playable streams of audio or video.
*/
decoder: 'Decoder',
/**
*@description Title of the 'Properties' tool in the sidebar of the elements tool
*/
properties: 'Properties',
/**
*@description Menu label for text tracks, it is followed by a number, like 'Text Track #1'
*/
textTrack: 'Text track',
/**
* @description Placeholder text stating that there are no text tracks on this player. A text track
* is all of the text that accompanies a particular video.
*/
noTextTracks: 'No text tracks',
/**
*@description Media property giving the width x height of the video
*/
resolution: 'Resolution',
/**
*@description Media property giving the file size of the media
*/
fileSize: 'File size',
/**
*@description Media property giving the media file bitrate
*/
bitrate: 'Bitrate',
/**
*@description Text for the duration of something
*/
duration: 'Duration',
/**
*@description The label for a timestamp when a video was started.
*/
startTime: 'Start time',
/**
*@description Media property signaling whether the media is streaming
*/
streaming: 'Streaming',
/**
*@description Media property describing where the media is playing from.
*/
playbackFrameUrl: 'Playback frame URL',
/**
*@description Media property giving the title of the frame where the media is embedded
*/
playbackFrameTitle: 'Playback frame title',
/**
*@description Media property describing whether the file is single or cross origin in nature
*/
singleoriginPlayback: 'Single-origin playback',
/**
*@description Media property describing support for range http headers
*/
rangeHeaderSupport: '`Range` header support',
/**
*@description Media property giving the media file frame rate
*/
frameRate: 'Frame rate',
/**
* @description Media property giving the distance of the playback quality from the ideal playback.
* Roughness is the opposite to smoothness, i.e. whether each frame of the video was played at the
* right time so that the video looks smooth when it plays.
*/
videoPlaybackRoughness: 'Video playback roughness',
/**
*@description A score describing how choppy the video playback is.
*/
videoFreezingScore: 'Video freezing score',
/**
*@description Media property giving the name of the renderer being used
*/
rendererName: 'Renderer name',
/**
*@description Media property giving the name of the decoder being used
*/
decoderName: 'Decoder name',
/**
*@description There is no decoder
*/
noDecoder: 'No decoder',
/**
*@description Media property signaling whether a hardware decoder is being used
*/
hardwareDecoder: 'Hardware decoder',
/**
*@description Media property signaling whether the content is encrypted. This is a noun phrase for
*a demultiplexer that does decryption.
*/
decryptingDemuxer: 'Decrypting demuxer',
/**
*@description Media property giving the name of the video encoder being used.
*/
encoderName: 'Encoder name',
/**
*@description There is no encoder.
*/
noEncoder: 'No encoder',
/**
*@description Media property signaling whether the encoder is hardware accelerated.
*/
hardwareEncoder: 'Hardware encoder',
};
const str_ = i18n.i18n.registerUIStrings('panels/media/PlayerPropertiesView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
const i18nLazyString = i18n.i18n.getLazilyComputedLocalizedString.bind(undefined, str_);
type TabData = {
[x: string]: string,
};
// Keep this enum in sync with panels/media/base/media_log_properties.h
export const enum PlayerPropertyKeys {
Resolution = 'kResolution',
TotalBytes = 'kTotalBytes',
Bitrate = 'kBitrate',
MaxDuration = 'kMaxDuration',
StartTime = 'kStartTime',
IsVideoEncrypted = 'kIsVideoEncrypted',
IsStreaming = 'kIsStreaming',
FrameUrl = 'kFrameUrl',
FrameTitle = 'kFrameTitle',
IsSingleOrigin = 'kIsSingleOrigin',
IsRangeHeaderSupported = 'kIsRangeHeaderSupported',
RendererName = 'kRendererName',
VideoDecoderName = 'kVideoDecoderName',
AudioDecoderName = 'kAudioDecoderName',
IsPlatformVideoDecoder = 'kIsPlatformVideoDecoder',
IsPlatformAudioDecoder = 'kIsPlatformAudioDecoder',
VideoEncoderName = 'kVideoEncoderName',
IsPlatformVideoEncoder = 'kIsPlatformVideoEncoder',
IsVideoDecryptingDemuxerStream = 'kIsVideoDecryptingDemuxerStream',
IsAudioDecryptingDemuxerStream = 'kIsAudioDecryptingDemuxerStream',
AudioTracks = 'kAudioTracks',
TextTracks = 'kTextTracks',
VideoTracks = 'kVideoTracks',
Framerate = 'kFramerate',
VideoPlaybackRoughness = 'kVideoPlaybackRoughness',
VideoPlaybackFreezing = 'kVideoPlaybackFreezing',
}
export class PropertyRenderer extends UI.Widget.VBox {
private readonly title: Platform.UIString.LocalizedString;
private readonly contents: HTMLElement;
private value: string|null;
private pseudoColorProtectionElement: HTMLDivElement|null;
constructor(title: Platform.UIString.LocalizedString) {
super();
this.contentElement.classList.add('media-property-renderer');
const titleElement = this.contentElement.createChild('span', 'media-property-renderer-title');
this.contents = this.contentElement.createChild('span', 'media-property-renderer-contents');
UI.UIUtils.createTextChild(titleElement, title);
this.title = title;
this.value = null;
this.pseudoColorProtectionElement = null;
this.contentElement.classList.add('media-property-renderer-hidden');
}
updateData(propname: string, propvalue: string): void {
// convert all empty possibilities into nulls for easier handling.
if (propvalue === '' || propvalue === null) {
return this.updateDataInternal(propname, null);
}
try {
propvalue = JSON.parse(propvalue) as string;
} catch (err) {
// TODO(tmathmeyer) typecheck the type of propvalue against
// something defined or sourced from the c++ definitions.
// Do nothing, some strings just stay strings!
}
return this.updateDataInternal(propname, propvalue);
}
protected updateDataInternal(propname: string, propvalue: string|null): void {
if (propvalue === null) {
this.changeContents(null);
} else if (this.value === propvalue) {
return; // Don't rebuild element!
} else {
this.value = propvalue;
this.changeContents(propvalue);
}
}
changeContents(value: string|null): void {
if (value === null) {
this.contentElement.classList.add('media-property-renderer-hidden');
if (this.pseudoColorProtectionElement === null) {
this.pseudoColorProtectionElement = document.createElement('div');
this.pseudoColorProtectionElement.classList.add('media-property-renderer');
this.pseudoColorProtectionElement.classList.add('media-property-renderer-hidden');
(this.contentElement.parentNode as HTMLElement)
.insertBefore(this.pseudoColorProtectionElement, this.contentElement);
}
} else {
if (this.pseudoColorProtectionElement !== null) {
this.pseudoColorProtectionElement.remove();
this.pseudoColorProtectionElement = null;
}
this.contentElement.classList.remove('media-property-renderer-hidden');
this.contents.removeChildren();
const spanElement = document.createElement('span');
spanElement.textContent = value;
this.contents.appendChild(spanElement);
}
}
}
export class FormattedPropertyRenderer extends PropertyRenderer {
private readonly formatfunction: (arg0: string) => string;
constructor(title: Platform.UIString.LocalizedString, formatfunction: (arg0: string) => string) {
super(title);
this.formatfunction = formatfunction;
}
updateDataInternal(propname: string, propvalue: string|null): void {
if (propvalue === null) {
this.changeContents(null);
} else {
this.changeContents(this.formatfunction(propvalue));
}
}
}
export class DefaultPropertyRenderer extends PropertyRenderer {
constructor(title: Platform.UIString.LocalizedString, defaultText: string) {
super(title);
this.changeContents(defaultText);
}
}
export class DimensionPropertyRenderer extends PropertyRenderer {
private width: number;
private height: number;
constructor(title: Platform.UIString.LocalizedString) {
super(title);
this.width = 0;
this.height = 0;
}
updateDataInternal(propname: string, propvalue: string|null): void {
let needsUpdate = false;
if (propname === 'width' && Number(propvalue) !== this.width) {
this.width = Number(propvalue);
needsUpdate = true;
}
if (propname === 'height' && Number(propvalue) !== this.height) {
this.height = Number(propvalue);
needsUpdate = true;
}
// If both properties arent set, don't bother updating, since
// temporarily showing ie: 1920x0 is meaningless.
if (this.width === 0 || this.height === 0) {
this.changeContents(null);
} else if (needsUpdate) {
this.changeContents(`${this.width}×${this.height}`);
}
}
}
export class AttributesView extends UI.Widget.VBox {
private readonly contentHash: number;
constructor(elements: UI.Widget.Widget[]) {
super();
this.contentHash = 0;
this.contentElement.classList.add('media-attributes-view');
for (const element of elements) {
element.show(this.contentElement);
// We just need a really simple way to compare the topical equality
// of the attributes views in order to avoid deleting and recreating
// a node containing exactly the same data.
const content = this.contentElement.textContent;
if (content !== null) {
this.contentHash += Platform.StringUtilities.hashCode(content);
}
}
}
getContentHash(): number {
return this.contentHash;
}
}
export class TrackManager {
private readonly type: string;
private readonly view: PlayerPropertiesView;
constructor(propertiesView: PlayerPropertiesView, type: string) {
this.type = type;
this.view = propertiesView;
}
updateData(_name: string, value: string): void {
const tabs = this.view.getTabs(this.type);
const newTabs = JSON.parse(value) as TabData[];
let enumerate = 1;
for (const tabData of newTabs) {
this.addNewTab(tabs, tabData, enumerate);
enumerate++;
}
}
addNewTab(tabs: GenericTrackMenu|NoTracksPlaceholderMenu, tabData: TabData, tabNumber: number): void {
const tabElements = [];
for (const [name, data] of Object.entries(tabData)) {
tabElements.push(new DefaultPropertyRenderer(i18n.i18n.lockedString(name), data));
}
const newTab = new AttributesView(tabElements);
tabs.addNewTab(tabNumber, newTab);
}
}
export class VideoTrackManager extends TrackManager {
constructor(propertiesView: PlayerPropertiesView) {
super(propertiesView, 'video');
}
}
export class TextTrackManager extends TrackManager {
constructor(propertiesView: PlayerPropertiesView) {
super(propertiesView, 'text');
}
}
export class AudioTrackManager extends TrackManager {
constructor(propertiesView: PlayerPropertiesView) {
super(propertiesView, 'audio');
}
}
const TrackTypeLocalized = {
Video: i18nLazyString(UIStrings.video),
Audio: i18nLazyString(UIStrings.audio),
};
class GenericTrackMenu extends UI.TabbedPane.TabbedPane {
private readonly decoderName: string;
private readonly trackName: string;
constructor(decoderName: string, trackName: string = i18nString(UIStrings.track)) {
super();
this.decoderName = decoderName;
this.trackName = trackName;
}
addNewTab(trackNumber: number, element: AttributesView): void {
const localizedTrackLower = i18nString(UIStrings.track);
const tabId = `Track${trackNumber}`;
if (this.hasTab(tabId)) {
const tabElement = this.tabView(tabId);
if (tabElement === null) {
return;
}
if ((tabElement as AttributesView).getContentHash() === element.getContentHash()) {
return;
}
this.closeTab(tabId, /* userGesture=*/ false);
}
this.appendTab(
tabId, // No need for localizing, internal ID.
`${this.trackName} #${trackNumber}`, element, `${this.decoderName} ${localizedTrackLower} #${trackNumber}`);
}
}
class DecoderTrackMenu extends GenericTrackMenu {
constructor(decoderName: string, informationalElement: UI.Widget.Widget) {
super(decoderName);
const decoderLocalized = i18nString(UIStrings.decoder);
const title = `${decoderName} ${decoderLocalized}`;
const propertiesLocalized = i18nString(UIStrings.properties);
const hoverText = `${title} ${propertiesLocalized}`;
this.appendTab('DecoderProperties', title, informationalElement, hoverText);
}
}
class NoTracksPlaceholderMenu extends UI.Widget.VBox {
private isPlaceholder: boolean;
private readonly wrapping: GenericTrackMenu;
constructor(wrapping: GenericTrackMenu, placeholderText: string) {
super();
this.isPlaceholder = true;
this.wrapping = wrapping;
this.wrapping.appendTab('_placeholder', placeholderText, new UI.Widget.VBox(), placeholderText);
this.wrapping.show(this.contentElement);
}
addNewTab(trackNumber: number, element: AttributesView): void {
if (this.isPlaceholder) {
this.wrapping.closeTab('_placeholder');
this.isPlaceholder = false;
}
this.wrapping.addNewTab(trackNumber, element);
}
}
export class PlayerPropertiesView extends UI.Widget.VBox {
private readonly mediaElements: PropertyRenderer[];
private readonly videoDecoderElements: PropertyRenderer[];
private readonly audioDecoderElements: PropertyRenderer[];
private readonly textTrackElements: PropertyRenderer[];
private readonly attributeMap: Map<string, PropertyRenderer|TrackManager>;
private readonly videoProperties: AttributesView;
private readonly videoDecoderProperties: AttributesView;
private readonly audioDecoderProperties: AttributesView;
private readonly videoDecoderTabs: DecoderTrackMenu;
private readonly audioDecoderTabs: DecoderTrackMenu;
private textTracksTabs: GenericTrackMenu|NoTracksPlaceholderMenu|null;
constructor() {
super();
this.contentElement.classList.add('media-properties-frame');
this.mediaElements = [];
this.videoDecoderElements = [];
this.audioDecoderElements = [];
this.textTrackElements = [];
this.attributeMap = new Map();
this.populateAttributesAndElements();
this.videoProperties = new AttributesView(this.mediaElements);
this.videoDecoderProperties = new AttributesView(this.videoDecoderElements);
this.audioDecoderProperties = new AttributesView(this.audioDecoderElements);
this.videoProperties.show(this.contentElement);
this.videoDecoderTabs = new DecoderTrackMenu(TrackTypeLocalized.Video(), this.videoDecoderProperties);
this.videoDecoderTabs.show(this.contentElement);
this.audioDecoderTabs = new DecoderTrackMenu(TrackTypeLocalized.Audio(), this.audioDecoderProperties);
this.audioDecoderTabs.show(this.contentElement);
this.textTracksTabs = null;
}
private lazyCreateTrackTabs(): GenericTrackMenu|NoTracksPlaceholderMenu {
let textTracksTabs = this.textTracksTabs;
if (textTracksTabs === null) {
const textTracks = new GenericTrackMenu(i18nString(UIStrings.textTrack));
textTracksTabs = new NoTracksPlaceholderMenu(textTracks, i18nString(UIStrings.noTextTracks));
textTracksTabs.show(this.contentElement);
this.textTracksTabs = textTracksTabs;
}
return textTracksTabs;
}
getTabs(type: string): GenericTrackMenu|NoTracksPlaceholderMenu {
if (type === 'audio') {
return this.audioDecoderTabs;
}
if (type === 'video') {
return this.videoDecoderTabs;
}
if (type === 'text') {
return this.lazyCreateTrackTabs();
}
// There should be no other type allowed.
throw new Error('Unreachable');
}
onProperty(property: Protocol.Media.PlayerProperty): void {
const renderer = this.attributeMap.get(property.name);
if (!renderer) {
throw new Error(`Player property "${property.name}" not supported.`);
}
renderer.updateData(property.name, property.value);
}
formatKbps(bitsPerSecond: string|number): string {
if (bitsPerSecond === '') {
return '0 kbps';
}
const kbps = Math.floor(Number(bitsPerSecond) / 1000);
return `${kbps} kbps`;
}
formatTime(seconds: string|number): string {
if (seconds === '') {
return '0:00';
}
const date = new Date();
date.setSeconds(Number(seconds));
return date.toISOString().substr(11, 8);
}
formatFileSize(bytes: string): string {
if (bytes === '') {
return '0 bytes';
}
const actualBytes = Number(bytes);
if (actualBytes < 1000) {
return `${bytes} bytes`;
}
const power = Math.floor(Math.log10(actualBytes) / 3);
const suffix = ['bytes', 'kB', 'MB', 'GB', 'TB'][power];
const bytesDecimal = (actualBytes / Math.pow(1000, power)).toFixed(2);
return `${bytesDecimal} ${suffix}`;
}
populateAttributesAndElements(): void {
/* Media properties */
const resolution = new PropertyRenderer(i18nString(UIStrings.resolution));
this.mediaElements.push(resolution);
this.attributeMap.set(PlayerPropertyKeys.Resolution, resolution);
const fileSize = new FormattedPropertyRenderer(i18nString(UIStrings.fileSize), this.formatFileSize);
this.mediaElements.push(fileSize);
this.attributeMap.set(PlayerPropertyKeys.TotalBytes, fileSize);
const bitrate = new FormattedPropertyRenderer(i18nString(UIStrings.bitrate), this.formatKbps);
this.mediaElements.push(bitrate);
this.attributeMap.set(PlayerPropertyKeys.Bitrate, bitrate);
const duration = new FormattedPropertyRenderer(i18nString(UIStrings.duration), this.formatTime);
this.mediaElements.push(duration);
this.attributeMap.set(PlayerPropertyKeys.MaxDuration, duration);
const startTime = new PropertyRenderer(i18nString(UIStrings.startTime));
this.mediaElements.push(startTime);
this.attributeMap.set(PlayerPropertyKeys.StartTime, startTime);
const streaming = new PropertyRenderer(i18nString(UIStrings.streaming));
this.mediaElements.push(streaming);
this.attributeMap.set(PlayerPropertyKeys.IsStreaming, streaming);
const frameUrl = new PropertyRenderer(i18nString(UIStrings.playbackFrameUrl));
this.mediaElements.push(frameUrl);
this.attributeMap.set(PlayerPropertyKeys.FrameUrl, frameUrl);
const frameTitle = new PropertyRenderer(i18nString(UIStrings.playbackFrameTitle));
this.mediaElements.push(frameTitle);
this.attributeMap.set(PlayerPropertyKeys.FrameTitle, frameTitle);
const singleOrigin = new PropertyRenderer(i18nString(UIStrings.singleoriginPlayback));
this.mediaElements.push(singleOrigin);
this.attributeMap.set(PlayerPropertyKeys.IsSingleOrigin, singleOrigin);
const rangeHeaders = new PropertyRenderer(i18nString(UIStrings.rangeHeaderSupport));
this.mediaElements.push(rangeHeaders);
this.attributeMap.set(PlayerPropertyKeys.IsRangeHeaderSupported, rangeHeaders);
const frameRate = new PropertyRenderer(i18nString(UIStrings.frameRate));
this.mediaElements.push(frameRate);
this.attributeMap.set(PlayerPropertyKeys.Framerate, frameRate);
const roughness = new PropertyRenderer(i18nString(UIStrings.videoPlaybackRoughness));
this.mediaElements.push(roughness);
this.attributeMap.set(PlayerPropertyKeys.VideoPlaybackRoughness, roughness);
const freezingScore = new PropertyRenderer(i18nString(UIStrings.videoFreezingScore));
this.mediaElements.push(freezingScore);
this.attributeMap.set(PlayerPropertyKeys.VideoPlaybackFreezing, freezingScore);
const rendererName = new PropertyRenderer(i18nString(UIStrings.rendererName));
this.mediaElements.push(rendererName);
this.attributeMap.set(PlayerPropertyKeys.RendererName, rendererName);
/* Video Decoder Properties */
const decoderName = new DefaultPropertyRenderer(i18nString(UIStrings.decoderName), i18nString(UIStrings.noDecoder));
this.videoDecoderElements.push(decoderName);
this.attributeMap.set(PlayerPropertyKeys.VideoDecoderName, decoderName);
const videoPlatformDecoder = new PropertyRenderer(i18nString(UIStrings.hardwareDecoder));
this.videoDecoderElements.push(videoPlatformDecoder);
this.attributeMap.set(PlayerPropertyKeys.IsPlatformVideoDecoder, videoPlatformDecoder);
const encoderName = new DefaultPropertyRenderer(i18nString(UIStrings.encoderName), i18nString(UIStrings.noEncoder));
this.videoDecoderElements.push(encoderName);
this.attributeMap.set(PlayerPropertyKeys.VideoEncoderName, encoderName);
const videoPlatformEncoder = new PropertyRenderer(i18nString(UIStrings.hardwareEncoder));
this.videoDecoderElements.push(videoPlatformEncoder);
this.attributeMap.set(PlayerPropertyKeys.IsPlatformVideoEncoder, videoPlatformEncoder);
const videoDDS = new PropertyRenderer(i18nString(UIStrings.decryptingDemuxer));
this.videoDecoderElements.push(videoDDS);
this.attributeMap.set(PlayerPropertyKeys.IsVideoDecryptingDemuxerStream, videoDDS);
const videoTrackManager = new VideoTrackManager(this);
this.attributeMap.set(PlayerPropertyKeys.VideoTracks, videoTrackManager);
/* Audio Decoder Properties */
const audioDecoder =
new DefaultPropertyRenderer(i18nString(UIStrings.decoderName), i18nString(UIStrings.noDecoder));
this.audioDecoderElements.push(audioDecoder);
this.attributeMap.set(PlayerPropertyKeys.AudioDecoderName, audioDecoder);
const audioPlatformDecoder = new PropertyRenderer(i18nString(UIStrings.hardwareDecoder));
this.audioDecoderElements.push(audioPlatformDecoder);
this.attributeMap.set(PlayerPropertyKeys.IsPlatformAudioDecoder, audioPlatformDecoder);
const audioDDS = new PropertyRenderer(i18nString(UIStrings.decryptingDemuxer));
this.audioDecoderElements.push(audioDDS);
this.attributeMap.set(PlayerPropertyKeys.IsAudioDecryptingDemuxerStream, audioDDS);
const audioTrackManager = new AudioTrackManager(this);
this.attributeMap.set(PlayerPropertyKeys.AudioTracks, audioTrackManager);
const textTrackManager = new TextTrackManager(this);
this.attributeMap.set(PlayerPropertyKeys.TextTracks, textTrackManager);
}
wasShown(): void {
super.wasShown();
this.registerCSSFiles([playerPropertiesViewStyles]);
}
} | the_stack |
import {Nullable} from './base'
import {getElement, pixelRatio} from './util'
import {View} from './view'
// Spacing between nodes in the tree.
const SPACE = 19;
// Padding from the edge of the canvas.
const PAD = 11;
// Radius of the nodes.
const RADIUS = 5;
interface Position {
parent: Nullable<Position>;
children: Position[];
}
class Node {
isMainline: boolean;
children: Node[] = [];
constructor(public parent: Nullable<Node>, public position: Position,
public x: number, public y: number) {
if (parent == null) {
// Root node.
this.isMainline = true;
} else {
this.isMainline = parent.isMainline && parent.children.length == 0;
parent.children.push(this);
}
}
}
interface LayoutResult {
maxDepth: number;
rootNode: Node;
}
type ClickListener = (position: Position) => void;
type HoverListener = (position: Nullable<Position>) => void;
class VariationTree extends View {
private rootNode: Nullable<Node> = null;
private ctx: CanvasRenderingContext2D;
private hoveredNode: Nullable<Node> = null;
private activeNode: Nullable<Node> = null;
private clickListeners: ClickListener[] = [];
private hoverListeners: HoverListener[] = [];
// Size of the canvas (ignoring the device's pixel ratio).
private width = 0;
private height = 0;
// Maximum x and y coordinate of tree nodes.
private maxX = 0;
private maxY = 0;
// Scroll offset for rendering the tree.
private scrollX = 0;
private scrollY = 0;
// It's 2018 and MouseEvent.movementX and MouseEvent.movementY is still not
// supported by all browsers, so we must calculate the movement deltas
// ourselves... *sigh*
private mouseX = 0;
private mouseY = 0;
constructor(parent: HTMLElement | string) {
super();
if (typeof(parent) == 'string') {
parent = getElement(parent);
}
let canvas = document.createElement('canvas');
this.ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
parent.appendChild(canvas);
this.resizeCanvas();
parent.addEventListener('mousemove', (e) => {
let oldNode = this.hoveredNode;
this.hoveredNode = this.hitTest(e.offsetX, e.offsetY);
if (this.hoveredNode != oldNode) {
if (this.hoveredNode != null) {
canvas.classList.add('pointer');
} else {
canvas.classList.remove('pointer');
}
for (let listener of this.hoverListeners) {
listener(this.hoveredNode ? this.hoveredNode.position : null);
}
}
});
parent.addEventListener('mousedown', (e) => {
this.mouseX = e.screenX;
this.mouseY = e.screenY;
let moveHandler = (e: MouseEvent) => {
this.scrollX += this.mouseX - e.screenX;
this.scrollY += this.mouseY - e.screenY;
this.scrollX = Math.min(this.scrollX, this.maxX + PAD - this.width);
this.scrollY = Math.min(this.scrollY, this.maxY + PAD - this.height);
this.scrollX = Math.max(this.scrollX, 0);
this.scrollY = Math.max(this.scrollY, 0);
this.mouseX = e.screenX;
this.mouseY = e.screenY;
this.draw();
e.preventDefault();
return false;
};
let upHandler = (e: MouseEvent) => {
window.removeEventListener('mousemove', moveHandler);
window.removeEventListener('mouseup', upHandler);
};
window.addEventListener('mousemove', moveHandler);
window.addEventListener('mouseup', upHandler);
});
parent.addEventListener('click', (e) => {
if (this.hoveredNode != null) {
for (let listener of this.clickListeners) {
listener(this.hoveredNode.position);
}
}
});
window.addEventListener('resize', () => {
this.resizeCanvas();
this.scrollIntoView();
this.draw();
});
}
newGame() {
this.rootNode = null;
this.activeNode = null;
this.layout();
this.scrollIntoView();
this.draw();
}
setRoot(position: Position) {
if (this.rootNode != null){
throw new Error('Already have a root note, you should call newGame first');
}
this.rootNode = new Node(null, position, PAD, PAD);
this.activeNode = this.rootNode;
}
setActive(position: Position) {
if (this.activeNode != null && this.activeNode.position != position) {
this.activeNode = this.lookupNode(position);
this.scrollIntoView();
this.draw();
}
}
addChild(parentPosition: Position, childPosition: Position) {
if (this.rootNode == null) {
throw new Error('Must start a game before attempting to add children');
}
// Add a new child node to the parent if necessary, or reuse the existing
// node.
let parentNode = this.lookupNode(parentPosition);
let childNode: Nullable<Node> = null;
for (let child of parentNode.children) {
if (child.position == childPosition) {
childNode = child;
break;
}
}
if (childNode == null) {
let x = parentNode.x + SPACE;
let y = parentNode.y + SPACE * parentNode.children.length;
childNode = new Node(parentNode, childPosition, x, y);
this.layout();
}
}
onClick(cb: ClickListener) {
this.clickListeners.push(cb);
}
onHover(cb: HoverListener) {
this.hoverListeners.push(cb);
}
private lookupNode(position: Position) {
let impl = (node: Node): Nullable<Node> => {
if (node.position == position) {
return node;
}
for (let child of node.children) {
let node = impl(child);
if (node != null) {
return node;
}
}
return null;
}
let node = this.rootNode != null ? impl(this.rootNode) : null;
if (node == null) {
throw new Error('Couldn\'t find node');
}
return node;
}
private hitTest(x: number, y: number) {
if (this.rootNode == null) {
return null;
}
x += this.scrollX;
y += this.scrollY;
let threshold = 0.4 * SPACE;
let traverse = (node: Node): Nullable<Node> => {
let dx = x - node.x;
let dy = y - node.y;
if (dx * dx + dy * dy < threshold * threshold) {
return node;
}
for (let child of node.children) {
let result = traverse(child);
if (result != null) {
return result;
}
}
return null;
};
return traverse(this.rootNode);
}
// TODO(tommadams): Don't draw parts of the tree that are out of view.
drawImpl() {
let ctx = this.ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
if (this.rootNode == null) {
return;
}
let pr = pixelRatio();
ctx.save();
ctx.translate(0.5 - pr * this.scrollX, 0.5 - pr * this.scrollY);
ctx.lineWidth = pr;
// Recursively draw the edges in the tree.
let drawEdges = (node: Node, drawMainline: boolean) => {
if (node.children.length == 0) {
return;
}
// Draw edges from parent to all children.
// The first child's edge is horizontal.
// The remaining childrens' edges slope at 45 degrees.
for (let child of node.children) {
let y = child.y;
if (child != node.children[0]) {
y -= SPACE;
}
if (drawMainline == child.isMainline) {
ctx.moveTo(pr * node.x, pr * y);
ctx.lineTo(pr * child.x, pr * child.y);
}
drawEdges(child, drawMainline);
}
// If a node has two or more children, draw a vertical line to
// connect the tops of all of the sloping edges.
if (node.children.length > 1 && !drawMainline) {
let lastChild = node.children[node.children.length - 1];
if (lastChild.y - SPACE > node.y) {
ctx.moveTo(pr * node.x, pr * node.y);
ctx.lineTo(pr * node.x, pr * (lastChild.y - SPACE));
}
}
};
for (let style of ['#fff', '#888']) {
ctx.beginPath();
ctx.strokeStyle = style;
drawEdges(this.rootNode, style == '#fff');
ctx.stroke();
}
// Draw the active node in red.
let r = RADIUS * pr;
if (this.activeNode != null) {
ctx.fillStyle = '#800';
ctx.strokeStyle = '#ff0';
ctx.beginPath();
ctx.arc(pr * this.activeNode.x, pr * this.activeNode.y, r, 0,
2 * Math.PI);
ctx.fill();
ctx.stroke();
}
// Draw the root node in gray.
ctx.strokeStyle = '#888';
if (this.activeNode != this.rootNode) {
ctx.fillStyle = '#666';
ctx.beginPath();
ctx.arc(pr * this.rootNode.x, pr * this.rootNode.y, r, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
}
// Recursively draw the non-root nodes.
// To avoid repeatedly changing the fill style between black and white,
// we draw in two passes: first all the black nodes, then all the white
// ones.
let drawNodes = (node: Node, draw: boolean) => {
if (draw && node != this.rootNode && node != this.activeNode) {
ctx.moveTo(pr * node.x + r, pr * node.y);
ctx.arc(pr * node.x, pr * node.y, r, 0, 2 * Math.PI);
}
for (let child of node.children) {
drawNodes(child, !draw);
}
};
for (let style of ['#000', '#fff']) {
ctx.fillStyle = style;
ctx.beginPath();
drawNodes(this.rootNode, style != '#000');
ctx.fill();
ctx.stroke();
}
ctx.restore();
}
private scrollIntoView() {
if (this.activeNode == null) {
return;
}
if (this.activeNode.x - this.scrollX > this.width - PAD) {
this.scrollX = this.activeNode.x - this.width + PAD;
} else if (this.activeNode.x - this.scrollX < PAD) {
this.scrollX = this.activeNode.x - PAD;
}
if (this.activeNode.y - this.scrollY > this.height - PAD) {
this.scrollY = this.activeNode.y - this.height + PAD;
} else if (this.activeNode.y - this.scrollY < PAD) {
this.scrollY = this.activeNode.y - PAD;
}
}
private layout() {
this.maxX = 0;
this.maxY = 0;
if (this.rootNode == null) {
return;
}
// Bottom-most node at each depth in the tree.
let bottomNode: Node[] = [this.rootNode];
// We want to lay the nodes in the tree out such that the main line of each
// node (the chain of first children of all descendants) is a horizontal
// line. We do this by incrementally building a new tree of layout data in
// traversal order of the game tree, satisfying the following constraints at
// each step:
// 1) A newly inserted node's y coordinate is greater than all other nodes
// at the same depth. This is enforced pre-traversal.
// 2) A newly inserted node's y coordinate is greater or equal to the y
// coordinate of its first child. This is enforced post-traversal.
let traverse = (node: Node, depth: number) => {
// Tell the compiler that node.parent is guaranteed to be non-null.
let parent = node.parent as Node;
// Satisfy constraint 1. In order to make the layout less cramped, we
// actually check both the current depth and the next depth.
node.y = parent.y;
for (let i = 0; i < 2 && depth + i < bottomNode.length; ++i) {
node.y = Math.max(node.y, bottomNode[depth + i].y + SPACE);
}
bottomNode[depth] = node;
for (let child of node.children) {
traverse(child, depth + 1);
}
// Satisfy constraint 2.
if (node == parent.children[0]) {
parent.y = Math.max(parent.y, node.y);
}
this.maxX = Math.max(this.maxX, node.x);
this.maxY = Math.max(this.maxY, node.y);
};
// Traverse the root node's children: the root node doesn't need laying
// out and this guarantees that all traversed nodes have parents.
for (let child of this.rootNode.children) {
traverse(child, 1);
}
}
private resizeCanvas() {
let pr = pixelRatio();
let canvas = this.ctx.canvas;
let parent = canvas.parentElement as HTMLElement;
this.width = parent.offsetWidth;
this.height = parent.offsetHeight;
canvas.width = pr * this.width;
canvas.height = pr * this.height;
canvas.style.width = `${this.width}px`;
canvas.style.height = `${this.height}px`;
}
}
export {
VariationTree,
} | the_stack |
declare namespace GoogleAdsScripts {
namespace AdsApp {
/** Represents a Google Ads ad group. */
interface AdGroup extends Base.StatsFor {
/** Creates a selector of all ad params in the ad group. */
adParams(): AdParamSelector;
/** Adds a callout to this ad group. */
addCallout(calloutExtension: Callout): CalloutOperation;
/** Adds a message to this ad group. */
addMessage(messageExtension: Message): MessageOperation;
/** Adds a mobile app to this ad group. */
addMobileApp(mobileAppExtension: MobileApp): MobileAppOperation;
/** Adds a phone number to this ad group. */
addPhoneNumber(phoneNumberExtension: PhoneNumber): PhoneNumberOperation;
/** Adds a price extension to this ad group. */
addPrice(priceExtension: Price): PriceOperation;
/** Adds a sitelink to this ad group. */
addSitelink(sitelinkExtension: Sitelink): SitelinkOperation;
/** Adds a snippet to this ad group. */
addSnippet(snippetExtension: Snippet): SnippetOperation;
/** Returns the selector of all ads in the ad group. */
ads(): AdSelector;
/** Applies a label to the ad group. */
applyLabel(name: string): void;
/** Provides access to this ad group's bidding fields. */
bidding(): AdGroupBidding;
/**
* Clears the mobile bid modifier for this ad group.
*
* @deprecated **Deprecated**. Google Ads Scripts now supports desktop and tablet ad group bid modifiers in addition to mobile.
* This functionality is available in the AdGroupDevices class, accessible via the AdGroup.devices method.
*/
clearMobileBidModifier(): void;
/** Creates a new negative keyword with the specified text. */
createNegativeKeyword(keywordText: string): void;
/** Returns an AdGroupDevices instance associated with the ad group. */
devices(): AdGroupDevices;
/**
* Provides access to this ad group's display criteria: Audience, ExcludedAudience, DisplayKeyword, ExcludedDisplayKeyword, Placement, ExcludedPlacement,
* Topic, and ExcludedTopic.
*/
display(): AdGroupDisplay;
/** Enables the ad group. */
enable(): void;
/** Provides access to this ad group's extensions: AdGroupCallout, AdGroupMessage, AdGroupMobileApp, AdGroupPhoneNumber, AdGroupSitelink, and AdGroupSnippet. */
extensions(): AdGroupExtensions;
/** Returns the base ad group to which this ad group belongs. */
getBaseAdGroup(): AdGroup;
/** Returns the base campaign to which this ad group belongs. */
getBaseCampaign(): Campaign;
/** Returns the campaign to which this ad group belongs or null if it does not belong to a search or display campaign. */
getCampaign(): Campaign;
/** Returns the type of this entity as a String, in this case, "AdGroup". */
getEntityType(): string;
/** Returns the ID of the ad group. */
getId(): number;
/**
* Returns the mobile bid modifier for this ad group.
*
* **Deprecated**. Google Ads Scripts now supports desktop and tablet ad group bid modifiers in addition to mobile.
* This functionality is available in the AdGroupDevices class, accessible via the AdGroup.devices method.
*/
getMobileBidModifier(): number;
/** Returns the name of the ad group. */
getName(): string;
/** Returns true if the ad group is enabled. */
isEnabled(): boolean;
/** Returns true if the ad group is paused. */
isPaused(): boolean;
/** Returns true if the ad group is removed. */
isRemoved(): boolean;
/** Returns the selector of all keywords in the ad group. */
keywords(): KeywordSelector;
/** Creates a selector of all labels applied to the ad group. */
labels(): LabelSelector;
/** Returns a selector of all negative keywords in the ad group. */
negativeKeywords(): NegativeKeywordSelector;
/** Returns a new ad builder space associated with this ad group. */
newAd(): AdBuilderSpace;
/** Returns a new keyword builder associated with this ad group. */
newKeywordBuilder(): KeywordBuilder;
/** Pauses the ad group. */
pause(): void;
/** Removes a callout extension from this ad group. */
removeCallout(calloutExtension: Callout): void;
/** Removes a label from the ad group. */
removeLabel(name: string): void;
/** Removes a message extension from this ad group. */
removeMessage(messageExtension: Message): void;
/** Removes a mobile app extension from this ad group. */
removeMobileApp(mobileAppExtension: MobileApp): void;
/** Removes a phone number extension from this ad group. */
removePhoneNumber(phoneNumberExtension: PhoneNumber): void;
/** Removes a price extension from this ad group. */
removePrice(priceExtension: Price): void;
/** Removes a sitelink extension from this ad group. */
removeSitelink(sitelinkExtension: Sitelink): void;
/** Removes a snippet extension from this ad group. */
removeSnippet(snippetExtension: Snippet): void;
/**
* Sets the mobile bid modifier for this ad group to the specified value.
*
* @deprecated **Deprecated**. Google Ads Scripts now supports desktop and tablet ad group bid modifiers in addition to mobile.
* This functionality is available in the AdGroupDevices class, accessible via the AdGroup.devices method.
*/
setMobileBidModifier(modifier: number): void;
/** Sets the name of the ad group. */
setName(name: string): void;
/** Provides access to ad group-level targeting criteria: audiences. */
targeting(): AdGroupTargeting;
/** Provides access to this ad group's URL fields. */
urls(): AdGroupUrls;
}
/** Provides access to an AdGroup's bidding fields. */
interface AdGroupBidding {
/** Returns the Target CPA bid for this ad group. */
getCpa(): number;
/** Returns the max CPC bid for this ad group. */
getCpc(): number;
/** Returns the CPM bid for this ad group. */
getCpm(): number;
/** Returns the flexible bidding strategy of the ad group. */
getStrategy(): BiddingStrategy;
/** Returns the bidding strategy source of this ad group. */
getStrategySource(): string;
/** Returns the bidding strategy type of this ad group. */
getStrategyType(): string;
/** Sets the Target CPA bid for this ad group. */
setCpa(cpa: number): void;
/** Sets the max CPC bid for this ad group. */
setCpc(cpc: number): void;
/** Sets the CPM bid for this ad group. */
setCpm(cpm: number): void;
}
/**
* Builder for an ad group under construction.
*
* Typical usage:
*
* var adGroupBuilder = campaign.newAdGroupBuilder();
* var adGroupOperation = adGroupBuilder
* .withName("ad group name")
* .withStatus("PAUSED")
* .build();
* var adGroup = adGroupOperation.getResult();
*/
interface AdGroupBuilder extends Base.Builder<AdGroupOperation> {
/** Sets the Target CPA bid of the new ad group to the specified value. */
withCpa(cpa: number): this;
/** Sets the max CPC bid of the new ad group to the specified value. */
withCpc(cpc: number): this;
/** Sets the CPM bid of the new ad group to the specified value. */
withCpm(cpm: number): this;
/** Sets the custom parameters of the new ad group to the specified value. */
withCustomParameters(customParameters: Record<string, string>): this;
/** Sets the final URL suffix of the new ad group to the specified value. */
withFinalUrlSuffix(suffix: string): this;
/** Sets the name of the new ad group to the specified value. */
withName(name: string): this;
/** Sets the status of the new ad group to the specified value. */
withStatus(status: string): this;
/** Sets the tracking template of the new ad group to the specified value. */
withTrackingTemplate(trackingTemplate: string): this;
}
/** Starting point for device-dependent ad group configurations. */
interface AdGroupDevices {
/** Clears the desktop bid modifier for this ad group. */
clearDesktopBidModifier(): void;
/** Clears the mobile bid modifier for this ad group. */
clearMobileBidModifier(): void;
/** Clears the tablet bid modifier for this ad group. */
clearTabletBidModifier(): void;
/** Returns the desktop bid modifier for this ad group. */
getDesktopBidModifier(): number;
/** Returns the mobile bid modifier for this ad group. */
getMobileBidModifier(): number;
/** Returns the tablet bid modifier for this ad group. */
getTabletBidModifier(): number;
/** Sets the desktop bid modifier for this ad group to the specified value. */
setDesktopBidModifier(modifier: number): void;
/** Sets the mobile bid modifier for this ad group to the specified value. */
setMobileBidModifier(modifier: number): void;
/** Sets the tablet bid modifier for this ad group to the specified value. */
setTabletBidModifier(modifier: number): void;
}
/**
* An iterator of ad groups.
*
* Typical usage:
*
* while (adGroupIterator.hasNext()) {
* var adGroup = adGroupIterator.next();
* }
*/
interface AdGroupIterator extends Base.Iterator<AdGroup> {}
/**
* An operation representing creation of a new ad group
*/
interface AdGroupOperation extends Base.Operation<AdGroup> {}
/**
* Fetches ad groups. Supports filtering and sorting.
*
* Typical usage:
*
* var adGroupSelector = AdsApp
* .adGroups()
* .withCondition("Impressions > 100")
* .forDateRange("LAST_MONTH")
* .orderBy("Clicks DESC");
*
* var adGroupIterator = adGroupSelector.get();
* while (adGroupIterator.hasNext()) {
* var adGroup = adGroupIterator.next();
* }
*/
interface AdGroupSelector
extends Base.Selector<AdGroupIterator>,
Base.SelectorForDateRange,
Base.SelectorOrderBy,
Base.SelectorWithCondition,
Base.SelectorWithIds,
Base.SelectorWithLimit {}
/** Provides access to ad group-level targeting criteria: audiences. */
interface AdGroupTargeting {
/** Specializes this selector to return SearchAdGroupAudience criteria. */
audiences(): SearchAdGroupAudienceSelector;
/** Specializes this selector to return SearchAdGroupExcludedAudience criteria. */
excludedAudiences(): SearchAdGroupExcludedAudienceSelector;
/** Returns the current targeting setting of the specified criterion type group for this ad group. */
getTargetingSetting(): string;
/** Returns a new user list builder for this ad group. */
newUserListBuilder(): SearchAdGroupAudienceBuilder;
/** Sets the targeting setting for this ad group. */
setTargetingSetting(criterionTypeGroup: string, targetingSetting: string): void;
}
/** Provides access to ad group URLs. */
interface AdGroupUrls {
clearFinalUrlSuffix(): void;
clearTrackingTemplate(): void;
getCustomParameters(): Record<string, string>;
getFinalUrlSuffix(): string;
getTrackingTemplate(): string;
setCustomParameters(customParameters: Record<string, string>): void;
setFinalUrlSuffix(suffix: string): void;
setTrackingTemplate(trackingTemplate: string): void;
}
/** Provides access to ad group-level targeting criteria (currently just audiences). */
interface AccountAdGroupTargeting {
/** Specializes this selector to return SearchAdGroupAudience criteria. */
audiences(): SearchAdGroupAudienceSelector;
/** Specializes this selector to return SearchAdGroupExcludedAudience criteria. */
excludedAudiences(): SearchAdGroupExcludedAudienceSelector;
}
}
} | the_stack |
import {ObservableType, isObservable} from '@layr/observable';
import {useState, useEffect, useCallback, useRef, useMemo, DependencyList} from 'react';
import {AsyncFunction, getTypeOf} from 'core-helpers';
import {useCustomization, Customization} from './components';
/**
* A convenient hook for loading data asynchronously and render a React node once the data is loaded.
*
* The `getter()` asynchronous function is called when the React component is rendered for the first time or when a change is detected in its `dependencies`.
*
* While the `getter()` function is running, the `useData()` hook returns the result of the nearest `dataPlaceholder()` function.
*
* Once the `getter()` function is executed, the `useData()` hook returns the result of the `renderer()` function which is called with the result of the `getter()` function as first parameter.
*
* If an error occurs during the `getter()` function execution, the `useData()` hook returns the result of the nearest `errorRenderer()` function.
*
* @param getter An asynchronous function for loading data.
* @param renderer A function which is called with the result of the `getter()` function as first parameter and a `refresh()` function as second parameter. You can call the `refresh()` function to force the re-execution of the `getter()` function. The `renderer()` function should return a React node.
* @param [dependencies] An array of values on which the `getter()` function depends (default: `[]`).
* @param [options.dataPlaceholder] A custom `dataPlaceholder()` function.
* @param [options.errorRenderer] A custom `errorRenderer()` function.
*
* @returns A React node.
*
* @example
* ```
* import {Component} from '﹫layr/component';
* import {Storable} from '﹫layr/storable';
* import React from 'react';
* import {view, useData} from '﹫layr/react-integration';
*
* class Article extends Storable(Component) {
* // ...
*
* ﹫view() static List() {
* return useData(
* async () => {
* return await this.find();
* },
*
* (articles) => {
* return articles.map((article) => (
* <div key={article.id}>{article.title}</div>
* ));
* }
* );
* }
* }
* ```
*
* @category High-Level Hooks
* @reacthook
*/
export function useData<Result>(
getter: () => Promise<Result>,
renderer: (data: Result, refresh: () => void) => JSX.Element | null,
deps: DependencyList = [],
options: {
dataPlaceholder?: Customization['dataPlaceholder'];
errorRenderer?: Customization['errorRenderer'];
} = {}
) {
const {dataPlaceholder, errorRenderer} = {...useCustomization(), ...options};
const [data, isExecuting, error, refresh] = useAsyncMemo(getter, deps);
if (isExecuting) {
return dataPlaceholder();
}
if (error !== undefined) {
return errorRenderer(error);
}
return renderer(data!, refresh);
}
export function useAction<Args extends any[] = any[], Result = any>(
handler: AsyncFunction<Args, Result>,
deps: DependencyList = [],
options: {
actionWrapper?: Customization['actionWrapper'];
errorNotifier?: Customization['errorNotifier'];
} = {}
) {
const {actionWrapper, errorNotifier} = {...useCustomization(), ...options};
const action = useCallback(async (...args: Args) => {
try {
return (await actionWrapper(handler as (...args: any[]) => Promise<any>, args)) as Result;
} catch (error) {
await errorNotifier(error);
throw error;
}
}, deps);
return action;
}
/**
* Makes a view dependent of an [observable](https://layrjs.com/docs/v2/reference/observable#observable-type) so the view is automatically re-rendered when the observable changes.
*
* @param observable An [observable](https://layrjs.com/docs/v2/reference/observable#observable-type) object.
*
* @example
* ```
* import {Component} from '﹫layr/component';
* import {createObservable} from '﹫layr/observable';
* import React from 'react';
* import {view, useObserve} from '﹫layr/react-integration';
*
* const observableArray = createObservable([]);
*
* class MyComponent extends Component {
* ﹫view() static View() {
* useObserve(observableArray);
*
* return (
* <div>
* {`observableArray's length: ${observableArray.length}`}
* </div>
* );
* }
* }
*
* // Changing `observableArray` will re-render `MyComponent.View()`
* observableArray.push('abc');
* ```
*
* @category High-Level Hooks
* @reacthook
*/
export function useObserve(observable: ObservableType) {
if (!isObservable(observable)) {
throw new Error(
`Expected an observable class or instance, but received a value of type '${getTypeOf(
observable
)}'`
);
}
const forceUpdate = useForceUpdate();
useEffect(
function () {
observable.addObserver(forceUpdate);
return function () {
observable.removeObserver(forceUpdate);
};
},
[observable]
);
}
/**
* Allows you to define an asynchronous callback and keep track of its execution.
*
* Plays the same role as the React built-in [`useCallback()`](https://reactjs.org/docs/hooks-reference.html#usecallback) hook but works with asynchronous callbacks.
*
* @param asyncCallback An asynchronous callback.
* @param [dependencies] An array of values on which the asynchronous callback depends (default: `[]`).
*
* @returns An array of the shape `[trackedCallback, isExecuting, error, result]` where `trackedCallback` is a function that you can call to execute the asynchronous callback, `isExecuting` is a boolean indicating whether the asynchronous callback is being executed, `error` is the error thrown by the asynchronous callback in case of failed execution, and `result` is the value returned by the asynchronous callback in case of succeeded execution.
*
* @example
* ```
* import {Component} from '﹫layr/component';
* import React from 'react';
* import {view, useAsyncCallback} from '﹫layr/react-integration';
*
* class Article extends Component {
* ﹫view() UpvoteButton() {
* const [handleUpvote, isUpvoting, upvotingError] = useAsyncCallback(async () => {
* await this.upvote();
* });
*
* return (
* <div>
* <button onClick={handleUpvote} disabled={isUpvoting}>Upvote</button>
* {upvotingError && ' An error occurred while upvoting the article.'}
* </div>
* );
* }
* }
* ```
*
* @category Low-Level Hooks
* @reacthook
*/
export function useAsyncCallback<Args extends any[] = any[], Result = any>(
asyncCallback: AsyncFunction<Args, Result>,
deps: DependencyList = []
) {
const [state, setState] = useState<{isExecuting?: boolean; error?: any; result?: Result}>({});
const isMounted = useIsMounted();
const trackedCallback = useCallback(
async (...args: Args) => {
setState({isExecuting: true});
try {
const result = await asyncCallback(...args);
if (isMounted()) {
setState({result});
}
return result;
} catch (error) {
if (isMounted()) {
setState({error});
}
throw error;
}
},
[...deps]
);
return [trackedCallback, state.isExecuting === true, state.error, state.result] as const;
}
/**
* Memoizes the result of an asynchronous function execution and provides a "recompute function" that you can call to recompute the memoized result.
*
* The asynchronous function is executed one time when the React component is rendered for the first time, and each time a dependency is changed or the "recompute function" is called.
*
* Plays the same role as the React built-in [`useMemo()`](https://reactjs.org/docs/hooks-reference.html#usememo) hook but works with asynchronous functions and allows to recompute the memoized result.
*
* @param asyncFunc An asynchronous function to compute the memoized result.
* @param [dependencies] An array of values on which the memoized result depends (default: `[]`, which means that the memoized result will be recomputed only when the "recompute function" is called).
*
* @returns An array of the shape `[memoizedResult, isExecuting, error, recompute]` where `memoizedResult` is the result returned by the asynchronous function in case of succeeded execution, `isExecuting` is a boolean indicating whether the asynchronous function is being executed, `error` is the error thrown by the asynchronous function in case of failed execution, and `recompute` is a function that you can call to recompute the memoized result.
*
* @example
* ```
* import {Component} from '﹫layr/component';
* import {Storable} from '﹫layr/storable';
* import React from 'react';
* import {view, useAsyncMemo} from '﹫layr/react-integration';
*
* class Article extends Storable(Component) {
* // ...
*
* ﹫view() static List() {
* const [articles, isLoading, loadingError, retryLoading] = useAsyncMemo(
* async () => {
* return await this.find();
* }
* );
*
* if (isLoading) {
* return <div>Loading the articles...</div>;
* }
*
* if (loadingError) {
* return (
* <div>
* An error occurred while loading the articles.
* <button onClick={retryLoading}>Retry</button>
* </div>
* );
* }
*
* return articles.map((article) => (
* <div key={article.id}>{article.title}</div>
* ));
* }
* }
* ```
*
* @category Low-Level Hooks
* @reacthook
*/
export function useAsyncMemo<Result>(asyncFunc: () => Promise<Result>, deps: DependencyList = []) {
const [state, setState] = useState<{
result?: Result;
isExecuting?: boolean;
error?: any;
}>({isExecuting: true});
const [recomputeCount, setRecomputeCount] = useState(0);
const isMounted = useIsMounted();
useEffect(() => {
setState({isExecuting: true});
asyncFunc().then(
(result) => {
if (isMounted()) {
setState({result});
}
return result;
},
(error) => {
if (isMounted()) {
setState({error});
}
throw error;
}
);
}, [...deps, recomputeCount]);
const recompute = useCallback(() => {
setState({isExecuting: true});
setRecomputeCount((recomputeCount) => recomputeCount + 1);
}, []);
return [state.result, state.isExecuting === true, state.error, recompute] as const;
}
/**
* Memoizes the result of a function execution and provides a "recompute function" that you can call to recompute the memoized result.
*
* The function is executed one time when the React component is rendered for the first time, and each time a dependency is changed or the "recompute function" is called.
*
* Plays the same role as the React built-in [`useMemo()`](https://reactjs.org/docs/hooks-reference.html#usememo) hook but with the extra ability to recompute the memoized result.
*
* @param func A function to compute the memoized result.
* @param [dependencies] An array of values on which the memoized result depends (default: `[]`, which means that the memoized result will be recomputed only when the "recompute function" is called).
*
* @returns An array of the shape `[memoizedResult, recompute]` where `memoizedResult` is the result of the function execution, and `recompute` is a function that you can call to recompute the memoized result.
*
* @example
* ```
* import {Component, provide} from '﹫layr/component';
* import {Storable} from '﹫layr/storable';
* import React, {useCallback} from 'react';
* import {view, useRecomputableMemo} from '﹫layr/react-integration';
*
* class Article extends Storable(Component) {
* // ...
* }
*
* class Blog extends Component {
* ﹫provide() static Article = Article;
*
* ﹫view() static ArticleCreator() {
* const [article, resetArticle] = useRecomputableMemo(() => new Article());
*
* const createArticle = useCallback(async () => {
* await article.save();
* resetArticle();
* }, [article]);
*
* return (
* <div>
* <article.CreateForm onSubmit={createArticle} />
* </div>
* );
* }
* }
* ```
*
* @category Low-Level Hooks
* @reacthook
*/
export function useRecomputableMemo<Result>(func: () => Result, deps: DependencyList = []) {
const [recomputeCount, setRecomputeCount] = useState(0);
const result = useMemo(func, [...deps, recomputeCount]);
const recompute = useCallback(() => {
setRecomputeCount((recomputeCount) => recomputeCount + 1);
}, []);
return [result, recompute] as const;
}
/**
* Allows you to call an asynchronous function and keep track of its execution.
*
* The function is executed one time when the React component is rendered for the first time, and each time a dependency is changed or the "recall function" is called.
*
* @param asyncFunc The asynchronous function to call.
* @param [dependencies] An array of values on which the asynchronous function depends (default: `[]`, which means that the asynchronous will be recalled only when the "recall function" is called).
*
* @returns An array of the shape `[isExecuting, error, recall]` where `isExecuting` is a boolean indicating whether the asynchronous function is being executed, `error` is the error thrown by the asynchronous function in case of failed execution, and `recall` is a function that you can call to recall the asynchronous function.
*
* @example
* ```
* // JS
*
* import {Component, provide, attribute} from '﹫layr/component';
* import {Storable} from '﹫layr/storable';
* import React from 'react';
* import {view, useAsyncCall} from '﹫layr/react-integration';
*
* class Article extends Storable(Component) {
* // ...
* }
*
* class Blog extends Component {
* ﹫provide() static Article = Article;
*
* ﹫attribute('Article[]?') static loadedArticles;
*
* ﹫view() static View() {
* const [isLoading, loadingError, retryLoading] = useAsyncCall(
* async () => {
* this.loadedArticles = await this.Article.find();
* }
* );
*
* if (isLoading) {
* return <div>Loading the articles...</div>;
* }
*
* if (loadingError) {
* return (
* <div>
* An error occurred while loading the articles.
* <button onClick={retryLoading}>Retry</button>
* </div>
* );
* }
*
* return this.loadedArticles.map((article) => (
* <div key={article.id}>{article.title}</div>
* ));
* }
* }
* ```
*
* @example
* ```
* // TS
*
* import {Component, provide, attribute} from '﹫layr/component';
* import {Storable} from '﹫layr/storable';
* import React from 'react';
* import {view, useAsyncCall} from '﹫layr/react-integration';
*
* class Article extends Storable(Component) {
* // ...
* }
*
* class Blog extends Component {
* ﹫provide() static Article = Article;
*
* ﹫attribute('Article[]?') static loadedArticles?: Article[];
*
* ﹫view() static View() {
* const [isLoading, loadingError, retryLoading] = useAsyncCall(
* async () => {
* this.loadedArticles = await this.Article.find();
* }
* );
*
* if (isLoading) {
* return <div>Loading the articles...</div>;
* }
*
* if (loadingError) {
* return (
* <div>
* An error occurred while loading the articles.
* <button onClick={retryLoading}>Retry</button>
* </div>
* );
* }
*
* return this.loadedArticles!.map((article) => (
* <div key={article.id}>{article.title}</div>
* ));
* }
* }
* ```
*
* @category Low-Level Hooks
* @reacthook
*/
export function useAsyncCall(asyncFunc: () => Promise<void>, deps: DependencyList = []) {
const [, isExecuting, error, recall] = useAsyncMemo(asyncFunc, deps);
return [isExecuting, error, recall] as const;
}
export function useIsMounted() {
const isMountedRef = useRef(false);
const isMounted = useCallback(() => {
return isMountedRef.current;
}, []);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
return isMounted;
}
export function useForceUpdate() {
const [, setState] = useState({});
const isMounted = useIsMounted();
const forceUpdate = useCallback(() => {
if (isMounted()) {
setState({});
}
}, []);
return forceUpdate;
}
export function useDelay(duration = 100) {
const [isElapsed, setIsElapsed] = useState(false);
useEffect(() => {
const timeout = setTimeout(() => {
setIsElapsed(true);
}, duration);
return () => {
clearTimeout(timeout);
};
}, []);
return [isElapsed] as const;
} | the_stack |
import { CoreConnection } from '../index'
import { PeripheralDeviceAPI as P, PeripheralDeviceAPI } from '../lib/corePeripherals'
import * as _ from 'underscore'
import { DDPConnectorOptions } from '../lib/ddpClient'
jest.mock('faye-websocket')
jest.mock('got')
process.on('unhandledRejection', (reason) => {
console.log('Unhandled Promise rejection!', reason)
})
const orgSetTimeout = setTimeout
describe('coreConnection', () => {
const coreHost = '127.0.0.1'
const corePort = 3000
function wait (time: number): Promise<void> {
return new Promise((resolve) => {
orgSetTimeout(() => {
resolve()
}, time)
})
}
test('Just setup CoreConnection', async () => {
let core = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onConnectionChanged = jest.fn()
let onConnected = jest.fn()
let onDisconnected = jest.fn()
core.onConnectionChanged(onConnectionChanged)
core.onConnected(onConnected)
core.onDisconnected(onDisconnected)
expect(core.connected).toEqual(false)
})
test('Test connection and basic Core functionality', async () => {
let core = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onConnectionChanged = jest.fn()
let onConnected = jest.fn()
let onDisconnected = jest.fn()
let onError = jest.fn()
core.onConnectionChanged(onConnectionChanged)
core.onConnected(onConnected)
core.onDisconnected(onDisconnected)
core.onError(onError)
expect(core.connected).toEqual(false)
// Initiate connection to Core:
let id = await core.init({
host: coreHost,
port: corePort
})
expect(core.connected).toEqual(true)
expect(id).toEqual(core.deviceId)
expect(onConnectionChanged).toHaveBeenCalledTimes(1)
expect(onConnectionChanged.mock.calls[0][0]).toEqual(true)
expect(onConnected).toHaveBeenCalledTimes(1)
expect(onDisconnected).toHaveBeenCalledTimes(0)
// Set some statuses:
let statusResponse = await core.setStatus({
statusCode: P.StatusCode.WARNING_MAJOR,
messages: ['testing testing']
})
expect(statusResponse).toMatchObject({
statusCode: P.StatusCode.WARNING_MAJOR
})
statusResponse = await core.setStatus({
statusCode: P.StatusCode.GOOD
})
expect(statusResponse).toMatchObject({
statusCode: P.StatusCode.GOOD
})
// Observe data:
let observer = core.observe('peripheralDevices')
observer.added = jest.fn()
observer.changed = jest.fn()
observer.removed = jest.fn()
// Subscribe to data:
let coll0 = core.getCollection('peripheralDevices')
expect(coll0.findOne({ _id: id })).toBeFalsy()
let subId = await core.subscribe('peripheralDevices', {
_id: id
})
let coll1 = core.getCollection('peripheralDevices')
expect(coll1.findOne({ _id: id })).toMatchObject({
_id: id
})
expect(observer.added).toHaveBeenCalledTimes(1)
// Call a method
await expect(core.callMethod('peripheralDevice.testMethod', ['return123'])).resolves.toEqual('return123')
// Call a method which will throw error:
await expect(core.callMethod('peripheralDevice.testMethod', ['abcd', true])).rejects.toMatchObject({
error: 418,
reason: /error/
})
// Call an unknown method
await expect(core.callMethod('myunknownMethod123', ['a', 'b'])).rejects.toMatchObject({
error: 404,
reason: /error/
})
// Unsubscribe:
core.unsubscribe(subId)
await wait(200) // wait for unsubscription to go through
expect(observer.removed).toHaveBeenCalledTimes(1)
// Uninitialize
id = await core.unInitialize()
expect(id).toEqual(core.deviceId)
// Set the status now (should cause an error)
await expect(core.setStatus({
statusCode: P.StatusCode.GOOD
})).rejects.toMatchObject({
error: 404
})
expect(onConnectionChanged).toHaveBeenCalledTimes(1)
// Close connection:
await core.destroy()
expect(core.connected).toEqual(false)
expect(onConnectionChanged).toHaveBeenCalledTimes(2)
expect(onConnectionChanged.mock.calls[1][0]).toEqual(false)
expect(onConnected).toHaveBeenCalledTimes(1)
expect(onDisconnected).toHaveBeenCalledTimes(1)
expect(onError).toHaveBeenCalledTimes(0)
})
test('Connection timeout', async () => {
let core = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onConnectionChanged = jest.fn()
let onConnected = jest.fn()
let onDisconnected = jest.fn()
let onFailed = jest.fn()
let onError = jest.fn()
core.onConnectionChanged(onConnectionChanged)
core.onConnected(onConnected)
core.onDisconnected(onDisconnected)
core.onFailed(onFailed)
core.onError(onError)
expect(core.connected).toEqual(false)
// Initiate connection to Core:
let err = null
try {
await core.init({
host: '127.0.0.999',
port: corePort
})
} catch (e) {
err = e
}
expect(err.message).toMatch(/Network error/)
expect(core.connected).toEqual(false)
await core.destroy()
})
test('Connection recover from close', async () => {
let core = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onConnectionChanged = jest.fn()
let onConnected = jest.fn()
let onDisconnected = jest.fn()
let onFailed = jest.fn()
let onError = jest.fn()
core.onConnectionChanged(onConnectionChanged)
core.onConnected(onConnected)
core.onDisconnected(onDisconnected)
core.onFailed(onFailed)
core.onError(onError)
expect(core.connected).toEqual(false)
// Initiate connection to Core:
await core.init({
host: coreHost,
port: corePort
})
expect(core.connected).toEqual(true)
// Force-close the socket:
core.ddp.ddpClient && core.ddp.ddpClient.socket.close()
await wait(10)
expect(core.connected).toEqual(false)
await wait(1300)
// should have reconnected by now
expect(core.connected).toEqual(true)
await core.destroy()
})
test('autoSubscription', async () => {
let core = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onConnectionChanged = jest.fn()
let onConnected = jest.fn()
let onDisconnected = jest.fn()
let onFailed = jest.fn()
let onError = jest.fn()
core.onConnectionChanged(onConnectionChanged)
core.onConnected(onConnected)
core.onDisconnected(onDisconnected)
core.onFailed(onFailed)
core.onError(onError)
expect(core.connected).toEqual(false)
// Initiate connection to Core:
await core.init({
host: coreHost,
port: corePort
})
expect(core.connected).toEqual(true)
let observerAdded = jest.fn()
let observerChanged = jest.fn()
let observerRemoved = jest.fn()
let observer = core.observe('peripheralDevices')
observer.added = observerAdded
observer.changed = observerChanged
observer.removed = observerRemoved
await core.autoSubscribe('peripheralDevices', { _id: 'JestTest' })
expect(observerAdded).toHaveBeenCalledTimes(1)
await core.setStatus({
statusCode: PeripheralDeviceAPI.StatusCode.GOOD,
messages: ['Jest A ' + Date.now()]
})
await wait(300)
expect(observerChanged).toHaveBeenCalledTimes(1)
// Force-close the socket:
core.ddp.ddpClient && core.ddp.ddpClient.socket.close()
await wait(10)
expect(core.connected).toEqual(false)
await wait(1300)
// should have reconnected by now
expect(core.connected).toEqual(true)
observerChanged.mockClear()
await core.setStatus({
statusCode: PeripheralDeviceAPI.StatusCode.GOOD,
messages: ['Jest B' + Date.now()]
})
await wait(300)
expect(observerChanged).toHaveBeenCalledTimes(1)
await core.destroy()
})
test('Connection recover from a close that lasts some time', async () => {
let core = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onConnectionChanged = jest.fn()
let onConnected = jest.fn()
let onDisconnected = jest.fn()
let onFailed = jest.fn()
let onError = jest.fn()
core.onConnectionChanged(onConnectionChanged)
core.onConnected(onConnected)
core.onDisconnected(onDisconnected)
core.onFailed(onFailed)
core.onError(onError)
expect(core.connected).toEqual(false)
// Initiate connection to Core:
let options: DDPConnectorOptions = {
host: coreHost,
port: corePort,
autoReconnect: true,
autoReconnectTimer: 100
}
await core.init(options)
expect(core.connected).toEqual(true)
// temporary scramble the ddp host:
options.host = '127.0.0.9'
core.ddp.ddpClient && core.ddp.ddpClient.resetOptions(options)
// Force-close the socket:
core.ddp.ddpClient && core.ddp.ddpClient.socket.close()
await wait(10)
expect(core.connected).toEqual(false)
await wait(1000) // allow for some reconnections
// restore ddp host:
options.host = '127.0.0.1'
core.ddp.ddpClient && core.ddp.ddpClient.resetOptions(options)
await wait(1000)
// should have reconnected by now
expect(core.connected).toEqual(true)
await core.destroy()
})
test('Parent connections', async () => {
let coreParent = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onError = jest.fn()
coreParent.onError(onError)
let parentOnConnectionChanged = jest.fn()
coreParent.onConnectionChanged(parentOnConnectionChanged)
let id = await coreParent.init({
host: coreHost,
port: corePort
})
expect(coreParent.connected).toEqual(true)
// Set child connection:
let coreChild = new CoreConnection({
deviceId: 'JestTestChild',
deviceToken: 'abcd2',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework child'
})
let onChildConnectionChanged = jest.fn()
let onChildConnected = jest.fn()
let onChildDisconnected = jest.fn()
let onChildError = jest.fn()
coreChild.onConnectionChanged(onChildConnectionChanged)
coreChild.onConnected(onChildConnected)
coreChild.onDisconnected(onChildDisconnected)
coreChild.onError(onChildError)
let idChild = await coreChild.init(coreParent)
expect(idChild).toEqual(coreChild.deviceId)
expect(coreChild.connected).toEqual(true)
expect(onChildConnectionChanged).toHaveBeenCalledTimes(1)
expect(onChildConnectionChanged.mock.calls[0][0]).toEqual(true)
expect(onChildConnected).toHaveBeenCalledTimes(1)
expect(onChildDisconnected).toHaveBeenCalledTimes(0)
// Set some statuses:
let statusResponse = await coreChild.setStatus({
statusCode: P.StatusCode.WARNING_MAJOR,
messages: ['testing testing']
})
expect(statusResponse).toMatchObject({
statusCode: P.StatusCode.WARNING_MAJOR
})
statusResponse = await coreChild.setStatus({
statusCode: P.StatusCode.GOOD
})
expect(statusResponse).toMatchObject({
statusCode: P.StatusCode.GOOD
})
// Uninitialize:
id = await coreChild.unInitialize()
expect(id).toEqual(coreChild.deviceId)
// Set the status now (should cause an error)
await expect(coreChild.setStatus({
statusCode: P.StatusCode.GOOD
})).rejects.toMatchObject({
error: 404
})
await coreParent.destroy()
await coreChild.destroy()
expect(onError).toHaveBeenCalledTimes(0)
expect(onChildError).toHaveBeenCalledTimes(0)
})
test('Parent destroy', async () => {
let coreParent = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onParentError = jest.fn()
coreParent.onError(onParentError)
await coreParent.init({
host: coreHost,
port: corePort
})
// Set child connection:
let coreChild = new CoreConnection({
deviceId: 'JestTestChild',
deviceToken: 'abcd2',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: 'mos_connection',
deviceName: 'Jest test framework child'
})
let onChildConnectionChanged = jest.fn()
let onChildConnected = jest.fn()
let onChildDisconnected = jest.fn()
let onChildError = jest.fn()
coreChild.onConnectionChanged(onChildConnectionChanged)
coreChild.onConnected(onChildConnected)
coreChild.onDisconnected(onChildDisconnected)
coreChild.onError(onChildError)
await coreChild.init(coreParent)
expect(coreChild.connected).toEqual(true)
// Close parent connection:
await coreParent.destroy()
expect(coreChild.connected).toEqual(false)
expect(onChildConnectionChanged).toHaveBeenCalledTimes(2)
expect(onChildConnectionChanged.mock.calls[1][0]).toEqual(false)
expect(onChildConnected).toHaveBeenCalledTimes(1)
expect(onChildDisconnected).toHaveBeenCalledTimes(1)
// Setup stuff again
onChildConnectionChanged.mockClear()
onChildConnected.mockClear()
onChildDisconnected.mockClear()
coreChild.onConnectionChanged(onChildConnectionChanged)
coreChild.onConnected(onChildConnected)
coreChild.onDisconnected(onChildDisconnected)
// connect parent again:
await coreParent.init({
host: coreHost,
port: corePort
})
await coreChild.init(coreParent)
expect(coreChild.connected).toEqual(true)
expect(onChildConnected).toHaveBeenCalledTimes(1)
expect(onChildConnectionChanged).toHaveBeenCalledTimes(1)
expect(onChildConnectionChanged.mock.calls[0][0]).toEqual(true)
expect(onChildDisconnected).toHaveBeenCalledTimes(0)
await coreParent.destroy()
await coreChild.destroy()
expect(onChildError).toHaveBeenCalledTimes(0)
expect(onParentError).toHaveBeenCalledTimes(0)
})
test('Child destroy', async () => {
let coreParent = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onParentError = jest.fn()
coreParent.onError(onParentError)
await coreParent.init({
host: coreHost,
port: corePort
})
// Set child connection:
let coreChild = new CoreConnection({
deviceId: 'JestTestChild',
deviceToken: 'abcd2',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: 'mos_connection',
deviceName: 'Jest test framework child'
})
let onChildConnectionChanged = jest.fn()
let onChildConnected = jest.fn()
let onChildDisconnected = jest.fn()
let onChildError = jest.fn()
coreChild.onConnectionChanged(onChildConnectionChanged)
coreChild.onConnected(onChildConnected)
coreChild.onDisconnected(onChildDisconnected)
coreChild.onError(onChildError)
await coreChild.init(coreParent)
expect(coreChild.connected).toEqual(true)
// Close parent connection:
await coreChild.destroy()
expect(coreChild.connected).toEqual(false)
expect(onChildConnectionChanged).toHaveBeenCalledTimes(2)
expect(onChildConnectionChanged.mock.calls[1][0]).toEqual(false)
expect(onChildConnected).toHaveBeenCalledTimes(1)
expect(onChildDisconnected).toHaveBeenCalledTimes(1)
await coreParent.destroy()
expect(onParentError).toHaveBeenCalledTimes(0)
expect(onChildError).toHaveBeenCalledTimes(0)
})
test('Test callMethodLowPrio', async () => {
let core = new CoreConnection({
deviceId: 'JestTest',
deviceToken: 'abcd',
deviceCategory: P.DeviceCategory.PLAYOUT,
deviceType: P.DeviceType.PLAYOUT,
deviceSubType: P.SUBTYPE_PROCESS,
deviceName: 'Jest test framework'
})
let onError = jest.fn()
core.onError(onError)
await core.init({
host: coreHost,
port: corePort
})
expect(core.connected).toEqual(true)
// Call a method
await expect(core.callMethod('peripheralDevice.testMethod', ['return123'])).resolves.toEqual('return123')
// Call a low-prio method
await expect(core.callMethodLowPrio('peripheralDevice.testMethod', ['low123'])).resolves.toEqual('low123')
let ps: Promise<any>[] = []
// method should be called before low-prio:
let i = 0
ps.push(core.callMethodLowPrio('peripheralDevice.testMethod', ['low1'])
.then((res) => {
expect(res).toEqual('low1')
return i++
}))
ps.push(core.callMethodLowPrio('peripheralDevice.testMethod', ['low2'])
.then((res) => {
expect(res).toEqual('low2')
return i++
}))
ps.push(core.callMethod('peripheralDevice.testMethod', ['normal1'])
.then((res) => {
expect(res).toEqual('normal1')
return i++
}))
let r = await Promise.all(ps)
expect(r[0]).toBeGreaterThan(r[2]) // because callMethod should have run before callMethodLowPrio
expect(r[1]).toBeGreaterThan(r[2]) // because callMethod should have run before callMethodLowPrio
// Clean up
await core.destroy()
expect(onError).toHaveBeenCalledTimes(0)
})
}) | the_stack |
declare module JQuerySPServices {
interface SPServicesOptions {
/** If true, we'll cache the XML results with jQuery's .data() function */
cacheXML?: boolean;
/** The Web Service operation */
operation: string;
/** URL of the target Web */
webURL?: string;
/** true to make the view the default view for the list */
makeViewDefault?: boolean;
// For operations requiring CAML, these options will override any abstractions
/** View name in CAML format. */
viewName?: string;
/** Query in CAML format */
CAMLQuery?: string;
/** View fields in CAML format */
CAMLViewFields?: string;
/** Row limit as a string representation of an integer */
CAMLRowLimit?: number;
/** Query options in CAML format */
CAMLQueryOptions?: string;
// Abstractions for CAML syntax
/** Method Cmd for UpdateListItems */
batchCmd?: string;
/** Fieldname / Fieldvalue pairs for UpdateListItems */
valuepairs?: [string, any][];
// As of v0.7.1, removed all options which were assigned an empty string ("")
/** Array of destination URLs for copy operations */
DestinationUrls?: string[];
/** An SPWebServiceBehavior indicating whether the client supports Windows SharePoint Services 2.0 or Windows SharePoint Services 3.0: {Version2 | Version3 } */
behavior?: string;
/** A Storage value indicating how the Web Part is stored: {None | Personal | Shared} */
storage?: string;
/** objectType for operations which require it */
objectType?: string;
/** true to delete a meeting;false to remove its association with a Meeting Workspace site */
cancelMeeting?: boolean;
/** true if the calendar is set to a format other than Gregorian;otherwise, false. */
nonGregorian?: boolean;
/** Specifies if the action is a claim or a release. Specifies true for a claim and false for a release. */
fClaim?: boolean;
/** The recurrence ID for the meeting that needs its association removed. This parameter can be set to 0 for single-instance meetings. */
recurrenceId?: number;
/** An integer that is used to determine the ordering of updates in case they arrive out of sequence. Updates with a lower-than-current sequence are discarded. If the sequence is equal to the current sequence, the latest update are applied. */
sequence?: number;
/** SocialDataService maximumItemsToReturn */
maximumItemsToReturn?: number;
/** SocialDataService startIndex */
startIndex?: number;
/** SocialDataService isHighPriority */
isHighPriority?: boolean;
/** SocialDataService isPrivate */
isPrivate?: boolean;
/** SocialDataService rating */
rating?: number;
/** Unless otherwise specified, the maximum number of principals that can be returned from a provider is 10. */
maxResults?: number;
/** Specifies user scope and other information? [None | User | DistributionList | SecurityGroup | SharePointGroup | All] */
principalType?: string;
/** Allow the user to force async */
async?: boolean;
/** Function to call on completion */
completefunc?: (xData: JQueryXHR, status: string) => void;
// Additional options
// Alert Operations
/** Array of GUIDs for DeleteAlerts */
IDs?: string[];
// Authentication Operations
/** Username for Login operation. */
username?: string;
/** Password for Login operation. */
password?: string;
// Copy Operations
/** Source URL for copy operations. */
SourceUrl?: string;
/** Document information as a set of fields, from copy operations. */
Fields?: any;
/** A byte stream representing a document's binary data, from copy operations. */
Stream?: any;
/** An array of CopyResult objects, from copy operations. */
Results?: any;
/**
* Absolute URL for source document, for Copy.GetItem; or,
* a specified URL to query the GUID and URL of the site collection to which it belongs, for GetSiteUrl.
*/
Url?: string;
// Form Operations
/** Site-relative URL of the form to retrieve. */
formUrl?: string;
// List Operations
/** List name for operations involving SharePoint lists. */
listName?: string;
/** ID of a list item for operations involving list attachments. */
listItemID?: string;
/**
* Name of the file to add as an attachment, for operations involving list attachments; or,
* the site-relative location of the folder name and file name of the file whose versions are to be retrieved, restored, or deleted.
*/
fileName?: string;
/** Byte array that contains the file to attach by using base-64 encoding, for operations involving list attachments. */
attachment?: any;
/**
* The base64Binary content of the item to add to a discussion board; or,
* a string containing the message to display to the client, for SendClientScriptErrorReport.
*/
message?: string | any;
/**
* Description of the list, for operations that create new lists; or,
* of the Web to be created; or,
* of the group.
*/
description?: string;
/** A 32-bit integer that specifies the list template to use; for options, see the MSDN documentation for AddList. */
templateID?: number;
/** A System.Guid specifying the Feature ID. */
featureID?: string;
/** The full path to the document, for check-in, check-out, web, or web part operations. */
pageUrl?: string;
/** Optional check-in comments; or, the contents of a social comment. */
comment?: string;
/** In string form, any of the values 0, 1 or 2, where 0 = MinorCheckIn, 1 = MajorCheckIn, and 2 = OverwriteCheckIn, for CheckInItems. */
CheckinType?: string;
/** The content type ID of the list or site content type. */
contentTypeId?: string;
/** Either "true" or "false" in string form, designating whether the file is to be flagged as checked out for offline editing. */
checkoutToLocal?: string;
/**
* A string in RFC 1123 date format representing the date and time of the last modification to the file.
* @example "20 Jun 1982 12:00:00 GMT"
*/
lastModified?: string;
/** Display name of the list or site content type. */
displayName?: string;
/** The content type ID of the site content type on which to base the list or site content type. */
parentType?: string;
/**
* A string representing the collection of columns to include on the new site content type.
*
* Format the column collection as a FieldRefs element, where each FieldRef child element represents a reference to an existing column to include on the content type.
*/
fields?: string;
/**
* A string representing the properties to specify for the content type.
*
* Format the properties as a ContentType element, and include the element attributes for the properties you want to specify.
*/
contentTypeProperties?: string;
/** A string containing "true" or "false" that designates whether to add the content type to the list view. */
addToView?: string;
/**
* A string that contains the absolute URL of the Web to be created or deleted; or,
* associated with a social data element; or,
* for the attachment, as follows:
*
* @example http://Server_Name/Site_Name/Lists/List_Name/Attachments/Item_ID/FileName.
*/
url?: string;
/**
* The document URI specified in the XMLDocument element.
*
* Windows SharePoint Services uses this URI to identify the correct XMLDocument element to delete.
*/
documentUri?: string;
/**
* List item ID for list operations, when accessing a particular item on the list.
*
* GetAttachmentCollection uses a string; UpdateListItems uses a number.
*/
ID?: number | string;
/**
* A ViewFields element that specifies which fields to return in the query and in what order, and that can be assigned to a System.Xml.XmlNode object.
*
* @example
* <ViewFields><FieldRef Name="ID" />
* <FieldRef Name="Title" /></ViewFields>
*/
viewFields?: string;
/**
* A string that contains the date and time in Coordinated Universal Time (UTC) ISO8601 format from which to start retrieving changes in the
* list. The value of this parameter is typically retrieved from a prior SOAP response. If this value is null, the query returns all items in
* the list.
*/
since?: string;
/**
* A Contains element that defines custom filtering for the query and that can be assigned to a System.Xml.XmlNode object.
*
* This parameter can contain null.
*
* @example
* <Contains>
* <FieldRef Name="Status"/>
* <Value Type="Text">Complete</Value>
* </Contains>
*/
contains?: string;
/** A string that contains the change token for the request. If null is passed, all items in the list are returned. */
changeToken?: string;
/** A string that contains the ID of the list. */
strlistID?: string;
/** A string that contains the ID of the item. */
strlistItemID?: string;
/** A string that contains the name of the field. */
strFieldName?: string;
/**
* A string that represents the collection of columns to add to the list or site content type.
*
* Format the column collection as a FieldRefs element, where each FieldRef child element references a column to add to the list content type.
*/
newFields?: string;
/**
* A string that represents the collection of columns to update on the list or site content type.
*
* Format the column collection as a FieldRefs element, where each FieldRef references a column to update on the content type.
*
* In each FieldRef child element, include the element attributes for the column properties you want to update.
*/
updateFields?: string;
/**
* A string that represents the collection of columns to delete from the list or site content type.
*
* Format the column collection as a FieldRefs element, where each FieldRef references a column to delete from the content type.
*
* In each FieldRef child element, include the ID attributes for the column you want to delete.
*/
deleteFields?: string;
/** A string representing the XML document to replace the existing XML document. */
newDocument?: string;
/**
* An XML fragment in the following form that can be assigned to a System.Xml.XmlNode object and that contains all the list properties to be updated.
*
* For possible attributes, see the MSDN documentation for UpdateList.
*
* @example
* <List Title="List_Name" Description="List_Description" Direction="LTR"/>
*/
listProperties?: string;
/** A string that contains the version of the list that is being updated so that conflict detection can be performed. */
listVersion?: string;
// Meetings Operations
/** The e-mail address, specified as email_address@domain.ext, for the meeting organizer. */
organizerEmail?: string;
/** A persistent GUID for the calendar component. */
uid?: string;
/** The date and time that the instance of the iCalendar object was created. This parameter needs to be in the UTC format (for example, 2003-03-04T04:45:22-08:00).*/
utcDateStamp?: string;
/** The title (subject) of the meeting, meeting workspace, Web, or social data. */
title?: string;
/** The location of the meeting. */
location?: string;
/** The start date and time for the meeting, expressed in UTC. */
utcDateStart?: string;
/** The end date and time for the meeting, expressed in UTC. */
utcDateEnd?: string;
/**
* The name of the template to use when the site is created.
*
* See Windows SharePoint Services template naming guidelines for specifying a configuration within a template.
*/
templateName?: string;
/**
* The LCID (locale identifier) to use when the site is created; or,
* the language that the term set label will be added or returned in.
*/
lcid?: number;
/** The time zone information to use when the site is created. */
timeZoneInformation?: any;
// Official File Operations
/** The file being submitted. */
fileToSubmit?: any;
/** A string representing a collection of RecordsRepositoryProperty objects, each of which represents a document property being submitted with the file. */
properties?: string;
/** A string that represents the name of the record routing type. */
recordRouting?: string;
/** A string representing the current URL of the file being submitted. */
sourceUrl?: string;
/**
* A string representing the logon name of the user who is submitting the file; or,
* the display name of the user, for UserGroup operations.
*/
userName?: string;
// People Operations
/** Logon name of the principal. */
principalKeys?: string[];
/** Indicates whether to add the principal to a SPUserCollection that is associated with the Web site. */
addToUserInfoList?: boolean;
/** Principal logon name. */
searchText?: string;
// Permission Operations
/** A string that contains the name of the list or site. */
objectName?: string;
/** A string that contains the name of the site group, the name of the cross-site group, or the user name (DOMAIN\User_Alias) of the user to whom the permission applies. */
permissionIdentifier?: string;
/** A string that specifies "user", "group" (cross-site group), or "role" (site group). The user or cross-site group has to be valid, and the site group has to already exist on the site. */
permissionType?: string;
/**
* A 32-bit integer in 0x00000000 format that represents a Microsoft.SharePoint.SPRights value and defines the permission.
* For available options, see the MSDN documentation on SPRights Enumeration. NOTE: This API is now obsolete.
*/
permissionMask?: string;
/** An XML fragment that specifies the permissions to add and that can be passed as a System.Xml.XmlNode object. */
permissionsInfoXml?: string;
/** An XML fragment that specifies the permissions to remove and that can be passed as a System.Xml.XmlNode object. */
memberIdsXml?: string;
// Search Operations
/** A string specifying the search query XML. */
queryXml?: string;
/** A string that specifies the registration requested in XML. */
registrationXml?: string;
// SharePoint Diagnostics Operations
/** A string containing the location of the file from which the error is being generated. */
file?: string;
/** A string containing the line of code from which the error is being generated. */
line?: string;
/** A string containing the client name that is experiencing the error. */
client?: string;
/** A string containing the call stack information from the generated error. */
stack?: string;
/** A string containing a team or product name. */
team?: string;
/** A string containing the original file name. */
originalFile?: string;
// SiteData Operations
/** A string that contains the site-relative URL of the folder. */
strFolderUrl?: string;
/** A string that contains either the name of the list or the GUID of the list enclosed in curly braces ({}). */
strListName?: string;
/** A string that contains an integer specifying the identifier (ID) of the item. */
strItemId?: string;
// Sites Operations
/** Language of the site. */
language?: number;
/** Whether or not a language is specified for this site. */
languageSpecified?: boolean;
/** Locale of the site. */
locale?: number;
/** Whether or not a locale is specified for this site. */
localeSpecified?: boolean;
/** Collation locale of the site. */
collationLocale?: number;
/** Whether or not a collation locale is specified for this site. */
collationLocaleSpecified?: boolean;
/** Whether the site will use unique permissions. */
uniquePermissions?: boolean;
/** Whether unique permissions will be used for this site. */
uniquePermissionsSpecified?: boolean;
/** Whether the site will be anonymous. */
anonymous?: boolean;
/** Whether an anonymity condition is specified for this site. */
anonymousSpecified?: boolean;
/** Whether the site will use a presence condition. */
presence?: boolean;
/** Whether a presence condition is specified for this site. */
presenceSpecified?: boolean;
/** URL of the site. */
SiteUrl?: string;
/** A 32-bit integer that specifies the locale identifier (LCID), for example, 1033 in English. */
LCID?: number;
/** A template array whose elements provide fields containing information about each template. */
TemplateList?: any;
// SocialDataService Operations
/** The identifier (ID) of the social tag term. */
termID?: string;
/** The keyword associated with the social tag. This value must contain fewer than 256 characters. */
keyword?: string;
/** The account name of the specified user. */
userAccountName?: string;
/** The last modified time of the social comment to be updated or deleted. */
lastModifiedTime?: string;
/** The URL from which the social terms are retrieved. This value must be an empty string or in a valid URI format and must contain fewer than 2085 characters. */
urlFolder?: string;
/**
* The analysis data for the social rating.
*
* The documentation claims that analysisDataEntry is required, but in my testing it is not. There also don't seem to be any user settable values in the XML structure.
*/
analysisDataEntry?: string;
// Spellcheck Operations
/** Chunks of text to spell check. */
chunksToSpell?: string[];
/** Language to spell check again. */
declaredLanguage?: number;
/** Detect language if possible. */
useLad?: boolean;
// Taxonomy Operations
/** TermStore ID of TermSet for term operations. */
sharedServiceId?: string;
/** TermSet ID for term operations. */
termSetId?: string;
/** XML of new Terms to be added. */
newTerms?: string;
/** TermStore ID of parent Term. */
sspId?: string;
/** Term IDs must be passed in as GUIDs contained in XML nodes. */
termIds?: string;
/** "StartsWith" or "ExactMatch" to specify what type of matching is to be used. */
matchOption?: string;
/** Maximum number of Term objects to be returned. */
resultCollectionSize?: number;
/** If matchOption is ExactMatch and no match is found and this flag is set to true, a new Term will be added to the TermStore object. */
addIfNotFound?: boolean;
/** TermStore IDs for multiple term operations, must be passed in as GUIDs contained in XML nodes. */
sharedServiceIds?: string;
/** Collection of TimeStamps which are the last edit time of TermSets stored on the client. */
clientTimeStamps?: string;
/** Collection of versions of the server that each TermSet was downloaded from (always 1 unless the client doesn't have the TermSet, then it is 0). */
clientVersions?: string;
// Users and Groups Operations
/** A string that contains the (new) name of the group. */
groupName?: string;
/** A System.Xml.XmlNode object that specifies one or more group names. */
groupNamesXml?: string;
/** A string that contains the user name (DOMAIN\User_Alias) of the owner for the group. */
ownerIdentifier?: string;
/** A string that specifies the type of owner, which can be either "user" or "group". */
ownerType?: string;
/** A string that contains the user name (DOMAIN\User_Alias) of the default user for the group. */
defaultUserLoginName?: string;
/** A string that contains the name of the role definition. */
roleName?: string;
/** A System.Xml.XmlNode object that specifies one or more role definition names. */
roleNamesXml?: string;
/** A System.Xml.XmlNode object that contains information about the users. */
usersInfoXml?: string;
/** A string that contains the user name (DOMAIN\User_Alias) of the user. */
userLoginName?: string;
/** A System.Xml.XmlNode object that contains information about the users. */
userLoginNamesXml?: string;
/** A string that contains the e-mail address of the user. */
userEmail?: string;
/** A System.Xml.XmlNode object that specifies the e-mail address of the user. */
emailXml?: string;
/** A string that contains notes for the user. */
userNotes?: string;
/** A string that contains the old name of the group. */
oldGroupName?: string;
// User Profile Service Operations
/** Name of an account, for User Profile Service operations. */
accountName?: string;
/** Name of the colleague account, for User Profile Service operations involving colleagues. */
colleagueAccountName?: string;
/** Group to be used in the operation. */
group?: string;
/** Privacy policy of the user profile data: [Public, Contacts, Organization, Manager, Private]. */
privacy?: string;
/** Updated privacy policy of the user profile data: [Public, Contacts, Organization, Manager, Private]. */
newPrivacy?: string;
/** User Profile Service isInWorkGroup */
isInWorkGroup?: boolean;
/** Membership information, in the form of a MembershipData object. */
membershipInfo?: string;
/** Name of the property that has a choice list. */
propertyName?: string;
/** GUID of the user profile, for GetUserProfileByGuid */
guid?: string;
/** Index of the user profile, for GetUserProfileByIndex */
index?: number;
/** Name of the account, for GetUserProfileByName */
AccountName?: string;
/** New property name and values, in XML node format. */
newData?: string;
/** ID of user profile links to remove. */
id?: number;
/** Internal unique identifier. */
sourceInternal?: string;
/** DirectoryEntry of the Distribution List (DL) from the Active Directory, or the SPWeb or SPSite object, depending on the MemberGroup. */
sourceReference?: string;
/** New data associated with a link or pinned link. */
data?: string;
// Versions Operations
/** A string that identifies the file version. */
fileVersion?: string;
// View Operations
/** A Query element containing the query that determines which records are returned and in what order, and that can be assigned to a System.Xml.XmlNode object. */
query?: string;
/**
* A RowLimit element that specifies the number of items, or rows, to display on a page before paging begins, and that can be assigned to a
* System.Xml.XmlNode object. The fragment can include the Paged attribute to specify that the view return list items in pages.
*/
rowLimit?: string;
/** A string that specifies whether the view is an HTML view or a Datasheet view. Possible values include "HTML" and "Grid". */
type?: string;
/** An XML fragment that contains all the view-level properties as attributes, such as Editor, Hidden, ReadOnly, and Title. */
viewProperties?: string;
/** An Aggregations element that specifies the fields to aggregate and that can be assigned to a System.Xml.XmlNode object. */
aggregations?: string;
/** A Formats element that defines the grid formatting for columns and that can be assigned to a System.Xml.XmlNode object. */
formats?: string;
/** A Toolbar element that sets the HTML used to render the toolbar in a view and that can be assigned to a System.Xml.XmlNode object. */
toolbar?: string;
/** A ViewHeader element that sets the HTML used to render the header of a view and that can be assigned to a System.Xml.XmlNode object. */
viewHeader?: string;
/** A ViewBody element that sets the HTML used to render the body of a view and that can be assigned to a System.Xml.XmlNode object. */
viewBody?: string;
/** A ViewFooter element that sets the HTML used to render the footer of a view and that can be assigned to a System.Xml.XmlNode object. */
viewFooter?: string;
/** A ViewEmpty element that contains the HTML used to render the page if the query returns no items and that can be assigned to a System.Xml.XmlNode object. */
viewEmpty?: string;
/** A RowLimitExceeded element that specifies alternate rendering for when the specified row limit is exceeded and that can be assigned to a System.Xml.XmlNode object. */
rowLimitExceeded?: string;
// Web Part Pages Operations
/** A string containing the XML of the Web Part. */
webPartXml?: string;
/** A Storage value indicating how the Web Part was stored: [None | Personal | Shared]. */
storageKey?: string;
/** ID of the zone to add the Web Part. */
zoneId?: string;
/** Index of the zone to add the Web Part. */
zoneIndex?: number;
/** The name of the Web Part Page. */
documentName?: string;
/** true to allow saving the Web Part as a different type; otherwise, false. */
allowTypeChange?: boolean;
// Webs Operations
/** URL of the file for GetCustomizedPageStatus. */
fileUrl?: string;
/** URL of the object for GetObjectIdFromUrl. */
objectUrl?: string;
/** URL of the page for WebUrlFromPageUrl. */
pageURL?: string;
// Workflow Operations
/** The URL location of an item on which a workflow is being run. */
item?: string;
/** Unique identifier of the assigned task. */
todoId?: string;
/** Globally unique identifier (GUID) of the assigned task list containing the task. */
todoListId?: string;
/** Task data for conversion into a hash table. */
taskData?: string;
/** Unique identifier of a task. */
taskId?: string;
/** Globally unique identifier (GUID) of a task list containing the task. */
listId?: string;
/** Globally unique identifier (GUID) of a template. */
templateId?: string;
/** The initiation form data. */
workflowParameters?: string;
}
interface SPServices {
/**
* With this defaults function, you can set the defaults for the remainder of the page life.
* This can be useful if you'd like to make many calls into the library for a single list or site.
*/
defaults: SPServicesOptions;
/**
* Returns the current version of SPServices as a string, e.g., "0.7.2"
*/
Version(): string;
/**
* This is the core function of the library, which you can use to make Ajax calls to the SharePoint Web Services.
*
* Note: As of version 2013.01, all calls return a jQuery deferred object aka a promise.
*/
(options: SPServicesOptions): JQueryXHR;
// region Value Added Functions
/**
* The SPArrangeChoices rearranges radio buttons or checkboxes in a form from vertical to horizontal display to save page real estate.
* If the column has "Allow 'Fill-in' choices:" set to 'Yes', the fill-in option will always remain at the bottom of the controls.
*/
SPArrangeChoices(options: {
/**
* [Optional] If specified, this list will be used to look up the column's attributes.
* By default, this is set at runtime to the list name for the current form's context based on the form's URL.
* You will not generally need to specify this value.
*/
listName?: string;
/** The DisplayName of the Choice column in the form. This function works with both radio buttons and checkboxes. */
columnName: string;
/** The maximum number of choices to show per row. */
perRow: number;
/** [Optional] If true, randomize the order of the options. */
randomize?: boolean;
}): void;
/**
* The SPAutocomplete function lets you provide values for a single line of text column from values in a SharePoint list.
* The function is highly configurable and can enhance the user experience with forms.
*/
SPAutocomplete(options: {
/**
* [Optional] The URL of the Web (site) which contains the sourceList. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs.
*/
WebURL?: string;
/**
* The name or GUID of the list which contains the available values.
* If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the WebURL if the list is in another site.
*/
sourceList: string;
/** The StaticName of the source column in sourceList */
sourceColumn: string;
/** The DisplayName of the column in the form */
columnName: string;
/**
* [Optional] The CAMLQuery option allows you to specify an additional filter on the relationshipList.
* The additional filter will be ANDed with the existing CAML which is checking for matching items based on the parentColumn selection.
* Bacause it is combined with the CAML required to make the function work, CAMLQuery here should contain a CAML fragment such as:
*
* @example
* CAMLQuery: "<Eq><FieldRef Name='Status'/><Value Type='Text'>Active</Value></Eq>"
*/
CAMLQuery?: string;
/**
* [Optional] This option can be used to specify additional options for retrieval from the sourceList.
* See the MSDN documentation for GetListItems for the syntax.
*/
CAMLQueryOptions?: string;
/**
* [Optional] This option allows you to specify how values should be matched.
* The available values are [BeginsWith, Contains] and the default is "BeginsWith".
*/
filterType?: string;
/** [Optional] Wait until this number of characters has been typed before attempting any actions. The default is 0. */
numChars?: number;
/** [Optional] If set to true, the function ignores case, if false it looks for an exact match. The default is false. */
ignoreCase?: boolean;
/**
* [Optional] When a matching value is shown, the matching characters are wrapped in a <span>.
* If highlightClass is specified, that class is applied to the span. An example might be:
*
* @example
* highlightClass: "ms-bold"
*/
highlightClass?: string;
/** [Optional] If set to true, only unique values returned from sourceList will be shown. The default is false. */
uniqueVals?: boolean;
/** [Optional] Speed at which the div should slide down when values match (milliseconds or [fast, slow]). The default is "fast". */
slideDownSpeed?: number | string;
/**
* [DEPRECATED] If present, this markup will be shown while Web Service processing is occurring.
* The default is "<img src='_layouts/images/REFRESH.GIF'/>".
* Because this library requires no server-side deployment, I wanted to use one of the out of the box images.
* You can substitute whatever image or text you would like in HTML format.
*
* Note: This option has been deprecated as of v0.6.0
*/
processingIndicator?: string;
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): void;
/**
* This is the first function we implemented which allows you to take advantage of the Web Services calls in a meaningful way.
* It allows you to easily set up cascading dropdowns on a list form.
*
* (What we mean by cascading dropdowns is the situation where the available options for one column depend on the value you select in another
* column.)
*/
SPCascadeDropdowns(options: {
/** [Optional] The name of the Web (site) which contains the relationships list */
relationshipWebURL?: string;
/** The name of the list which contains the parent/child relationships */
relationshipList: string;
/** The internal name of the parent column in the relationship list */
relationshipListParentColumn: string;
/** The internal name of the child column in the relationship list */
relationshipListChildColumn: string;
/** [Optional] If specified, sort the options in the dropdown by this column,
* otherwise the options are sorted by relationshipListChildColumn
*/
relationshipListSortColumn?: string;
/** The display name of the parent column in the form */
parentColumn: string;
/** The display name of the child column in the form */
childColumn: string;
/** The list the form is working with. This is useful if the form is not in the list context.
*
* will try to default to: $().SPServices.SPListNameFromUrl()
*/
listName?: string;
/** [Optional] For power users, this CAML fragment will be Anded with the default query on the relationshipList */
CAMLQuery?: string;
/** [Optional] For power users, ability to specify Query Options */
CAMLQueryOptions?: string;
/** [DEPRECATED] Text to use as prompt. If included, {0} will be replaced with the value of childColumn. Original value "Choose {0}..." */
promptText?: string;
/** [Optional] Text to use for the (None) selection. Provided for non-English language support. */
noneText?: string;
/** [Optional] If set to true and childColumn is a complex dropdown, convert it to a simple dropdown */
simpleChild?: boolean;
/** [Optional] If set to true and there is only a single child option, select it */
selectSingleOption?: boolean;
/** By default, we match on the lookup's text value. If matchOnId is true, we'll match on the lookup id instead. */
matchOnId?: boolean;
/** Function to call on completion of rendering the change. */
completefunc?: (xData: JQueryXHR, status: string) => void;
/** If true, show error messages; if false, run silent */
debug?: boolean;
}): void;
/**
* The SPComplexToSimpleDropdown function lets you convert a "complex" dropdown rendered by SharePoint in a form to a "simple" dropdown.
* It can work in conjunction with SPCascadeDropdowns; call SPComplexToSimpleDropdown first.
*
* While this function doesn't use the SharePoint Web Services directly, it can be used with other SPServices functions which do.
*/
SPComplexToSimpleDropdown(options: {
/** The DisplayName of the column in the form */
columnName: string;
/**
* [Optional] If specified, the completefunc will be called each time there is a change to columnName. Potential uses for the
* completefunc: consistent default formatting overrides, additional lookup customizations, image manipulations, etc.
* You can pass your completefunc in either of these two ways:
*
* @example
* completefunc: function() {
* ...do something...
* },
*
* or
*
* @example
* completefunc: doSomething, // Where doSomething is the name of your function
*/
completefunc?: () => void;
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): void;
/**
* SPDisplayRelatedInfo is a function in the jQuery Library for SharePoint Web Services that lets you display information which is related
* to the selection in a dropdown. This can really bring your forms to life for users: rather than just selecting bland text values, you can
* show them images and links that are related to their choices.
*/
SPDisplayRelatedInfo(options: {
/** The DisplayName of the column in the form */
columnName: string;
/** [Optional] The URL of the Web (site) which contains the relatedList. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs. */
relatedWebURL?: string;
/**
* The name or GUID of the list which contains the related information.
* If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the relatedWebURL if the list is in another site.
*/
relatedList: string;
/** The StaticName of the column in the relatedList */
relatedListColumn: string;
/** An array of StaticNames of related columns to display */
relatedColumns: string[];
/**
* [Optional] The format to use in displaying the related information. The default is "table". The displayFormat takes one of two options:
*
* * "table" displays the matching items much like a standard List View Web Part would, in a table with column headers
* * "list" also uses a table, but displays the item(s) in a vertical orientation
*/
displayFormat?: string;
/** [Optional] If specified, the CSS class for the table headers. The default is "ms-vh2". */
headerCSSClass?: string;
/** [Optional] If specified, the CSS class for the table cells. The default is "ms-vb". */
rowCSSClass?: string;
/**
* [Optional] If used on an input column (not a dropdown), no matching will occur until at least this number of characters has been
* entered. The default is 0.
*/
numChars?: string;
/**
* [Optional] If used on an input column (not a dropdown), type of match. Can be any valid CAML comparison operator, most often "Eq" or
* "BeginsWith". The default is "Eq".
*/
matchType?: string;
/**
* [Optional] The CAMLQuery option allows you to specify an additional filter on the relationshipList.
* The additional filter will be ANDed with the existing CAML which is checking for matching items based on the parentColumn selection.
* Because it is combined with the CAML required to make the function work, CAMLQuery here should contain a CAML fragment such as:
*
* @example
* CAMLQuery: "<Eq><FieldRef Name='Status'/><Value Type='Text'>Active</Value></Eq>"
*/
CAMLQuery?: string;
/**
* [Optional] By default, we match on the lookup's text value. If matchOnId is true, we'll match on the lookup id instead.
* The default value is false.
*/
matchOnId?: boolean;
/**
* [Optional] If specified, the completefunc will be called each time there is a change to parentColumn. Potential uses for the
* completefunc: consistent default formatting overrides, additional lookup customizations, image manipulations, etc.
* You can pass your completefunc in either of these two ways:
*
* @example
* completefunc: function() {
* ...do something...
* },
*
* or
*
* @example
* completefunc: doSomething, // Where doSomething is the name of your function
*/
completefunc?: () => void;
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): void;
/**
* The SPFilterDropdown function allows you to filter the values available in a Lookup column using CAML against the Lookup column's source
* list. This function works with all three types of "dropdown": <20 options (simple select), 20+ options (complex select), and multi-select.
*/
SPFilterDropdown(options: {
/**
* [Optional] The URL of the Web (site) which contains the relationshipList. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs.
*/
relationshipWebURL?: string;
/**
* The name or GUID of the list which contains the parent/child relationships.
* If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the relationshipWebURL if the list is in another site.
*/
relationshipList: string;
/** The StaticName of the column in the relationshipList which is used for the lookup column */
relationshipListColumn: string;
/** [Optional] If specified, sort the options in the dropdown by this column otherwise the options are sorted by relationshipListColumn */
relationshipListSortColumn?: string;
/** [Optional] Allows sorting either ascending (true) or descending (false). The default is true (ascending). */
relationshipListSortAscending?: boolean;
/** The DisplayName of the column in the form */
columnName: string;
/**
* [Optional] By default, set to the list name for the current context based on the URL.
* If your form is outside the context of the list, then you can specify the listName yourself.
*/
listName?: string;
/**
* [DEPRECATED] Text to use as prompt. If included, {0} will be replaced with the value of childColumn. The default value is "".
*
* NOTE: I discourage the use of this option. Yes, I put it into the function, but if the user doesn't make a choice, they get an ugly
* error because SharePoint doesn't understand it as an option. I've left in in for backward compatibility.
*
* Deprecated in v0.7.1.
*/
promptText?: string;
/** [Optional] Text to use for the (None) selection. Provided for non-English language support. The default value is "(None)". */
noneText?: string;
/**
* [Optional] The CAMLQuery option allows you to specify the filter on the relationshipList.
* The additional filter will be ANDed with the existing CAML which is checking for matching items based on the parentColumn selection.
* The CAMLQuery should contain a CAML fragment such as:
*
* @example
* CAMLQuery: "<Eq><FieldRef Name='Status'/><Value Type='Text'>Active</Value></Eq>"
*/
CAMLQuery?: string;
/**
* [Optional] This option can be used to specify additional options for retrieval from the sourceList. See the MSDN documentation for
* GetListItems for the syntax.
*/
CAMLQueryOptions?: string;
/**
* [Optional] If specified, the completefunc will be called upon completion of the filtering.
* Uses for the completefunc: consistent default formatting overrides, additional lookup customizations, image manipulations, etc.
* You can pass your completefunc in either of these two ways:
*
* @example
* completefunc: function() {
* ...do something...
* },
*
* or
*
* @example
* completefunc: doSomething, // Where doSomething is the name of your function
*/
completefunc?: () => void;
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): void;
/**
* The SPFindMMSPicker function helps you find a Managed Metadata Service (MMS) Picker's values.
*/
SPFindMMSPicker(options: {
/** The DisplayName of the People Picker in the form. */
MMSDisplayName: string;
}): { guid: string, value: string }[];
/**
* SPFindPeoplePicker allows you to get or set the values for People Pickers. When you call it with the DisplayName of a People Picker, the
* function returns an object which contains information about the People Picker's structure and current value.
*/
SPFindPeoplePicker(options: {
/** The DisplayName of the People Picker in the form. */
peoplePickerDisplayName: string;
/** [Optional] If you'd like to set the value of the People Picker, optionally provide it here. */
valueToSet?: string;
/**
* [Optional] If you'd like to "click" on the Check Names icon to resolve the name in the People Picker, set checkNames to true. The
* default value is true.
*/
checkNames?: boolean;
}): {
/**
* This is reference to the table row which contains the People Picker. This can be useful if you want to hide or show the row
* conditionally based on some user action.
*/
row: any;
/** The full contents of the div[name='upLevelDiv'] element. */
contents: any;
/**
* The current value set in the People Picker. If you pass a value into the function, it will be set and returned in this string.
* If there are multiple people specified, they are returned separated by semi-colons, as in the People Picker display.
*/
currentValue: string;
/**
* This is a reference to the checkNames img tag in the People Picker. It's used by the function to initiate resolution of a Person
* or Group value by firing the click event on it. Once you have this reference, you can do the same.
*/
checkNames: any;
/**
* If the browser is Internet Explorer, then this object will contain the full dictionary entry values for each user or group in the
* People Picker value. If the browser is not IE, then the function calls GetUserInfo to retrieve similar values to mirror the
* dictionary entry structure.
*/
dictionaryEntries: any;
};
/**
* The SPLookupAddNew function allows you to provide a link in forms for Lookup columns so that the user can add new values to the Lookup
* list easily. It is based on a blog post by Waldek Mastykarz.
*/
SPLookupAddNew(options: {
/** The DisplayName of the Lookup column in the form. */
lookupColumn: string;
/**
* [Optional] The text to display as a link to add a new value to the lookup list. If you include the {0} placeholder, it will be
* replaced with the value of looukupColumn. The default value is "Add new {0}".
*/
promptText?: string;
/** [Optional] If true, the link will open in a new window without passing the Source. The default value is false. */
newWindow?: boolean;
/**
* [Optional] If ContentTypeID is specified, it will be passed on the Query String to the NewForm for the Lookup column's list.
* e.g., "/SiteName/NewForm.aspx?ContentTypeID=0x0100FD8C376B70E78A46974ECF1B10F8D7AD"
*/
ContentTypeID?: string;
/**
* [Optional] If specified, the completefunc will be called upon successful completion of the call to SPLookupAddNew. Potential uses for
* the completefunc: consistent default formatting overrides, additional lookup customizations, image manipulations, etc.
* You can pass your completefunc in either of these two ways:
*
* @example
* completefunc: function() {
* ...do something...
* },
*
* or
*
* @example
* completefunc: doSomething, // Where doSomething is the name of your function
*/
completefunc?: () => void;
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): void;
/**
* This function allows you to redirect to another page from a new item form with the new item's ID. This allows chaining of forms from item
* creation onward.
*/
SPRedirectWithID(options: {
/**
* The page for the redirect. Upon save of the form, the page will refresh briefly and then be redirected to redirectUrl with the new
* item's ID on the Query String.
*/
redirectUrl: string;
/**
* [Optional] In some cases, you may want to pass the newly created item's ID with a different parameter name than ID. Specify that
* name here, if needed. The default is ID.
*/
qsParamName?: string;
}): void;
/**
* Checks to see if the value for a column on the form is unique in the list. The idea for this function came from testing
* $().SPServices.SPCascadeDropdowns. When using lists like relational tables, you want to be sure that at least one column contains unique
* values. Currently, the function works only with Single line of text columns, and will generally be used with the Title column. There is
* considerable flexibility in the use of this function based on the combination of options and the ability to change the messages and their
* formatting.
*
* Note that this function will work on the NewForm and EditForm for a list, but not in the datasheet view. The intent is to put some rigor
* around the normal item creation process. Because this is a client-side function, it does not pervasively enforce the uniqueness rule.
*/
SPRequireUnique(options?: {
/** [Optional] The StaticName of the column on the form. The default value is "Title". */
columnStaticName?: string;
/**
* [Optional] This indicates what should happen if the user enters a value which already exists. The default is 0 (warn).
*
* * 0 = warn means that a warning message will be placed on the screen, but the user can save the item
* * 1 = prevent means that a warning message will be placed on the screen and the user will be prevented from saving the item (the OK
* button will be disabled until a unique value is entered)
*/
duplicateAction?: number;
/** [Optional] If set to true, the function ignores case, if false it looks for an exact match. The default is false. */
ignoreCase?: boolean;
/**
* [Optional] The initial message to display after setup. The message is displayed below in input control, but above the column
* description, if any. The default value is "This value must be unique."
*/
initMsg?: string;
/** [Optional] The CSS class for the initial message specified in initMsg. The default value is "ms-vb". */
initMsgCSSClass?: string;
/**
* [Optional] The error message to display if the value is not unique. The message is displayed below in input control, but above the
* column description, if any. (This is the same location as the initMsg.) The default value is "This value is not unique."
*/
errMsg?: string;
/** [Optional] The CSS class for the error message specified in errMsg. The default value is "ms-formvalidation". */
errMsgCSSClass?: string;
/**
* [Optional] If true, the function will show the other items in the list which are duplicates as links so that one can easily research
* what they are and potentially clean them up.
*/
showDupes?: boolean;
/**
* [Optional] If specified, the completefunc will be called upon successful completion of the call to SPRequireUnique. Potential uses for
* the completefunc: consistent default formatting overrides, additional lookup customizations, image manipulations, etc.
* You can pass your completefunc in either of these two ways:
*
* @example
* completefunc: function() {
* ...do something...
* },
*
* or
*
* @example
* completefunc: doSomething, // Where doSomething is the name of your function
*/
completefunc?: () => void;
}): void;
/**
* The SPSetMultiSelectSizes function sets the sizes of the multi-select boxes for a column on a form automagically based on the values they
* contain. The function takes into account the fontSize, fontFamily, fontWeight, etc., in its algorithm.
*/
SPSetMultiSelectSizes(options: {
/** The DisplayName of the multi-select column in the form. */
multiSelectColumn: string;
/**
* [Optional] If present, the width of the multi-select boxes will not be set narrower than this number of pixels. If either minWidth
* or maxWidth is greater than zero, then they provide the lower and upper bounds (in pixels) for the width of the multi-select boxes.
*/
minWidth?: number;
/**
* [Optional] If present, the width of the multi-select boxes will not be set wider than this number of pixels. If either minWidth or
* maxWidth is greater than zero, then they provide the lower and upper bounds (in pixels) for the width of the multi-select boxes.
*/
maxWidth?: number;
}): void;
/**
* SPUpdateMultipleListItems allows you to update multiple items in a list based upon some common characteristic or metadata criteria.
*/
SPUpdateMultipleListItems(options: {
/**
* [Optional] The URL of the Web (site) which contains the list. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs.
*/
webURL?: string;
/**
* The name or GUID of the list. If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the webURL if the list is in another site.
*/
listName: string;
/**
* [Optional] The CAMLQuery option allows you to specify the filter on the list. CAMLQuery here should contain valid CAML such as:
*
* @example
* CAMLQuery: "<Query><Where><Eq><FieldRef Name='Status'/><Value Type='Text'>Active</Value></Eq></Where></Query>"
*/
CAMLQuery?: string;
/** [Optional] The batchCmd option specifies what the action should be. The choices are "Update" or "Delete". "Update" is the default. */
batchCmd?: string;
/** [Optional] Fieldname / Fieldvalue pairs for UpdateListItems */
valuepairs?: [string, any][];
/**
* [Optional] If specified, the completefunc will be called each time there is a change to parentColumn. Potential uses for the
* completefunc: consistent default formatting overrides, additional lookup customizations, image manipulations, etc.
* You can pass your completefunc in either of these two ways:
*
* @example
* completefunc: function() {
* ...do something...
* },
*
* or
*
* @example
* completefunc: doSomething, // Where doSomething is the name of your function
*/
completefunc?: () => void;
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): void;
// endregion
// region Utilities Functions
/**
* This utility function converts a JavaScript date object to the ISO 8601 format required by SharePoint to update list items.
*
* @param dateToConvert [Optional] The JavaScript date we'd like to convert. If no date is passed, the function returns the current date/time.
* @param dateOffset [Optional] The time zone offset requested. Default is EST.
*/
SPConvertDateToISO(dateToConvert?: Date, dateOffset?: string): string;
/**
* This function displays the XMLHttpResult from an AJAX call formatted for easy debugging. You can call it manually as part of your
* completefunc. The function returns an HTML string which contains a parsed version of the XMLHttpResult object.
*/
SPDebugXMLHttpResult(options: {
/** An XMLHttpResult object returned from an AJAX call */
node: Document;
}): string;
/**
* SPDropdownCtl was previously a private function I used in SPServices to find dropdown controls in the DOM. Because of the changes to the
* way title values are set in Office365 circa Jan 2014, it made sense to expose this as a public function. By making this a public function,
* it is my hope that it will help to smooth over any future changes to the way SharePoint renders this type of control in the DOM.
*
* The function finds a dropdown in a form based on the name of the column (either the DisplayName or the StaticName) and returns an object
* you can use in your own functions.
*/
SPDropdownCtl(options: {
/** The DisplayName of the parent column in the form */
displayName: string;
}): { [key: string]: any };
/**
* This utility function, which is also publicly available, simply returns the current site's URL. It mirrors the functionality of the
* WebUrlFromPageUrl operation.
*/
SPGetCurrentSite(): string;
/**
* This utility function, which is also publicly available, returns information about the current user.
*/
SPGetCurrentUser(options?: {
/** [Optional] URL of the target Site Collection. If not specified, the current Web is used. */
webURL?: string;
/**
* [Optional] You can specify which value from userdisp.aspx you'd like returned with this option. The default is the user's account
* (Name in the Field Internal Name column below). You can specify any of the Field Internal Names for option fieldName. The fields
* listed below are the default out-of-the-box fields. If you've got custom fields which are exposed on the userdisp.aspx page, then you
* should be able to retrieve them with this function as well.
*
* Note that, as of v0.6.1, you can also request the ID of the user by specifying fieldName: "ID".
*/
fieldName?: string;
/**
* [Optional] Added in v0.7.2 to allow requesting multiple column values.
* The column names can be passed in as an array, such as ["ID", "Last Name"]
*/
fieldNames?: string[];
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): string | { [key: string]: any };
/**
* This function returns the DisplayName for a column based on the StaticName. This simple utility function, which utilizes the GetList
* operation of the Lists Web Service, seemed useful to expose as a public function.
*/
SPGetDisplayFromStatic(options: {
/**
* [Optional] The URL of the Web (site) which contains the listName. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs.
*/
webURL?: string;
/**
* The name or GUID of the list. If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the webURL if the list is in another site.
*/
listName: string;
/** [Optional] The StaticName of the column. */
columnStaticName?: string;
/**
* [Optional] The StaticNames of the columns in an array. This option was added in v0.7.2 to allow multiple column conversions at the
* same time.
*/
columnStaticNames?: string[];
}): string | string[];
/**
* Function to return the ID of the last item created on a list by a specific user. Useful for maintaining parent/child relationships.
* This function was built for use by the $().SPServices.SPRedirectWithID function, but is also useful in other circumstances.
*/
SPGetLastItemId(options: {
/**
* [Optional] The URL of the Web (site) which contains the listName. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs.
*/
webURL?: string;
/**
* The name or GUID of the list. If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the relationshipWebURL if the list is in another site.
*/
listName: string;
/** [Optional] The account for the user in DOMAIN\username format. If not specified, the current user is used. */
userAccount?: string;
/**
* [Optional] The CAMLQuery option allows you to specify an additional filter on the relationshipList.
* The additional filter will be ANDed with the existing CAML which is checking for matching items based on the parentColumn selection.
* Because it is combined with the CAML required to make the function work, CAMLQuery here should contain a CAML fragment such as:
*
* @example
* CAMLQuery: "<Eq><FieldRef Name='Status'/><Value Type='Text'>Active</Value></Eq>"
*/
CAMLQuery?: string;
}): string;
/**
* SPGetListItemsJson combines several SPServices capabilities into one powerful function. By calling GetListItemChangesSinceToken, parsing
* the list schema, and passing the resulting mapping and data to SPXmlToJson automagically, we have a one-stop shop for retrieving
* SharePoint list data in JSON format. No manual mapping required!
*/
SPGetListItemsJson(options: {
/**
* [Optional] The URL of the Web (site) which contains the list. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs.
*/
webURL?: string;
/**
* The name or GUID of the list which contains the parent/child relationships.
* If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the webURL if the list is in another site.
*/
listName: string;
/**
* [Optional] The CAMLQuery option allows you to specify the filter on the list. CAMLQuery here should contain valid CAML such as:
*
* @example
* CAMLQuery: "<Query><Where><Eq><FieldRef Name='Status'/><Value Type='Text'>Active</Value></Eq></Where></Query>"
*/
CAMLQuery?: string;
/**
* [Optional] If specified, only the columns in CAMLViewFields plus some other required columns are retrieved.
* This can be very important if your list has a lot of columns, as it can reduce the amount of data returned from the call.
* See the MSDN documentation for GetListItemsChangesSinceToken for the syntax.
*/
CAMLViewFields?: string;
/**
* [Optional] This option can be used to limit the number of items retrieved from the list.
* See the MSDN documentation for GetListItemsChangesSinceToken for the syntax.
*/
CAMLRowLimit?: string;
/**
* [Optional] This option can be used to specify additional options for retrieval from the list.
* See the MSDN documentation for GetListItemsChangesSinceToken for the syntax.
*/
CAMLQueryOptions?: string;
/**
* [Optional] GetListItemChangesSinceToken passes back a changeToken on each call.
* If you are making calls after the initial one and pass in the changeToken value, only the changes since that token will be retrieved.
* See the MSDN documentation for GetListItemsChangesSinceToken for the syntax.
*/
changeToken?: string;
/**
* [Optional] This option allows you to pass in an additional filter for the request. It should be a valid CAML clause.
* See the MSDN documentation for GetListItemsChangesSinceToken for the syntax.
*/
contains?: string;
/**
* [Optional] If you have created your own mapping, as specified in SPXmltoJson, pass it as this option.
* If present, the function will use your mapping and ignore the list schema returned by GetListItemChangesSinceToken.
*/
mapping?: { [key: string]: any };
/**
* [Optional] If you want the function to use the list schema returned by GetListItemChangesSinceToken for the majority of the columns
* but you would like to specify your own mapping for some of the columns, pass those mappings in using the mappingOverrides option.
*
* As an example, this mappingOverride would only change the way the two specified columns are converted by the SPXmlToJson function
* internally in the call (the JSON objectType is not available from the list schema):
*
* @example
* mappingOverrides: {
* ows_FiscalPeriodData: {
* mappedName: "FiscalPeriodData",
* objectType: "JSON"
* },
* ows_FiscalPeriodNames: {
* mappedName: "FiscalPeriodNames",
* objectType: "JSON"
* }
* }
*/
mappingOverrides?: { [key: string]: any };
/**
* [Optional] Setting debug: true indicates that you would like to receive messages if anything obvious is wrong with the function call,
* like using a column name which doesn't exist. I call this debug mode.
*/
debug?: boolean;
}): {
/**
* The changeToken as returned by GetListItemChangesSinceToken. This token can be passed to subsequent calls to the function.
* The various parts of the changeToken have specific meaning, but you should treat it as an immutable string.
*/
changeToken: string;
/**
* The mapping used to parse the data into JSON. This mapping will include any specific overrides you specified as well as the
* automatically created mappings. You can pass this mapping into the function on subsequent calls to reduce overhead, though the
* function saves the mapping in a local data store for reuse.
*/
mapping: { [key: string]: any };
/**
* The main reason we make the call, the data property is an object containing all of the retrieved data in JSON format,
* as specified in SPXmlToJson.
*/
data: { [key: string]: any };
/**
* If this is call 2-n to the function, deletedIds will contain an array of IDs for list items which have been deleted since the
* prior call.
*/
deletedIds: string[];
};
/**
* The SPGetQueryString function parses out the parameters on the Query String and makes them available for further use. This function was
* previously included, but was a private function.
*/
SPGetQueryString(): string;
/**
* This function returns the StaticName for a column based on the DisplayName. This simple utility function, which utilizes the GetList
* operation of the Lists Web Service, seemed useful to expose as a public function.
*/
SPGetStaticFromDisplay(options: {
/**
* [Optional] The URL of the Web (site) which contains the listName. If not specified, the current site is used.
* Examples would be: "/", "/Accounting", "/Departments/HR", etc. Note: It's always best to use relative URLs.
*/
webURL?: string;
/**
* The name or GUID of the list. If you choose to use the GUID, it should look like: "{E73FEA09-CF8F-4B30-88C7-6FA996EE1706}".
* Note also that if you use the GUID, you do not need to specify the webURL if the list is in another site.
*/
listName: string;
/** [Optional] The DisplayName of the column. */
columnDisplayName?: string;
/**
* [Optional] The DisplayNames of the columns in an array. This option was added in v0.7.2 to allow multiple column conversions at the
* same time.
*/
columnDisplayNames?: string[];
}): string | string[];
/**
* This utility function, which is also publicly available, returns the current list's GUID if called in the context of a list, meaning that
* the URL is within the list, like /DocLib or /Lists/ListName.
*
* @param listName [Optional] Option to allow passing in a URL to the function rather than simply picking up the current context. This will
* help where custom list forms are stored outside the list context.
*/
SPListNameFromUrl(listName?: string): string;
/**
* The SPScriptAudit function allows you to run an auditing report showing where scripting is in use in a site.
*/
SPScriptAudit(options?: {
/**
* [Optional] The site on which to run the audit. If no site is specified, the current site is used.
* Examples would be: "/Departments", "/Departments/HR", "/Sites", etc.
*/
webURL?: string;
/** [Optional] The name of a specific list to audit. If not present, all lists in the site are audited. */
listName?: string;
/**
* [Optional] The ID of an HTML element into which to insert the report.
* If you would like to see the report within this div: <div id="MyOutput"></div>, then the value would be "MyOutput".
*/
outputId?: string;
/** [Optional] Audit the form pages if true. The default is true. */
auditForms?: boolean;
/** [Optional] Audit the view pages if true. The default is true. */
auditViews?: boolean;
/** [Optional] Audit the Pages Document Library if true. The default is true. */
auditPages?: boolean;
/** [Optional] The Pages Document Library, if desired. The default is "Pages". */
auditPagesListName?: string;
/** [Optional] true if you would like to see the output for hidden lists; false if not. The default is false. */
showHiddenLists?: boolean;
/**
* [Optional] true if you would like to see the output for lists with no scripts (effectively "verbose"); false if not. The default is
* false.
*/
showNoScript?: boolean;
/** [Optional] true if you would like to see the included script files on each page; false if not. The default is true. */
showSrc?: boolean;
}): void;
// endregion
}
}
interface JQuery {
/**
* SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use.
*
* It also includes functions which use the various Web Service operations to provide more useful (and cool) capabilities.
* It works entirely client side and requires no server install.
*/
SPServices: JQuerySPServices.SPServices;
/**
* Can be used to find namespaced elements in returned XML, such as rs:data or z:row from GetListItems.
*
* My hope is that by having this function in place, SPServices will be a bit more future-proof against changes made by the jQuery team.
* The function is only required if you want your script to work reliably cross-browser, as Internet Explorer will reliably find the elements
* with the simpler .find("z:row") syntax.
*
* @param nodeName An XML node name, such as rs:data or z:row.
*/
SPFilterNode(nodeName: string): JQuery;
/**
* SPXmlToJson is a function to convert XML data into JSON for client-side processing.
*/
SPXmlToJson(options?: {
/**
* An array of columns to return in the JSON. While you should generally limit the values you request in your Web Services calls where you
* can, in some cases you won't have that capability. This option alows you to create "lean" JSON by only including the attributes you need.
* You can also rename the attributes for better compatibility with other jQuery plugins, for instance. Where it makes sense, the different
* column types (SPFieldType) are returned as analogous JavaScript objects. If not specified in the mapping, values are returned as strings.
*
* The default value for mapping is {} (no mappings).
*/
mapping?: { [key: string]: any };
/** If true, return all attributes, regardless whether they are in the mapping. The default is false. */
includeAllAttrs?: boolean;
/** Specifically for GetListItems, if true, the leading "ows_" will be stripped from the field name. */
removeOws?: boolean;
/** If true, empty ("") values will not be returned. The default is false. Added in 2014.01. */
sparse?: boolean;
}): { [key: string]: any };
} | the_stack |
import type { ImportDeclaration, SyntaxList } from 'typescript';
import { ExtensionContext, NotebookCell, NotebookDocument, Uri, workspace } from 'vscode';
import { EOL } from 'os';
import { MappingItem, RawSourceMap, SourceMapConsumer, SourceMapGenerator } from 'source-map';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { CodeObject } from '../server/types';
import { LineNumber, NewColumn, OldColumn, processTopLevelAwait } from './asyncWrapper';
import { getNotebookCwd } from '../utils';
declare const __webpack_require__: any;
declare const __non_webpack_require__: any;
let ts: typeof import('typescript');
let tmpDirectory: string | undefined;
const mapOfSourceFilesToNotebookUri = new Map<string, Uri>();
const mapFromCellToPath = new WeakMap<NotebookCell, CodeObject>();
const codeObjectToSourceMaps = new WeakMap<
CodeObject,
{
raw: RawSourceMap;
originalToGenerated: Map<number, Map<number, MappingItem>>;
generatedToOriginal: Map<number, Map<number, MappingItem>>;
originalToGeneratedCache: Map<string, { line?: number; column?: number }>;
generatedToOriginalCache: Map<string, { line?: number; column?: number }>;
}
>();
export namespace Compiler {
export function register(context: ExtensionContext) {
const typescriptPath = path.join(
context.extensionUri.fsPath,
'resources',
'scripts',
'node_modules',
'typescript',
'index.js'
);
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require;
ts = fs.existsSync(typescriptPath) ? requireFunc(typescriptPath) : requireFunc('typescript');
}
/**
* Returns the Cell associated with the temporary file we create (used to enable debugging with source maps), this will
*/
export function getCellFromTemporaryPath(sourceFilename: string): NotebookCell | undefined {
if (mapOfSourceFilesToNotebookUri.has(sourceFilename)) {
return getNotebookCellfromUri(mapOfSourceFilesToNotebookUri.get(sourceFilename));
}
if (sourceFilename.toLowerCase().endsWith('.nnb') || sourceFilename.toLowerCase().endsWith('.ipynb')) {
const key = Array.from(mapOfSourceFilesToNotebookUri.keys()).find((item) => sourceFilename.includes(item));
return getNotebookCellfromUri(key ? mapOfSourceFilesToNotebookUri.get(key) : undefined);
}
}
/**
* Will replace the bogus paths in stack trace with user friendly paths.
* E.g. if the following is the stack trace we get back:
* /var/folders/3t/z38qn8r53l169lv_1nfk8y6w0000gn/T/vscode-nodebook-sPmlC6/nodebook_cell_ch0000013.js:2
console.log(x);
^
ReferenceError: x is not defined
at hello (/var/folders/3t/z38qn8r53l169lv_1nfk8y6w0000gn/T/vscode-nodebook-sPmlC6/nodebook_cell_ch0000013.js:2:17)
at /var/folders/3t/z38qn8r53l169lv_1nfk8y6w0000gn/T/vscode-nodebook-sPmlC6/nodebook_cell_ch0000012.js:1:1
at Script.runInContext (vm.js:144:12)
at Script.runInNewContext (vm.js:149:17)
at Object.runInNewContext (vm.js:304:38)
at runCode (/Users/donjayamanne/Desktop/Development/vsc/typescript-notebook/out/extension/kernel/server/codeExecution.js:64:33)
at Object.execCode (/Users/donjayamanne/Desktop/Development/vsc/typescript-notebook/out/extension/kernel/server/codeExecution.js:98:30)
at WebSocket.<anonymous> (/Users/donjayamanne/Desktop/Development/vsc/typescript-notebook/out/extension/kernel/server/index.js:47:41)
at WebSocket.emit (events.js:375:28)
at WebSocket.emit (domain.js:470:12)
*
* We need to repace the temporary paths `/var/folders/3t/z38qn8r53l169lv_1nfk8y6w0000gn/T/vscode-nodebook-sPmlC6/nodebook_cell_ch0000013.js` with the cell index.
* & also remove all of the messages that are not relevant (VM stack trace).
*/
export function fixCellPathsInStackTrace(
document: NotebookDocument,
error?: Error | string,
replaceWithRealCellUri = false
): string {
if (typeof error === 'object' && error.name === 'InvalidCode_CodeExecution') {
error.name = 'SyntaxError';
error.stack = '';
return '';
}
let stackTrace = (typeof error === 'string' ? error : error?.stack) || '';
let lineFound = false;
if (stackTrace.includes('at Script.runInContext (vm.js')) {
stackTrace = stackTrace.substring(0, stackTrace.indexOf('at Script.runInContext (vm.js')).trimEnd();
}
if (
stackTrace.includes('extension/server/codeExecution.ts') ||
stackTrace.includes('extension/server/codeExecution.js')
) {
stackTrace = stackTrace.split(/\r?\n/).reduce((newStack, line, i) => {
const separator = i > 0 ? '\n' : '';
if (!lineFound) {
lineFound =
line.includes('extension/server/codeExecution.ts') ||
line.includes('extension/server/codeExecution.js');
if (!lineFound) {
newStack += `${separator}${line}`;
}
}
return newStack;
}, '');
}
if (!stackTrace.includes('vscode-notebook-') || !stackTrace.includes('notebook_cell_')) {
return stackTrace;
}
document.getCells().forEach((cell) => {
const tempPath = mapFromCellToPath.get(cell);
if (!tempPath) {
return;
}
if (stackTrace.includes(tempPath.sourceFilename)) {
const codeObject = Compiler.getCodeObject(cell);
if (!codeObject) {
return;
}
const sourceMap = Compiler.getSourceMapsInfo(codeObject);
if (!sourceMap) {
return;
}
const regex = new RegExp(tempPath.sourceFilename, 'g');
const lines = stackTrace.split(tempPath.sourceFilename);
lines
.filter((line) => line.startsWith(':'))
.forEach((stack) => {
const parts = stack.split(':').slice(1);
const line = parseInt(parts[0]);
const column = parseInt(parts[1]);
if (!isNaN(line) && !isNaN(column)) {
const mappedLocation = Compiler.getMappedLocation(
codeObject,
{ line, column },
'DAPToVSCode'
);
if (typeof mappedLocation.line === 'number' && typeof mappedLocation.column === 'number') {
const textToReplace = `${tempPath.sourceFilename}:${line}:${column}`;
const textToReplaceWith = replaceWithRealCellUri
? `${cell.document.uri.toString()}:${mappedLocation.line}:${mappedLocation.column}`
: `<Cell ${cell.index + 1}> [${mappedLocation.line}, ${mappedLocation.column}]`;
stackTrace = stackTrace.replace(textToReplace, textToReplaceWith);
}
}
});
stackTrace = stackTrace.replace(regex, `<Cell ${cell.index + 1}> `);
}
});
return stackTrace;
}
const dummyFnToUseImports = 'adf8d89dff594ea79f38d03905825d73';
export function getSourceMapsInfo(codeObject: CodeObject) {
return codeObjectToSourceMaps.get(codeObject);
}
export function getMappedLocation(
codeObject: CodeObject,
location: { line?: number; column?: number },
direction: 'VSCodeToDAP' | 'DAPToVSCode'
): { line?: number; column?: number } {
if (typeof location.line !== 'number' && typeof location.column !== 'number') {
return location;
}
const sourceMap = getSourceMapsInfo(codeObject);
if (!sourceMap) {
return location;
}
if (typeof location.line !== 'number') {
return location;
}
const cacheKey = `${location.line || ''},${location.column || ''}`;
const cache =
direction === 'VSCodeToDAP' ? sourceMap.originalToGeneratedCache : sourceMap.generatedToOriginalCache;
const cachedData = cache.get(cacheKey);
if (cachedData) {
return cachedData;
}
const mappedLocation = { ...location };
if (direction === 'DAPToVSCode') {
// There's no such mapping of this line number.
const map = sourceMap.generatedToOriginal.get(location.line);
if (!map) {
return location;
}
const matchingItem = typeof location.column === 'number' ? map.get(location.column) : map.get(0)!;
if (matchingItem) {
mappedLocation.line = matchingItem.originalLine;
mappedLocation.column = matchingItem.originalColumn;
}
// get the first item that has the lowest column.
// TODO: Review this.
else if (map.has(0)) {
mappedLocation.line = map.get(0)!.originalLine;
mappedLocation.column = map.get(0)!.originalColumn;
} else {
const column = Array.from(map.keys()).sort()[0];
mappedLocation.line = map.get(column)!.originalLine;
mappedLocation.column = map.get(column)!.originalColumn;
}
} else {
const map = sourceMap.originalToGenerated.get(location.line);
if (!map) {
return location;
}
const matchingItem =
typeof location.column === 'number'
? // Find the next closes column we have, we if cannot find an exact match.
map.get(location.column) || map.get(location.column - 1) || map.get(location.column + 1)
: map.get(0)!;
if (matchingItem) {
mappedLocation.line = matchingItem.generatedLine;
mappedLocation.column = matchingItem.generatedColumn;
}
// get the first item that has the lowest column.
// TODO: Review this.
else if (map.has(0)) {
mappedLocation.line = map.get(0)!.generatedLine;
mappedLocation.column = map.get(0)!.generatedColumn;
} else {
const column = Array.from(map.keys()).sort()[0];
mappedLocation.line = map.get(column)!.generatedLine;
mappedLocation.column = map.get(column)!.generatedColumn;
}
}
cache.set(cacheKey, mappedLocation);
return mappedLocation;
}
export function getCodeObject(cell: NotebookCell) {
return mapFromCellToPath.get(cell)!;
}
function getNotebookCwd(notebook: NotebookDocument){
if (notebook.isUntitled){
return workspace.workspaceFolders?.length ? workspace.workspaceFolders[0].uri.fsPath : os.tmpdir();
}
return path.dirname(notebook.uri.fsPath);
}
export function getOrCreateCodeObject(
cell: NotebookCell,
code = cell.document.getText(),
supportBreakingOnExceptionsInDebugger: boolean = true
): CodeObject {
try {
// Parser fails when we have comments in the last line, hence just add empty line.
code = `${code}${EOL}`;
const details = createCodeObject(cell);
if (details.textDocumentVersion === cell.document.version) {
return details;
}
let expectedImports = '';
try {
// If imports are not used, typescript will drop them.
// Solution, add dummy code into ts that will make the compiler think the imports are used.
// E.g. if we have `import * as fs from 'fs'`, then add `myFunction(fs)` at the bottom of the code
// And once the JS is generated remove that dummy code.
expectedImports = getExpectedImports(cell);
} catch (ex) {
console.error(`Failed to generate dummy placeholders for imports`);
}
// Even if the code is JS, transpile it (possibel user accidentally selected JS cell & wrote TS code)
const result = ts.transpile(
code,
{
sourceMap: true,
inlineSourceMap: true,
jsx: ts.JsxEmit.None,
sourceRoot: path.dirname(details.sourceTsFilename),
noImplicitUseStrict: true,
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove,
strict: false, // No way.
fileName: details.sourceTsFilename,
resolveJsonModule: true,
removeComments: true,
target: ts.ScriptTarget.ESNext, // Minimum Node12 (but let users use what ever they want). Lets look into user defined tsconfig.json.
module: ts.ModuleKind.CommonJS,
alwaysStrict: false,
checkJs: false, // We're not going to give errors, the user can get this from vscode problems window & linters, etc... why re-invent the wheel here.
noEmitHelpers: true,
esModuleInterop: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
experimentalDecorators: true,
allowUnreachableCode: true,
preserveConstEnums: true,
allowJs: true,
rootDir: getNotebookCwd(cell.notebook),
allowSyntheticDefaultImports: true,
skipLibCheck: true // We expect users to rely on VS Code to let them know if they have issues in their code.
},
details.sourceTsFilename
);
// let transpiledCode = result;
// let transpiledCode = result.replace(
// 'Object.defineProperty(exports, "__esModule", { value: true });',
// 'Object.defineProperty(module.exports, "__esModule", { value: true });'
// );
let transpiledCode = result.replace(
'Object.defineProperty(exports, "__esModule", { value: true });',
' '.repeat('Object.defineProperty(exports, "__esModule", { value: true });'.length)
);
// Remove `use strict`, this causes issues some times.
// E.g. this code fails (dfd not found).
/*
import * as dfd from 'danfojs-node';
const df: dfd.DataFrame = await dfd.read_csv('./finance-charts-apple.csv');
const layout = {
title: 'A financial charts',
xaxis: {
title: 'Date',
},
yaxis: {
title: 'Count',
}
}
const newDf = df.set_index({ key: "Date" })
newDf.plot("").line({ columns: ["AAPL.Open", "AAPL.High"], layout })
*/
// Split generated source & source maps
const lines = transpiledCode.split(/\r?\n/).filter((line) => !line.startsWith(dummyFnToUseImports));
const sourceMapLine = lines.pop()!;
transpiledCode = lines.join(EOL);
// Update the source to account for top level awaits & other changes, etc.
const sourceMap = Buffer.from(sourceMapLine.substring(sourceMapLine.indexOf(',') + 1), 'base64').toString();
const sourceMapInfo = { original: sourceMap, updated: '' };
transpiledCode = replaceTopLevelConstWithVar(
cell,
transpiledCode,
sourceMapInfo,
expectedImports,
supportBreakingOnExceptionsInDebugger
);
// Re-generate source maps correctly
const updatedRawSourceMap: RawSourceMap = JSON.parse(
sourceMapInfo.updated || sourceMapInfo.updated || sourceMap || ''
);
updatedRawSourceMap.file = path.basename(details.sourceFilename);
updatedRawSourceMap.sourceRoot = path.dirname(details.sourceFilename);
updatedRawSourceMap.sources = [path.basename(details.sourceFilename)];
const updatedSourceMap = JSON.stringify(updatedRawSourceMap);
// Node debugger doesn't seem to support inlined source maps
// https://github.com/microsoft/vscode/issues/130303
// Once available, uncomment this file & the code.
// const transpiledCodeWithSourceFile = `${transpiledCode}${EOL}//# sourceURL=file:///${details.sourceFilename}`;
// const transpiledCodeWithSourceMap = `${transpiledCode}${EOL}//# sourceMappingURL=data:application/json;base64,${Buffer.from(
// updatedSourceMap
// ).toString('base64')}`;
// updateCodeObject(details, cell, transpiledCodeWithSourceMap, updatedSourceMap);
// details.code = transpiledCodeWithSourceFile;
updateCodeObject(details, cell, transpiledCode, updatedSourceMap);
const originalToGenerated = new Map<number, Map<number, MappingItem>>();
const generatedToOriginal = new Map<number, Map<number, MappingItem>>();
new SourceMapConsumer(updatedRawSourceMap).eachMapping((mapping) => {
let maps = originalToGenerated.get(mapping.originalLine) || new Map<number, MappingItem>();
originalToGenerated.set(mapping.originalLine, maps);
maps.set(mapping.originalColumn, mapping);
maps = generatedToOriginal.get(mapping.generatedLine) || new Map<number, MappingItem>();
generatedToOriginal.set(mapping.generatedLine, maps);
maps.set(mapping.generatedColumn, mapping);
});
codeObjectToSourceMaps.set(details, {
raw: updatedRawSourceMap,
originalToGenerated,
generatedToOriginal,
originalToGeneratedCache: new Map<string, { line?: number; column?: number }>(),
generatedToOriginalCache: new Map<string, { line?: number; column?: number }>()
});
if (!process.env.__IS_TEST) {
console.debug(`Compiled TS cell ${cell.index} into ${details.code}`);
}
return details;
} catch (ex) {
// Only for debugging.
console.error('Yikes', ex);
throw ex;
}
}
}
/**
* Found that sometimes the repl crashes when we have trailing commas and an async.
* The following sample code fails (but removing the trailing comments work):
tensor = tf.tensor([
[
[1,1,1],
[0,0,0],
[1,1,1]
],
[
[0,0,0],
[1,1,1],
[0,0,0]
],
[
[1,1,1],
[0,0,0],
[1,1,1]
]
]);
var big = tf.fill([10,10,4], 0.5)
// big
// // tensor = tensor.mult
// let m = await tf.node.encodePng(tensor);
const image = await tf.node.encodePng(tensor);
let fs = require('fs');
fs.writeFileSync('wow.png', image)
image
// console.log(img1);
// // let fs = require('fs');
// fs.writeFileSync('wow.png', img)
*/
// private removeTrailingComments(code: string) {
// const lines = code.split(/\r?\n/).reverse();
// let nonEmptyLineFound = false;
// const reversedLines = lines.map((line) => {
// const isEmpty = line.trim().length === 0 || line.trim().startsWith('//');
// nonEmptyLineFound = nonEmptyLineFound || !isEmpty;
// return nonEmptyLineFound ? line : '';
// });
// return reversedLines.reverse().join(EOL);
// }
/**
* We cannot have top level constants.
* Running the cell again will cause errors.
* Solution, convert const to var.
*/
function replaceTopLevelConstWithVar(
cell: NotebookCell,
source: string,
sourceMap: { original?: string; updated?: string },
expectedImports: string,
supportBreakingOnExceptionsInDebugger?: boolean
) {
if (source.trim().length === 0) {
return expectedImports;
}
const result = processTopLevelAwait(expectedImports, source, supportBreakingOnExceptionsInDebugger);
try {
updateCodeAndAdjustSourceMaps(result!.linesUpdated, sourceMap);
} catch (ex) {
console.error(`Failed to adjust source maps`, ex);
}
return result!.updatedCode;
}
function updateCodeAndAdjustSourceMaps(
linesUpdated: Map<
LineNumber,
{ adjustedColumns: Map<OldColumn, NewColumn>; firstOriginallyAdjustedColumn?: number; totalAdjustment: number }
>,
sourceMap: { original?: string; updated?: string }
) {
// If we don't have any original source maps, then nothing to update.
if (!sourceMap.original) {
return;
}
// If we have changes, update the source maps now.
const originalSourceMap: RawSourceMap = JSON.parse(sourceMap.original);
const updated = new SourceMapGenerator({
file: path.basename(originalSourceMap.file || ''),
sourceRoot: path.dirname(originalSourceMap.sourceRoot || '')
});
const original = new SourceMapConsumer(originalSourceMap);
original.eachMapping((mapping) => {
const newMapping: MappingItem = {
generatedColumn: mapping.generatedColumn,
generatedLine: mapping.generatedLine + 2, // We added a top empty line and one after start of IIFE
name: mapping.name,
originalColumn: mapping.originalColumn,
originalLine: mapping.originalLine,
source: mapping.source
};
// // Check if we have adjusted the columns for this line.
const oldValue = newMapping.generatedColumn;
const adjustments = linesUpdated.get(newMapping.generatedLine);
if (adjustments?.adjustedColumns?.size) {
const positionsInAscendingOrder = Array.from(adjustments.adjustedColumns.keys()).sort();
// Get all columns upto this current column, get the max column & its new position.
const lastColumnUpdatedUptoThisColumn = positionsInAscendingOrder.filter(
(item) => item <= newMapping.generatedColumn
);
if (lastColumnUpdatedUptoThisColumn.length) {
const lastColumn = lastColumnUpdatedUptoThisColumn[lastColumnUpdatedUptoThisColumn.length - 1];
const incrementBy = adjustments.adjustedColumns.get(lastColumn)! - lastColumn;
newMapping.generatedColumn += incrementBy;
}
} else if (
typeof adjustments?.firstOriginallyAdjustedColumn === 'number' &&
mapping.originalColumn >= adjustments?.firstOriginallyAdjustedColumn
) {
// Something is wrong in the code.
newMapping.generatedColumn += adjustments.totalAdjustment;
}
// We need a test for this, assume we declare a variable and that line of code is indented
// E.g. we have ` var x = 1234` (note the leading spaces)
if (newMapping.generatedColumn < 0) {
newMapping.generatedColumn = oldValue;
}
updated.addMapping({
generated: {
column: newMapping.generatedColumn,
line: newMapping.generatedLine
},
original: {
column: newMapping.originalColumn,
line: newMapping.originalLine
},
source: newMapping.source,
name: newMapping.name
});
});
sourceMap.updated = updated.toString();
}
function createCodeObject(cell: NotebookCell) {
if (mapFromCellToPath.has(cell)) {
return mapFromCellToPath.get(cell)!;
}
const cwd = getNotebookCwd(cell.notebook);
const notebookFSPath = cell.notebook.isUntitled ? cell.notebook.uri.toString() : cell.notebook.uri.fsPath;
const codeObject: CodeObject = {
code: '',
sourceFilename: '',
sourceTsFilename: '',
sourceMapFilename: '',
friendlyName: cwd && !cell.notebook.isUntitled
? `${path.relative(cwd, notebookFSPath)}?cell=${cell.index + 1}`
: `${notebookFSPath}?cell=${cell.index + 1}`,
textDocumentVersion: -1
};
if (!tmpDirectory) {
tmpDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-notebook-'));
}
codeObject.code = '';
// codeObject.sourceFilename = codeObject.sourceFilename || cell.document.uri.toString();
codeObject.sourceFilename =
codeObject.sourceFilename || path.join(tmpDirectory, `notebook_cell_${cell.document.uri.fragment}.js`);
codeObject.sourceTsFilename =
codeObject.sourceTsFilename || path.join(tmpDirectory, `notebook_cell_${cell.document.uri.fragment}.ts`);
codeObject.sourceMapFilename = codeObject.sourceMapFilename || `${codeObject.sourceFilename}.map`;
mapOfSourceFilesToNotebookUri.set(codeObject.sourceFilename, cell.document.uri);
mapOfSourceFilesToNotebookUri.set(cell.document.uri.toString(), cell.document.uri);
mapFromCellToPath.set(cell, codeObject);
// For some reason if the file is empty, then generics don't work
// To fix this issue (https://github.com/DonJayamanne/typescript-notebook/issues/40) we must have code in the file.
// Even tried locally by manullay importing typescript and using compiler, same problem.
fs.writeFileSync(codeObject.sourceTsFilename, cell.document.getText());
return codeObject;
}
function updateCodeObject(codeObject: CodeObject, cell: NotebookCell, sourceCode: string, sourceMapText: string) {
if (!tmpDirectory) {
tmpDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-nodebook-'));
}
codeObject.code = sourceCode;
if (codeObject.textDocumentVersion !== cell.document.version) {
fs.writeFileSync(codeObject.sourceFilename, sourceCode);
fs.writeFileSync(codeObject.sourceTsFilename, sourceCode);
// if (sourceMapText) {
// fs.writeFileSync(codeObject.sourceMapFilename, sourceMapText);
// }
}
codeObject.textDocumentVersion = cell.document.version;
mapFromCellToPath.set(cell, codeObject);
return codeObject;
}
function getNotebookCellfromUri(uri?: Uri) {
if (!uri) {
return;
}
const notebookUri = uri.fsPath.toLowerCase();
const notebook = workspace.notebookDocuments.find((item) => item.uri.fsPath.toLowerCase() === notebookUri);
if (notebook) {
return notebook.getCells().find((cell) => cell.document.uri.toString() === uri.toString());
}
}
function getExpectedImports(cell: NotebookCell) {
const program = ts.createSourceFile(
cell.document.uri.fsPath,
cell.document.getText(),
ts.ScriptTarget.ES2019,
false,
ts.ScriptKind.TS
);
const sourceList = program.getChildAt(0) as SyntaxList;
const imports = sourceList
.getChildren()
.filter((item) => item.kind === ts.SyntaxKind.ImportDeclaration)
.map((item) => item as ImportDeclaration);
const requireStatements: string[] = [];
const variables: string[] = [];
imports.forEach((item: ImportDeclaration) => {
if (!ts.isStringLiteral(item.moduleSpecifier)) {
return;
}
const importFrom = item.moduleSpecifier.text;
const position = cell.document.positionAt(item.moduleSpecifier.end);
const line = cell.document.lineAt(position.line).text.trim();
// We're only goinng to try to make this work for lines that start with `import ....`
if (!line.startsWith('import')) {
return;
}
const importClause = item.importClause;
if (!importClause) {
requireStatements.push(`void (require("${importFrom}"));`);
return;
}
if (importClause.isTypeOnly) {
return;
}
if (importClause.name) {
variables.push(`var ${importClause.name.getText(program)};`);
requireStatements.push(
`void (${importClause.name.getText(program)} = __importDefault(require("${importFrom}")));`
);
}
if (importClause.namedBindings) {
if (ts.isNamespaceImport(importClause.namedBindings)) {
variables.push(`var ${importClause.namedBindings.name.text};`);
requireStatements.push(
`void (${importClause.namedBindings.name.text} = __importStar(require("${importFrom}")));`
);
} else {
const namedImportsForModule: string[] = [];
importClause.namedBindings.elements.forEach((ele) => {
if (ele.propertyName) {
variables.push(`var ${ele.name.text};`);
namedImportsForModule.push(`${ele.propertyName.text}:${ele.name.text}`);
} else {
variables.push(`var ${ele.name.text};`);
namedImportsForModule.push(`${ele.name.text}`);
}
});
if (namedImportsForModule.length) {
requireStatements.push(`void ({${namedImportsForModule.join(', ')}} = require("${importFrom}"));`);
}
}
}
});
return `${variables.join('')}${requireStatements.join('')}`;
}
export type BaseNode<T> = {
type: T;
start: number;
end: number;
loc: BodyLocation;
range?: [number, number];
};
type TokenLocation = { line: number; column: number };
type BodyLocation = { start: TokenLocation; end: TokenLocation };
type FunctionDeclaration = BaseNode<'FunctionDeclaration'> & {
body: BlockStatement;
id: { name: string; loc: BodyLocation };
};
export type VariableDeclaration = BaseNode<'VariableDeclaration'> & {
kind: 'const' | 'var' | 'let';
id: { name: string; loc: BodyLocation };
// loc: BodyLocation;
declarations: VariableDeclarator[];
};
type VariableDeclarator = BaseNode<'VariableDeclarator'> & {
id:
| (BaseNode<string> & { name: string; loc: BodyLocation; type: 'Identifier' | '<other>' })
| (BaseNode<'ObjectPattern'> & {
name: string;
properties: { type: 'Property'; key: { name: string }; value: { name: string } }[];
})
| (BaseNode<'ArrayPattern'> & {
name: string;
elements: { name: string; type: 'Identifier' }[];
});
init?: { loc: BodyLocation };
loc: BodyLocation;
};
type OtherNodes = BaseNode<'other'> & { loc: BodyLocation };
type ClassDeclaration = BaseNode<'ClassDeclaration'> & {
id: { name: string; loc: BodyLocation };
};
type BodyDeclaration = ExpressionStatement | VariableDeclaration | ClassDeclaration | FunctionDeclaration | OtherNodes;
type BlockStatement = {
body: BodyDeclaration[];
};
type ExpressionStatement = BaseNode<'ExpressionStatement'> & {
expression:
| (BaseNode<'CallExpression'> & {
callee:
| (BaseNode<'ArrowFunctionExpression'> & { body: BlockStatement })
| (BaseNode<'CallExpression'> & {
body: BlockStatement;
callee: { name: string; loc: BodyLocation };
});
})
| BaseNode<'other'>;
loc: BodyLocation;
}; | the_stack |
import { connect, Cursor } from 'mongodb';
import { connectionString } from '../index';
import { ObjectId } from 'bson';
/**
* test the FilterQuery type using collection.find<T>() method
* Monog uses FilterQuery type for every method that performs a document search
* for example: findX, updateX, deleteX, distinct, countDocuments
* So we don't add duplicate tests for every collection method and only use find
*/
async function run() {
const client = await connect(connectionString);
const db = client.db('test');
/**
* Test the generic FilterQuery using collection.find<T>() method
*/
// a collection model for all possible MongoDB BSON types and TypeScript types
interface UserModel {
_id: ObjectId; // ObjectId field
name?: string; // optional field
family: string; // string field
age: number; // number field
gender: 'male' | 'female' | 'other'; // union field
isBanned: boolean; // boolean field
addedBy?: UserModel; // object field (Embedded/Nested Documents)
createdAt: Date; // date field
schools: string[]; // array of string
scores: number[]; // array of number
friends?: UserModel[]; // array of objects
}
const sampleUser: UserModel = {
_id: new ObjectId("577fa2d90c4cc47e31cf4b6f"),
name: 'Peter',
family: 'Anderson',
age: 30,
gender: 'male',
isBanned: false,
createdAt: new Date(),
schools: ['s1', 's2'],
scores: [100, 80, 90],
};
const collectionT = db.collection<UserModel>('test.filterQuery');
/**
* test simple field queries e.g. { name: 'John' }
*/
/// it should query __string__ fields
await collectionT.find({ name: 'John' }).toArray();
// it should query string fields by regex
await collectionT.find({ name: /Joh/i }).toArray();
// it should query string fields by RegExp object
await collectionT.find({ name: new RegExp('Joh', 'i') }).toArray();
/// it should not accept wrong types for string fields
// $ExpectError
await collectionT.find({ name: 23 }).toArray();
// $ExpectError
await collectionT.find({ name: { prefix: 'Dr' } }).toArray();
// $ExpectError
await collectionT.find({ name: [ 'John' ] }).toArray();
/// it should query __number__ fields
await collectionT.find({ age: 12 }).toArray();
/// it should not accept wrong types for number fields
// $ExpectError
await collectionT.find({ age: /12/i }).toArray(); // it cannot query number fields by regex
// $ExpectError
await collectionT.find({ age: '23' }).toArray();
// $ExpectError
await collectionT.find({ age: { prefix: 43 } }).toArray();
// $ExpectError
await collectionT.find({ age: [ 23, 43 ] }).toArray();
/// it should query __nested document__ fields only by exact match
// TODO: we currently cannot enforce field order but field order is important for mongo
await collectionT.find({ addedBy: sampleUser }).toArray();
/// nested documents query should contain all required fields
// $ExpectError
await collectionT.find({ addedBy: { family: 'Anderson' } }).toArray();
/// it should not accept wrong types for nested document fields
// $ExpectError
await collectionT.find({ addedBy: 21 }).toArray();
// $ExpectError
await collectionT.find({ addedBy: 'Anderson' }).toArray();
// $ExpectError
await collectionT.find({ addedBy: [ sampleUser ] }).toArray();
// $ExpectError
await collectionT.find({ addedBy: [ { family: 'Anderson' } ] }).toArray();
/// it should query __array__ fields by exact match
await collectionT.find({ schools: ['s1', 's2', 's3'] }).toArray();
/// it should query __array__ fields by element type
await collectionT.find({ schools: 's1' }).toArray();
await collectionT.find({ schools: /s1/i }).toArray();
await collectionT.find({ scores: 23 }).toArray();
await collectionT.find({ friends: sampleUser }).toArray();
/// it should not query array fields by wrong types
// $ExpectError
await collectionT.find({ schools: 12 }).toArray();
// $ExpectError
await collectionT.find({ scores: 'high' }).toArray();
// $ExpectError
await collectionT.find({ friends: { name: 'hellow' } }).toArray();
/// it should accept MongoDB ObjectId and Date as query parameter
await collectionT.find({ createdAt: new Date() }).toArray();
await collectionT.find({ _id: new ObjectId() }).toArray();
/// it should not accept other types for ObjectId and Date
// $ExpectError
await collectionT.find({ createdAt: { a: 12 } }).toArray();
// $ExpectError
await collectionT.find({ createdAt: sampleUser }).toArray();
// $ExpectError
await collectionT.find({ _id: "577fa2d90c4cc47e31cf4b6f" }).toArray();
// $ExpectError
await collectionT.find({ _id: { a: 12 } }).toArray();
/**
* test comparison query operators
*/
/// $eq $ne $gt $gte $lt $lte queries should behave exactly like simple queries above
await collectionT.find({ name: { $eq: 'John' } }).toArray();
await collectionT.find({ name: { $eq: /Jack/ } }).toArray();
await collectionT.find({ gender: { $eq: 'male' } }).toArray();
await collectionT.find({ age: { $gt: 12, $lt: 13 } }).toArray();
await collectionT.find({ schools: { $eq: '12' } }).toArray();
await collectionT.find({ scores: { $gte: 23 } }).toArray();
await collectionT.find({ createdAt: { $lte: new Date() } }).toArray();
await collectionT.find({ friends: { $ne: sampleUser } }).toArray();
/// it should not accept wrong queries
// $ExpectError
await collectionT.find({ name: { $ne: 12 }}).toArray();
// $ExpectError
await collectionT.find({ gender: { $eq: '123' }}).toArray();
// $ExpectError
await collectionT.find({ createdAt: { $lte: '1232' } }).toArray();
/// it should not accept undefined query selectors in query object
// $ExpectError
await collectionT.find({ age: { $undefined: 12 } }).toArray();
/// it should query simple fields using $in and $nin selectors
await collectionT.find({ name: { $in: [ 'John', 'Jack', 'Joe' ] } }).toArray();
await collectionT.find({ age: { $in: [ 12, 13 ] } }).toArray();
await collectionT.find({ friends: { $in: [ sampleUser ] } }).toArray();
await collectionT.find({ createdAt: { $nin: [ new Date() ] } }).toArray();
/// it should query array fields using $in and $nin selectors
await collectionT.find({ schools: { $in: [ 's1', 's21', 's43' ] } }).toArray();
await collectionT.find({ schools: { $in: [ /r1/, /s21/, /s43/ ] } }).toArray();
await collectionT.find({ scores: { $in: [ 23, 43 ] } }).toArray();
await collectionT.find({ scores: { $in: [ [ 100, 90, 80 ] ] } }).toArray();
/// it should not accept wrong params for $in and $nin selectors
// $ExpectError
await collectionT.find({ name: { $in: [ 'John', 32, 42 ] } }).toArray();
// $ExpectError
await collectionT.find({ age: { $in: [ /12/, 12 ] } }).toArray();
// $ExpectError
await collectionT.find({ createdAt: { $nin: [ 12 ] } }).toArray();
// $ExpectError
await collectionT.find({ friends: { $in: [ { name: 'Pete' } ] } }).toArray();
// $ExpectError
await collectionT.find({ schools: { $in: [ { $eq: 21 } ] }}).toArray();
/**
* test logical query operators
*/
/// it should accept any query selector for __$not operator__
await collectionT.find({ name: { $not: { $eq: 'John' } } }).toArray();
/// it should accept regex for string fields
await collectionT.find({ name: { $not: /Hi/i } }).toArray();
await collectionT.find({ schools: { $not: /Hi/ } }).toArray();
/// it should not accept simple queries in $not operator
// $ExpectError
await collectionT.find({ name: { $not: 'John' } }).toArray();
/// it should not accept regex for non strings
// $ExpectError
await collectionT.find({ age: { $not: /sdsd/ } }).toArray();
/// it should accept any filter query for __$and, $or, $nor operator__
await collectionT.find({ $and: [ { name: 'John' } ]}).toArray();
await collectionT.find({ $and: [ { name: 'John' }, { age: { $in: [ 12, 14 ] } } ]}).toArray();
await collectionT.find({ $or: [ { name: /John/i }, { schools: 's12' } ]}).toArray();
await collectionT.find({ $nor: [ { name: { $ne: 'John' } } ]}).toArray();
/// it should not accept __$and, $or, $nor operator__ as non-root query
// $ExpectError
await collectionT.find({ name: { $or: [ 'John', 'Joe' ] } }).toArray();
/// it should not accept single objects for __$and, $or, $nor operator__ query
// $ExpectError
await collectionT.find({ $and: { name: 'John' } }).toArray();
/**
* test 'element' query operators
*/
/// it should query using $exists
await collectionT.find({ name: { $exists: true } }).toArray();
await collectionT.find({ name: { $exists: false } }).toArray();
/// it should not query $exists by wrong values
// $ExpectError
await collectionT.find({ name: { $exists: '' } }).toArray();
// $ExpectError
await collectionT.find({ name: { $exists: 'true' } }).toArray();
/**
* test evaluation query operators
*/
/// it should query using $regex
await collectionT.find({ name: { $regex: /12/i } }).toArray();
/// it should query using $regex and $options
await collectionT.find({ name: { $regex: /12/, $options: 'i' } }).toArray();
/// it should not accept $regex for none string fields
// $ExpectError
await collectionT.find({ age: { $regex: /12/ } }).toArray();
// $ExpectError
await collectionT.find({ age: { $options: '3' } }).toArray();
/// it should query using $mod
await collectionT.find({ age: { $mod: [ 12, 2 ] } }).toArray();
/// it should not accept $mod for none number fields
// $ExpectError
await collectionT.find({ name: { $mod: [ 12, 2 ] } }).toArray();
/// it should not accept $mod with less/more than 2 elements
// $ExpectError
await collectionT.find({ age: { $mod: [ 12, 2, 2 ] } }).toArray();
// $ExpectError
await collectionT.find({ age: { $mod: [ 12 ] } }).toArray();
// $ExpectError
await collectionT.find({ age: { $mod: [ ] } }).toArray();
/// it should fulltext search using $text
await collectionT.find({ $text: { $search: 'Hello' } }).toArray();
await collectionT.find({ $text: { $search: 'Hello', $caseSensitive: true } }).toArray();
/// it should fulltext search only by string
// $ExpectError
await collectionT.find({ $text: { $search: 21, $caseSensitive: 'true' } }).toArray();
// $ExpectError
await collectionT.find({ $text: { $search: { name: 'hellow' } } }).toArray();
// $ExpectError
await collectionT.find({ $text: { $search: /regex/g } }).toArray();
/// it should query using $where
await collectionT.find({ $where: "functin() { return true }" }).toArray();
await collectionT.find({ $where: function (this: any) { return this.name === "hellow"; }}).toArray();
/// it should not fail when $where is not Function or String
// $ExpectError
await collectionT.find({ $where: 12 }).toArray();
// $ExpectError
await collectionT.find({ $where: /regex/g }).toArray();
/**
* test array query operators
*/
/// it should query array fields
await collectionT.find({ schools: { $size: 2 } }).toArray();
await collectionT.find({ schools: { $all: [ 's1', 's2' ] } }).toArray();
await collectionT.find({ friends: { $elemMatch: { name: 'Joe' } } }).toArray();
/// it should not query non array fields
// $ExpectError
await collectionT.find({ name: { $all: [ 'world', 'world' ] } }).toArray();
// $ExpectError
await collectionT.find({ age: { $elemMatch: [ 'world', 'world' ] } }).toArray();
// $ExpectError
await collectionT.find({ gender: { $size: 2 } }).toArray();
} | the_stack |
import { Option, Some, None } from "../src/Option";
import { Vector } from "../src/Vector";
import { instanceOf } from "../src/Comparison";
import { Seq } from "../src/Seq";
import { MyClass, MySubclass } from "./SampleData";
import { assertFailCompile } from "./TestHelpers";
import * as assert from 'assert'
describe("option creation", () => {
it("should create a Some for Option.ofNullable(0)", () => {
assert.ok(Option.ofNullable(0).equals(Option.of(0)));
assert.ok(Option.ofNullable(0).isSome());
});
});
describe("option comparison", () => {
it("should mark equal options as equal", () =>
assert.ok(Option.of(5).equals(Option.of(5))))
it("should mark different options as not equal", () =>
assert.ok(!Option.of(5).equals(Option.of(6))))
it("should mark none as equals to none", () =>
assert.ok(Option.none<string>().equals(Option.none<string>())));
it("should mark none and some as not equal", () =>
assert.ok(!Option.of(5).equals(Option.none<number>())));
it("should mark none and some as not equal", () =>
assert.ok(!Option.none<number>().equals(Option.of(5))));
it("should return true on contains", () =>
assert.ok(Option.of(5).contains(5)));
it("should return false on contains on none", () =>
assert.ok(!Option.none().contains(5)));
it("should return false on contains", () =>
assert.ok(!Option.of(6).contains(5)));
it("doesn't throw when given another type on equals", () => assert.equal(
false, Option.of(1).equals(<any>[1,2])));
it("doesn't throw when given null on equals", () => assert.equal(
false, Option.of(1).equals(<any>null)));
it("empty doesn't throw when given another type on equals", () => assert.equal(
false, Option.none().equals(<any>[1,2])));
it("empty doesn't throw when given null on equals", () => assert.equal(
false, Option.none().equals(<any>null)));
it("should throw when comparing options without true equality", () => assert.throws(
() => Option.of(Vector.of([1])).equals(Option.of(Vector.of([1])))));
it("should fail compilation on an obviously bad equality test", () =>
assertFailCompile(
"Option.of([1]).equals(Option.of([1]))", "Argument of type \'" +
"Option<number[]>\' is not assignable to parameter"));
it("should fail compilation on an obviously bad contains test", () =>
assertFailCompile(
"Option.of([1]).contains([1])",
"Argument of type \'number[]\' is not assignable to parameter"));
});
describe("option transformation", () => {
it("should transform with map", () => {
assert.ok(Option.of(5).equals(Option.of(4).map(x=>x+1)));
});
it("should return the original Some with orCall", () => {
assert.ok(Option.of(5).equals(Option.of(5).orCall(() => Option.none())));
});
it("should call the function when calling orCall on None", () => {
assert.ok(Option.of(5).equals(Option.none<number>().orCall(() => Option.of(5))));
});
it("should handle null as Some", () =>
assert.ok(Option.of(5).map<number|null>(x => null).equals(Option.of<number|null>(null))));
it("should transform a Some to string properly", () =>
assert.equal("Some(5)", Option.of(5).toString()));
it("should transform a None to string properly", () =>
assert.equal("None()", Option.none().toString()));
it("should transform with flatMap x->y", () => {
assert.ok(Option.of(5).equals(Option.of(4).flatMap(x=>Option.of(x+1))));
});
it("should transform with flatMap x->none", () => {
assert.ok(Option.none<number>().equals(Option.of(4).flatMap(x=>Option.none<number>())));
});
it("should transform with flatMap none->none", () => {
assert.ok(Option.none<number>().equals(Option.none<number>().flatMap(x=>Option.of(x+1))));
});
it("should filter some->some", () =>
assert.ok(Option.of(5).equals(Option.of(5).filter(x => x>2))));
it("should filter some->none", () =>
assert.ok(Option.of(5).filter(x => x<2).isNone()));
it("should filter none->none", () =>
assert.ok(Option.none<number>().filter(x => x<2).isNone()));
it("filter upcasts if possible", () => {
// here we only want to check that the code does compile,
// that 'x' is correctly seen has MySubclass in the 3rd line
Option.of<MyClass>(new MySubclass("a",1,"b"))
.filter(instanceOf(MySubclass))
.filter(x => x.getField3().length>1);
});
it("should apply match to a some", () =>
assert.equal(5, Option.of(4).match({
Some: x=>x+1,
None: ()=>-1
})));
it("should apply match to a nome", () =>
assert.equal(-1, Option.none<number>().match({
Some: x=>x+1,
None: ()=>-1
})));
it("some supports transform", () =>
assert.equal(6, Option.of(3).transform(x => 6)));
it("none supports transform", () =>
assert.equal(6, Option.none<number>().transform(x => 6)));
it("should support lists combining some & none", () => {
const a = <Some<number>>Option.of(5);
const b = <None<number>>Option.none<number>();
const c = Vector.of<Option<number>>(a, b);
});
});
describe("Option helpers", () => {
it("should do sequence when all are some", () =>
assert.ok(
Option.of(<Seq<number>>Vector.of(1,2,3)).equals(
Option.sequence(Vector.of(Option.of(1), Option.of(2), Option.of(3))))));
it("should fail sequence when some are none", () =>
assert.ok(
Option.sequence(Vector.of(Option.of(1), Option.none<number>(), Option.of(3))).isNone()));
it("should liftA2", () => assert.ok(Option.of(11).equals(
Option.liftA2((x:number,y:number) => x+y)(Option.of(5), Option.of(6)))));
it("should abort liftA2 on none", () => assert.ok(Option.none<number>().equals(
Option.liftA2((x:number,y:number) => x+y)(Option.of(5), Option.none<number>()))));
it("should liftAp", () => assert.ok(Option.of(14).equals(
Option.liftAp((x:{a:number,b:number,c:number}) => x.a+x.b+x.c)
({a:Option.of(5), b:Option.of(6), c:Option.of(3)}))));
it("should abort liftAp on none", () => assert.ok(Option.none<number>().equals(
Option.liftAp((x:{a:number,b:number}) => x.a+x.b)
({a:Option.of(5), b:Option.none<number>()}))));
it("should support ifSome on Some", () => {
let x = 0;
Option.of(5).ifSome(v => x=v);
assert.equal(5, x);
});
it("should support ifSome on None", () => {
let x = 0;
Option.of(5).filter(x=>x<0).ifSome(v => x=v);
assert.equal(0, x);
});
it("should support ifNone on Some", () => {
let x = 0;
Option.of(5).ifNone(() => x=5);
assert.equal(0, x);
});
it("should support ifNone on None", () => {
let x = 0;
Option.of(5).filter(x=>x<0).ifNone(() => x=5);
assert.equal(5, x);
});
});
describe("option retrieval", () => {
it("should return the value on Some.getOrElse", () =>
assert.equal(5, Option.of(5).getOrElse(6)));
it("should return the alternative on None.getOrElse", () =>
assert.equal(6, Option.none().getOrElse(6)));
it("should return the value on Some.toVector", () =>
assert.deepEqual([5], Option.of(5).toVector().toArray()));
it("should return empty on None.toVector", () =>
assert.deepEqual([], Option.none().toVector().toArray()));
it("should not throw on Some.getOrThrow", () =>
assert.equal(5, Option.of(5).getOrThrow()));
it("should throw on None.getOrThrow", () =>
assert.throws(() => Option.none().getOrThrow()));
it("should throw on None.getOrThrow with custom msg", () =>
assert.throws(() => Option.none().getOrThrow("my custom msg"),
(err: Error) => err.message === 'my custom msg'));
it("should offer get() if i checked for isSome", () => {
const opt = <Option<number>>Option.of(5);
if (opt.isSome()) {
// what we are checking here is whether this does build
// .get() is available only on Some not on None
assert.equal(5, opt.get());
}
});
it("should offer get() if i eliminated isNone", () => {
const opt = <Option<number>>Option.of(5);
if (!opt.isNone()) {
// what we are checking here is whether this does build
// .get() is available only on Some not on None
assert.equal(5, opt.get());
}
});
it("should allow some & none in a list", () => {
const a = Option.of(5);
const b = Option.none<number>();
if (a.isSome() && b.isNone()) {
Vector.of(a.asOption(),b);
}
})
});
describe("lifting", () => {
it("should lift 0-parameter functions", () => {
assert.ok(Option.lift(()=>1)().equals(Option.of(1)));
assert.ok(Option.lift(()=>undefined)().isNone());
assert.ok(Option.lift(()=>{throw "x"})().isNone());
});
it("should lift 1-parameter functions", () => {
assert.ok(Option.lift((x:number)=>x+1)(1).equals(Option.of(2)));
assert.ok(Option.lift((x:number)=>undefined)(1).isNone());
assert.ok(Option.lift((x:number)=>{throw "x"})(1).isNone());
});
it("should lift 2-parameter functions", () => {
assert.ok(Option.lift(
(x:number,y:number)=>x+1)(1,2).equals(Option.of(2)));
assert.ok(Option.lift(
(x:number,y:number)=>undefined)(1,2).isNone());
assert.ok(Option.lift(
(x:number,y:number)=>{throw "x"})(1,2).isNone());
});
it("should lift 3-parameter functions" , () => {
assert.ok(Option.lift(
(x:number,y:number,z:number)=>x+1)(1,2,3).equals(Option.of(2)));
assert.ok(Option.lift(
(x:number,y:number,z:number)=>undefined)(1,2,3).isNone());
assert.ok(Option.lift(
(x:number,y:number,z:number)=>{throw "x"})(1,2,3).isNone());
});
it("should lift 4-parameter functions", () => {
assert.ok(Option.lift(
(x:number,y:number,z:number,a:number)=>x+1)(1,2,3,4).equals(Option.of(2)));
assert.ok(Option.lift(
(x:number,y:number,z:number,a:number)=>undefined)(1,2,3,4).isNone());
assert.ok(Option.lift(
(x:number,y:number,z:number,a:number)=>{throw "x"})(1,2,3,4).isNone());
});
it("should lift 5-parameter functions", () => {
assert.ok(Option.lift(
(x:number,y:number,z:number,a:number,b:number)=>x+1)(1,2,3,4,5).equals(Option.of(2)));
assert.ok(Option.lift(
(x:number,y:number,z:number,a:number,b:number)=>undefined)(1,2,3,4,5).isNone());
assert.ok(Option.lift(
(x:number,y:number,z:number,a:number,b:number)=>{throw "x"})(1,2,3,4,5).isNone());
});
}); | the_stack |
import { Collection } from "./collection";
import { CloneMethod } from "./clone";
import { Doc } from "../../common/types";
import { Scorer } from "../../full-text-search/src/scorer";
import { Query as FullTextSearchQuery } from "../../full-text-search/src/query_types";
/**
* ResultSet class allowing chainable queries. Intended to be instanced internally.
* Collection.find(), Collection.where(), and Collection.chain() instantiate this.
*
* @example
* mycollection.chain()
* .find({ 'doors' : 4 })
* .where(function(obj) { return obj.name === 'Toyota' })
* .data();
*
* @param <TData> - the data type
* @param <TNested> - nested properties of data type
*/
export declare class ResultSet<T extends object = object> {
_collection: Collection<T>;
_filteredRows: number[];
_filterInitialized: boolean;
private _scoring;
/**
* Constructor.
* @param {Collection} collection - the collection which this ResultSet will query against
*/
constructor(collection: Collection<T>);
/**
* Reset the ResultSet to its initial state.
* @returns {ResultSet} Reference to this ResultSet, for future chain operations.
*/
reset(): this;
/**
* Override of toJSON to avoid circular references
*/
toJSON(): ResultSet<T>;
/**
* Allows you to limit the number of documents passed to next chain operation.
* A ResultSet copy() is made to avoid altering original ResultSet.
* @param {int} qty - The number of documents to return.
* @returns {ResultSet} Returns a copy of the ResultSet, limited by qty, for subsequent chain ops.
*/
limit(qty: number): this;
/**
* Used for skipping 'pos' number of documents in the ResultSet.
* @param {int} pos - Number of documents to skip; all preceding documents are filtered out.
* @returns {ResultSet} Returns a copy of the ResultSet, containing docs starting at 'pos' for subsequent chain ops.
*/
offset(pos: number): this;
/**
* To support reuse of ResultSet in branched query situations.
* @returns {ResultSet} Returns a copy of the ResultSet (set) but the underlying document references will be the same.
*/
copy(): ResultSet<T>;
/**
* Executes a named collection transform or raw array of transform steps against the ResultSet.
* @param {(string|array)} transform - name of collection transform or raw transform array
* @param {object} [parameters=] - object property hash of parameters, if the transform requires them.
* @returns {ResultSet} either (this) ResultSet or a clone of of this ResultSet (depending on steps)
*/
transform(transform: string | Collection.Transform<T>[], parameters?: object): this;
/**
* User supplied compare function is provided two documents to compare. (chainable)
* @example
* rslt.sort(function(obj1, obj2) {
* if (obj1.name === obj2.name) return 0;
* if (obj1.name > obj2.name) return 1;
* if (obj1.name < obj2.name) return -1;
* });
* @param {function} comparefun - A javascript compare function used for sorting.
* @returns {ResultSet} Reference to this ResultSet, sorted, for future chain operations.
*/
sort(comparefun: (a: Doc<T>, b: Doc<T>) => number): this;
/**
* Simpler, loose evaluation for user to sort based on a property name. (chainable).
* Sorting based on the same lt/gt helper functions used for binary indices.
* @param {string} propname - name of property to sort by.
* @param {boolean|object=} options - boolean for sort descending or options object
* @param {boolean} [options.desc=false] - whether to sort descending
* @param {string} [options.sortComparator] override default with name of comparator registered in ComparatorMap
* @returns {ResultSet} Reference to this ResultSet, sorted, for future chain operations.
*/
simplesort(propname: keyof T, options?: boolean | ResultSet.SimpleSortOptions): this;
/**
* Allows sorting a ResultSet based on multiple columns.
* @example
* // to sort by age and then name (both ascending)
* rs.compoundsort(['age', 'name']);
* // to sort by age (ascending) and then by name (descending)
* rs.compoundsort(['age', ['name', true]);
* @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order
* @returns {ResultSet} Reference to this ResultSet, sorted, for future chain operations.
*/
compoundsort(properties: (keyof T | [keyof T, boolean])[]): this;
/**
* Helper function for compoundsort(), performing individual object comparisons
* @param {Array} properties - array of property names, in order, by which to evaluate sort order
* @param {object} obj1 - first object to compare
* @param {object} obj2 - second object to compare
* @returns {number} 0, -1, or 1 to designate if identical (sortwise) or which should be first
*/
private _compoundeval(properties, obj1, obj2);
/**
* Sorts the ResultSet based on the last full-text-search scoring.
* @param {boolean} [ascending=false] - sort ascending
* @returns {ResultSet}
*/
sortByScoring(ascending?: boolean): this;
/**
* Returns the scoring of the last full-text-search.
* @returns {ScoreResult[]}
*/
getScoring(): Scorer.ScoreResult[];
/**
* Oversee the operation of OR'ed query expressions.
* OR'ed expression evaluation runs each expression individually against the full collection,
* and finally does a set OR on each expression's results.
* Each evaluation can utilize a binary index to prevent multiple linear array scans.
* @param {array} expressionArray - array of expressions
* @returns {ResultSet} this ResultSet for further chain ops.
*/
findOr(expressionArray: ResultSet.Query<Doc<T>>[]): this;
$or(expressionArray: ResultSet.Query<Doc<T>>[]): this;
/**
* Oversee the operation of AND'ed query expressions.
* AND'ed expression evaluation runs each expression progressively against the full collection,
* internally utilizing existing chained ResultSet functionality.
* Only the first filter can utilize a binary index.
* @param {array} expressionArray - array of expressions
* @returns {ResultSet} this ResultSet for further chain ops.
*/
findAnd(expressionArray: ResultSet.Query<Doc<T>>[]): this;
$and(expressionArray: ResultSet.Query<Doc<T>>[]): this;
/**
* Used for querying via a mongo-style query object.
*
* @param {object} query - A mongo-style query object used for filtering current results.
* @param {boolean} firstOnly - (Optional) Used by collection.findOne() - flag if this was invoked via findOne()
* @returns {ResultSet} this ResultSet for further chain ops.
*/
find(query?: ResultSet.Query<Doc<T>>, firstOnly?: boolean): this;
/**
* Used for filtering via a javascript filter function.
* @param {function} fun - A javascript function used for filtering current results by.
* @returns {ResultSet} this ResultSet for further chain ops.
*/
where(fun: (obj: Doc<T>) => boolean): this;
/**
* Returns the number of documents in the ResultSet.
* @returns {number} The number of documents in the ResultSet.
*/
count(): number;
/**
* Terminates the chain and returns array of filtered documents
* @param {object} options
* @param {boolean} [options.forceClones] - Allows forcing the return of cloned objects even when
* the collection is not configured for clone object.
* @param {string} [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method.
* Possible values 'parse-stringify', 'deep', and 'shallow' and
* @param {boolean} [options.removeMeta] - will force clones and strip $loki and meta properties from documents
*
* @returns {Array} Array of documents in the ResultSet
*/
data(options?: ResultSet.DataOptions): Doc<T>[];
/**
* Used to run an update operation on all documents currently in the ResultSet.
* @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object.
* @returns {ResultSet} this ResultSet for further chain ops.
*/
update(updateFunction: (obj: Doc<T>) => Doc<T>): this;
/**
* Removes all document objects which are currently in ResultSet from collection (as well as ResultSet)
* @returns {ResultSet} this (empty) ResultSet for further chain ops.
*/
remove(): this;
/**
* data transformation via user supplied functions
*
* @param {function} mapFunction - this function accepts a single document for you to transform and return
* @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value
* @returns {value} The output of your reduceFunction
*/
mapReduce<U1, U2>(mapFunction: (item: Doc<T>, index: number, array: Doc<T>[]) => U1, reduceFunction: (array: U1[]) => U2): U2;
/**
* Left joining two sets of data. Join keys can be defined or calculated properties
* eqJoin expects the right join key values to be unique. Otherwise left data will be joined on the last joinData object with that key
* @param {Array|ResultSet|Collection} joinData - Data array to join to.
* @param {(string|function)} leftJoinKey - Property name in this result set to join on or a function to produce a value to join on
* @param {(string|function)} rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on
* @param {function} [mapFun=] - a function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject}
* @param {object} [dataOptions=] - optional options to apply to data() calls for left and right sides
* @param {boolean} dataOptions.removeMeta - allows removing meta before calling mapFun
* @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
* @param {string} dataOptions.forceCloneMethod - allows overriding the default or collection specified cloning method
* @returns {ResultSet} A ResultSet with data in the format [{left: leftObj, right: rightObj}]
*/
eqJoin(joinData: Collection<any> | ResultSet<any> | any[], leftJoinKey: string | ((obj: any) => string), rightJoinKey: string | ((obj: any) => string), mapFun?: (left: any, right: any) => any, dataOptions?: ResultSet.DataOptions): ResultSet<any>;
/**
* Applies a map function into a new collection for further chaining.
* @param {function} mapFun - javascript map function
* @param {object} [dataOptions=] - options to data() before input to your map function
* @param {boolean} dataOptions.removeMeta - allows removing meta before calling mapFun
* @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object
* @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method
* @return {ResultSet}
*/
map<U extends object>(mapFun: (obj: Doc<T>, index: number, array: Doc<T>[]) => U, dataOptions?: ResultSet.DataOptions): ResultSet<U>;
}
export declare namespace ResultSet {
interface DataOptions {
forceClones?: boolean;
forceCloneMethod?: CloneMethod;
removeMeta?: boolean;
}
interface SimpleSortOptions {
desc?: boolean;
sortComparator?: string;
}
type ContainsHelperType<R> = R extends string ? string | string[] : R extends any[] ? R[number] | R[number][] : R extends object ? keyof R | (keyof R)[] : never;
type LokiOps<R> = {
$eq?: R;
} | {
$ne?: R;
} | {
$gt?: R;
} | {
$gte?: R;
} | {
$lt?: R;
} | {
$lte?: R;
} | {
$between?: [R, R];
} | {
$in?: R[];
} | {
$nin?: R[];
} | {
$keyin?: object;
} | {
$nkeyin?: object;
} | {
$definedin?: object;
} | {
$undefinedin?: object;
} | {
$regex?: RegExp | string | [string, string];
} | {
$containsNone?: ContainsHelperType<R>;
} | {
$containsAny?: ContainsHelperType<R>;
} | {
$contains?: ContainsHelperType<R>;
} | {
$type?: string;
} | {
$finite?: boolean;
} | {
$size?: number;
} | {
$len?: number;
} | {
$where?: (val?: R) => boolean;
};
type Query<T> = {
[P in keyof T]?: LokiOps<T[P]> | T[P];
} & {
$and?: Query<T>[];
} & {
$or?: Query<T>[];
} & {
$fts?: FullTextSearchQuery;
};
} | the_stack |
import { sr25519Verify, waitReady } from '@polkadot/wasm-crypto'
import { KusamaProtocol } from '../../../src/protocols/substrate/kusama/KusamaProtocol'
import { SubstrateNetwork } from '../../../src/protocols/substrate/SubstrateNetwork'
import { AirGapWalletStatus } from '../../../src/wallet/AirGapWallet'
import { TestProtocolSpec } from '../implementations'
import { KusamaProtocolStub } from '../stubs/kusama.stub'
/*
* Test Mnemonic: leopard crouch simple blind castle they elder enact slow rate mad blanket saddle tail silk fury quarter obscure interest exact veteran volcano fabric cherry
*
*/
// Test Mnemonic: food talent voyage degree siege clever account medal film remind good kind
// Derivation path: m/
// Private Key: d08bc6388fdeb30fc34a8e0286384bd5a84b838222bb9b012fc227d7473fc87aa2913d02297653ce859ccd6b2c057f7e57c9ef6cc359300a891c581fb6d03141
// Public Key: 52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10
// Hex Seed: 55a1417bbfacd64e069b4d07e47fb34ce9ff53b15556698038604f002524aec0
// Address (Kusama SS58): ESzXrcSsbM3Jxzuz2zczuYgCXsxQrqPw29AR2doaxZdzemT
export class KusamaTestProtocolSpec extends TestProtocolSpec {
public name = 'Kusama'
public lib = new KusamaProtocol()
public stub = new KusamaProtocolStub()
public validAddresses = [
'EEWyMLHgwtemr48spFNnS3U2XjaYswqAYAbadx2jr9ppp4X',
'HTy49kysog4fCwjsCeZXzEFQ1YyuwfUpJS6UhS9jRKtaWKM',
'CjEiyp4VU7o5pvSXCvLbKjd8xohwmTtgRysiuKssu4Ye7K5',
'GHszz6ePQwec9voFXNe7h2DmkcgwGvPKzY2LbdksHimHmAp',
'F2TTnBLPaccoLimZvVGts4LAoWzQR1EY9NrjPc61gU2Nkje',
'CupYGbY1cY8ErcAwQoxp97KKAf1RUPH4m3ZArr7rekfkUoc',
'HeCLXHxxN7dKistZLvoaTNGZcY2GXjH9SaGKvVwRyDbvFwW',
'GvK1ubf7dbMogDbJH4YibMyyWBbxACtn9SSPEqxMWunBv2E',
'G71LDs8bA4xYmhkZK24ndPYRhZfWVXqKtNjq1rb84J8FLfu',
'GsUbgMs2f8BvcD5RPRGNZJtByKfqj3PrqSBwp8m1DrVR5s8'
]
public wallet = {
privateKey:
'd08bc6388fdeb30fc34a8e0286384bd5a84b838222bb9b012fc227d7473fc87aa2913d02297653ce859ccd6b2c057f7e57c9ef6cc359300a891c581fb6d03141',
publicKey: '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10',
addresses: ['ESzXrcSsbM3Jxzuz2zczuYgCXsxQrqPw29AR2doaxZdzemT'],
masterFingerprint: 'f4e222fd',
status: AirGapWalletStatus.ACTIVE
}
public txs = [
{
from: this.wallet.addresses,
to: this.wallet.addresses,
amount: '1000000000000',
fee: '1000000000',
unsignedTx: {
encoded:
// tslint:disable-next-line: prefer-template
'04' + // number of txs
'2106' + // tx length
'01' + // optional type (specVersion)
'ee070000' + // specVersion
'00' + // type
'02286bee' + // fee
// transaction
'4102' + // length
'84' + // signed flag (not signed)
'00' + // MultiAddress type
'52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId signer
'00' + // signature type (ed25519)
'0000000000000000000000000000000000000000000000000000000000000000' + // signature
'0000000000000000000000000000000000000000000000000000000000000000' + // signature
'8503' + // era
'04' + // nonce
'00' + // tip
'0400' + // moduleId + callId
'00' + // MultiAddress type
'52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination
'070010a5d4e8' + // value
// payload
'a903' + // payload length
Buffer.from(
'0400' + // moduleId + callId
'00' + // MultiAddress type
'52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination
'070010a5d4e8' + // value
'8503' + // era
'04' + // nonce
'00' + // tip
'ee070000' + // specVersion
'01000000' + // transactionVersion
'd51522c9ef7ba4e0990f7a4527de79afcac992ab97abbbc36722f8a27189b170' + // genesis hash
'33a7a745849347ce3008c07268be63d8cefd3ef61de0c7318e88a577fb7d26a9' // block hash
).toString('hex') // payload
},
signedTx:
// tslint:disable-next-line: prefer-template
'04' + // number of txs
'2106' + // tx length
'01' + // optional type (specVersion)
'ee070000' + // specVersion
'00' + // type
'02286bee' + // fee
// transaction
'4102' + // length
'84' + // signed flag (signed)
'00' + // MultiAddress type
'52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId signer
'00' + // signature type (ed25519)
'e209d71282bbff8af2f4362e4b478d156c9c1df81e2a7d733912525308909a16' + // signature
'adf7eb5602136d4b0a9a57acdd07a443f3bc4865c2455bf36f01ff9fa9b4478d' + // signature
'8503' + // era
'04' + // nonce
'00' + // tip
'0400' + // moduleId + callId
'00' + // MultiAddress type
'52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination
'070010a5d4e8' + // value
// payload
'a903' + // payload length
Buffer.from(
'0400' + // moduleId + callId
'00' + // MultiAddress type
'52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination
'070010a5d4e8' + // value
'8503' + // era
'04' + // nonce
'00' + // tip
'ee070000' + // specVersion
'01000000' + // transactionVersion
'd51522c9ef7ba4e0990f7a4527de79afcac992ab97abbbc36722f8a27189b170' + // genesis hash
'33a7a745849347ce3008c07268be63d8cefd3ef61de0c7318e88a577fb7d26a9' // block hash
).toString('hex') // payload
}
]
public verifySignature = async (publicKey: string, tx: any): Promise<boolean> => {
await waitReady()
const decoded = this.lib.options.transactionController.decodeDetails(tx)[0]
const signature = decoded.transaction.signature.signature.value
const payload = Buffer.from(decoded.payload, 'hex')
const publicKeyBuffer = Buffer.from(publicKey, 'hex')
return sr25519Verify(signature, payload, publicKeyBuffer)
}
public seed(): string {
return '55a1417bbfacd64e069b4d07e47fb34ce9ff53b15556698038604f002524aec0'
}
public mnemonic(): string {
return 'food talent voyage degree siege clever account medal film remind good kind'
}
public messages = [
{
message: 'example message',
signature:
'0x30094f45a892156fe1f79254674fdebe69da314b72371f3665aecdc486fd6233b7729571bf12765bb80cf07bd81846634a5a2e60045f492a492e2b40eee8ac8b'
}
]
public encryptAES = [
{
message: 'example message',
encrypted: 'b9a7091ad33077761052c00f44227a9a!ff56d06348ae96d9df03f811667a08!2b08382f04eb77bf66c5cab27d06f25a'
}
]
public transactionResult = {
transactions: [
{
protocolIdentifier: 'kusama',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://polkadot-kusama-node.prod.gke.papers.tech',
blockExplorer: { blockExplorer: 'https://polkascan.io/kusama' },
extras: { apiUrl: 'https://kusama.subscan.io/api/scan', network: SubstrateNetwork.KUSAMA }
},
from: ['GzgRTyefkykqf72gC8hGgDVa7p1MYTDyCwFjTsVc53FxZi7'],
to: ['EEWyMLHgwtemr48spFNnS3U2XjaYswqAYAbadx2jr9ppp4X'],
isInbound: true,
amount: '99977416667634',
fee: '2583332366',
timestamp: 1601036370,
hash: '0x33482af443df63c3b0c9b5920b0723256a1e69602bba0bbe50cae3cb469084a5',
blockHeight: 4200705,
status: 'applied'
},
{
protocolIdentifier: 'kusama',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://polkadot-kusama-node.prod.gke.papers.tech',
blockExplorer: { blockExplorer: 'https://polkascan.io/kusama' },
extras: { apiUrl: 'https://kusama.subscan.io/api/scan', network: SubstrateNetwork.KUSAMA }
},
from: ['EEWyMLHgwtemr48spFNnS3U2XjaYswqAYAbadx2jr9ppp4X'],
to: ['Dz5JAFYyLigyGnhDyrT5bJ6u8TxagA2muR1UFz7xQVVcfWA'],
isInbound: false,
amount: '1020000000000',
fee: '2583332366',
timestamp: 1601034570,
hash: '0xffef69ea4dbceef33bd904a2aaf92129cca4435642d7f71e85dbccb91d53c3af',
blockHeight: 4200409,
status: 'applied'
}
],
cursor: { page: 1 }
}
public nextTransactionResult = {
transactions: [
{
protocolIdentifier: 'kusama',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://polkadot-kusama-node.prod.gke.papers.tech',
blockExplorer: { blockExplorer: 'https://polkascan.io/kusama' },
extras: { apiUrl: 'https://kusama.subscan.io/api/scan', network: SubstrateNetwork.KUSAMA }
},
from: ['EEWyMLHgwtemr48spFNnS3U2XjaYswqAYAbadx2jr9ppp4X'],
to: ['DxAN9aGS117GJQNGSnaoPw5YVRCZD67DXC8aBzhJk9joK7X'],
isInbound: false,
amount: '15966000000000',
fee: '2599999026',
timestamp: 1601030652,
hash: '0xd02429787c9f28692018a2147ad093222857e686563c1166a1338fa9b624b9d3',
blockHeight: 4199759,
status: 'applied'
},
{
protocolIdentifier: 'kusama',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://polkadot-kusama-node.prod.gke.papers.tech',
blockExplorer: { blockExplorer: 'https://polkascan.io/kusama' },
extras: { apiUrl: 'https://kusama.subscan.io/api/scan', network: SubstrateNetwork.KUSAMA }
},
from: ['EEWyMLHgwtemr48spFNnS3U2XjaYswqAYAbadx2jr9ppp4X'],
to: ['DxAN9aGS117GJQNGSnaoPw5YVRCZD67DXC8aBzhJk9joK7X'],
isInbound: false,
amount: '3800000000000',
fee: '2599999026',
timestamp: 1601030412,
hash: '0x898a890d48861039715bd8d0671593ddf62c539f4b566fcab02859ff2b172c64',
blockHeight: 4199719,
status: 'applied'
}
],
cursor: { page: 2 }
}
} | the_stack |
import { Component, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { FormBuilder, Validators} from '@angular/forms';
import { FormArray, FormGroup, FormControl} from '@angular/forms';
import { InfluxServerService } from './influxservercfg.service';
import { ValidationService } from '../common/validation.service'
import { ExportServiceCfg } from '../common/dataservice/export.service'
import { GenericModal } from '../common/generic-modal';
import { ExportFileModal } from '../common/dataservice/export-file-modal';
import { Observable } from 'rxjs/Rx';
import { ItemsPerPageOptions } from '../common/global-constants';
import { TableActions } from '../common/table-actions';
import { AvailableTableActions } from '../common/table-available-actions';
import { TableListComponent } from '../common/table-list.component';
import { InfluxServerCfgComponentConfig, TableRole, OverrideRoleActions } from './influxservercfg.data';
declare var _:any;
@Component({
selector: 'influxservers',
providers: [InfluxServerService, ValidationService],
templateUrl: './influxservereditor.html',
styleUrls: ['../css/component-styles.css']
})
export class InfluxServerCfgComponent {
@ViewChild('viewModal') public viewModal: GenericModal;
@ViewChild('viewModalDelete') public viewModalDelete: GenericModal;
@ViewChild('exportFileModal') public exportFileModal : ExportFileModal;
itemsPerPageOptions : any = ItemsPerPageOptions;
editmode: string; //list , create, modify
influxservers: Array<any>;
filter: string;
influxserverForm: any;
myFilterValue: any;
alertHandler : any = null;
//Initialization data, rows, colunms for Table
private data: Array<any> = [];
public rows: Array<any> = [];
public tableAvailableActions : any;
selectedArray : any = [];
public defaultConfig : any = InfluxServerCfgComponentConfig;
public tableRole : any = TableRole;
public overrideRoleActions: any = OverrideRoleActions;
public isRequesting : boolean;
public counterItems : number = null;
public counterErrors: any = [];
public page: number = 1;
public itemsPerPage: number = 20;
public maxSize: number = 5;
public numPages: number = 1;
public length: number = 0;
private builder;
private oldID : string;
//Set config
public config: any = {
paging: true,
sorting: { columns: this.defaultConfig['table-columns'] },
filtering: { filterString: '' },
className: ['table-striped', 'table-bordered']
};
constructor(public influxServerService: InfluxServerService, public exportServiceCfg : ExportServiceCfg, builder: FormBuilder) {
this.editmode = 'list';
this.reloadData();
this.builder = builder;
}
createStaticForm() {
this.influxserverForm = this.builder.group({
ID: [this.influxserverForm ? this.influxserverForm.value.ID : '', Validators.required],
Host: [this.influxserverForm ? this.influxserverForm.value.Host : '', Validators.required],
Port: [this.influxserverForm ? this.influxserverForm.value.Port : '', Validators.compose([Validators.required, ValidationService.uintegerNotZeroValidator])],
DB: [this.influxserverForm ? this.influxserverForm.value.DB : '', Validators.required],
User: [this.influxserverForm ? this.influxserverForm.value.User : '', Validators.required],
Password: [this.influxserverForm ? this.influxserverForm.value.Password : '', Validators.required],
Retention: [this.influxserverForm ? this.influxserverForm.value.Retention : 'autogen', Validators.required],
Precision: [this.influxserverForm ? this.influxserverForm.value.Precision : 's', Validators.required],
Timeout: [this.influxserverForm ? this.influxserverForm.value.Timeout : 30, Validators.compose([Validators.required, ValidationService.uintegerNotZeroValidator])],
UserAgent: [this.influxserverForm ? this.influxserverForm.value.UserAgent : ''],
EnableSSL: [this.influxserverForm ? this.influxserverForm.value.EnableSSL : 'false'],
SSLCA: [this.influxserverForm ? this.influxserverForm.value.SSLCA : ''],
SSLCert: [this.influxserverForm ? this.influxserverForm.value.SSLCert : ''],
SSLKey: [this.influxserverForm ? this.influxserverForm.value.SSLKey : ''],
InsecureSkipVerify: [this.influxserverForm ? this.influxserverForm.value.InsecureSkipVerify : 'true'],
BufferSize: [this.influxserverForm ? this.influxserverForm.value.BufferSize : 65535, Validators.compose([Validators.required, ValidationService.uintegerNotZeroValidator])],
Description: [this.influxserverForm ? this.influxserverForm.value.Description : '']
});
}
reloadData() {
// now it's a simple subscription to the observable
this.alertHandler = null;
this.influxServerService.getInfluxServer(null)
.subscribe(
data => {
this.isRequesting = false;
this.influxservers = data
this.data = data;
},
err => console.error(err),
() => console.log('DONE')
);
}
applyAction(test : any, data? : Array<any>) : void {
this.selectedArray = data || [];
switch(test.action) {
case "RemoveAllSelected": {
this.removeAllSelectedItems(this.selectedArray);
break;
}
case "ChangeProperty": {
this.updateAllSelectedItems(this.selectedArray,test.field,test.value)
break;
}
case "AppendProperty": {
this.updateAllSelectedItems(this.selectedArray,test.field,test.value,true);
}
default: {
break;
}
}
}
customActions(action : any) {
switch (action.option) {
case 'export' :
this.exportItem(action.event);
break;
case 'new' :
this.newInfluxServer()
case 'view':
this.viewItem(action.event);
break;
case 'edit':
this.editInfluxServer(action.event);
break;
case 'remove':
this.removeItem(action.event);
break;
case 'tableaction':
this.applyAction(action.event, action.data);
break;
}
}
viewItem(id) {
console.log('view', id);
this.viewModal.parseObject(id);
}
exportItem(item : any) : void {
this.exportFileModal.initExportModal(item);
}
removeAllSelectedItems(myArray) {
let obsArray = [];
this.counterItems = 0;
this.isRequesting = true;
for (let i in myArray) {
console.log("Removing ",myArray[i].ID)
this.deleteInfluxServer(myArray[i].ID,true);
obsArray.push(this.deleteInfluxServer(myArray[i].ID,true));
}
this.genericForkJoin(obsArray);
}
removeItem(row) {
let id = row.ID;
console.log('remove', id);
this.influxServerService.checkOnDeleteInfluxServer(id)
.subscribe(
data => {
console.log(data);
let temp = data;
this.viewModalDelete.parseObject(temp)
},
err => console.error(err),
() => { }
);
}
newInfluxServer() {
//No hidden fields, so create fixed Form
this.createStaticForm();
this.editmode = "create";
}
editInfluxServer(row) {
let id = row.ID;
this.influxServerService.getInfluxServerById(id)
.subscribe(data => {
this.influxserverForm = {};
this.influxserverForm.value = data;
this.oldID = data.ID
this.createStaticForm();
this.editmode = "modify";
},
err => console.error(err)
);
}
deleteInfluxServer(id, recursive?) {
if (!recursive) {
this.influxServerService.deleteInfluxServer(id)
.subscribe(data => { },
err => console.error(err),
() => { this.viewModalDelete.hide(); this.editmode = "list"; this.reloadData() }
);
} else {
return this.influxServerService.deleteInfluxServer(id, true)
.do(
(test) => { this.counterItems++},
(err) => { this.counterErrors.push({'ID': id, 'error' : err})}
);
}
}
cancelEdit() {
this.editmode = "list";
this.reloadData();
}
saveInfluxServer() {
if (this.influxserverForm.valid) {
this.influxServerService.addInfluxServer(this.influxserverForm.value)
.subscribe(data => { console.log(data) },
err => {
console.log(err);
},
() => { this.editmode = "list"; this.reloadData() }
);
}
}
updateAllSelectedItems(mySelectedArray,field,value, append?) {
let obsArray = [];
this.counterItems = 0;
this.isRequesting = true;
if (!append)
for (let component of mySelectedArray) {
component[field] = value;
obsArray.push(this.updateInfluxServer(true,component));
} else {
let tmpArray = [];
if(!Array.isArray(value)) value = value.split(',');
console.log(value);
for (let component of mySelectedArray) {
console.log(value);
//check if there is some new object to append
let newEntries = _.differenceWith(value,component[field],_.isEqual);
tmpArray = newEntries.concat(component[field])
console.log(tmpArray);
component[field] = tmpArray;
obsArray.push(this.updateInfluxServer(true,component));
}
}
this.genericForkJoin(obsArray);
//Make sync calls and wait the result
this.counterErrors = [];
}
updateInfluxServer(recursive?, component?) {
if(!recursive) {
if (this.influxserverForm.valid) {
var r = true;
if (this.influxserverForm.value.ID != this.oldID) {
r = confirm("Changing Influx Server ID from " + this.oldID + " to " + this.influxserverForm.value.ID + ". Proceed?");
}
if (r == true) {
this.influxServerService.editInfluxServer(this.influxserverForm.value, this.oldID, true)
.subscribe(data => { console.log(data) },
err => console.error(err),
() => { this.editmode = "list"; this.reloadData() }
);
}
}
} else {
return this.influxServerService.editInfluxServer(component, component.ID)
.do(
(test) => { this.counterItems++ },
(err) => { this.counterErrors.push({'ID': component['ID'], 'error' : err['_body']})}
)
.catch((err) => {
return Observable.of({'ID': component.ID , 'error': err['_body']})
})
}
}
testInfluxServerConnection() {
this.influxServerService.testInfluxServer(this.influxserverForm.value, true)
.subscribe(
data => this.alertHandler = {msg: 'Influx Version: '+data['Message'], result : data['Result'], elapsed: data['Elapsed'], type: 'success', closable: true},
err => {
let error = err.json();
this.alertHandler = {msg: error['Message'], elapsed: error['Elapsed'], result : error['Result'], type: 'danger', closable: true}
},
() => { console.log("DONE")}
);
}
genericForkJoin(obsArray: any) {
Observable.forkJoin(obsArray)
.subscribe(
data => {
this.selectedArray = [];
this.reloadData()
},
err => console.error(err),
);
}
} | the_stack |
import { ByteArray } from './../../graphics/images/index';
import { TtfReader } from './ttf-reader';
import { TtfMetrics } from './ttf-metrics';
import { PdfDictionary, SaveDescendantFontEventHandler, SaveFontDictionaryEventHandler } from './../../primitives/pdf-dictionary';
import { SaveFontProgramEventHandler, SaveCmapEventHandler } from './../../primitives/pdf-stream';
import { PdfStream } from './../../primitives/pdf-stream';
import { PdfArray } from './../../primitives/pdf-array';
import { PdfName } from './../../primitives/pdf-name';
import { PdfNumber } from './../../primitives/pdf-number';
import { PdfString } from './../../primitives/pdf-string';
import { PdfReferenceHolder } from './../../primitives/pdf-reference';
import { PdfFontMetrics } from './pdf-font-metrics';
import { IPdfPrimitive } from './../../../interfaces/i-pdf-primitives';
import { StandardWidthTable } from './pdf-font-metrics';
import { DictionaryProperties } from './../../input-output/pdf-dictionary-properties';
import { Dictionary } from './../../collections/dictionary';
import { FontDescriptorFlags } from './enum';
import { RectangleF, Rectangle } from './../../drawing/pdf-drawing';
import { TtfGlyphInfo } from './ttf-glyph-info';
import { Operators } from './../../input-output/pdf-operators';
export class UnicodeTrueTypeFont {
// Fields
private readonly nameString : string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
* Name of the font subset.
*/
private subsetName : string;
/**
* `Size` of the true type font.
* @private
*/
private fontSize : number;
/**
* `Base64 string` of the true type font.
* @private
*/
private fontString : string;
/**
* `font data` of the true type font.
* @private
*/
private fontData : Uint8Array;
/**
* `true type font` reader object.
* @private
*/
public ttfReader : TtfReader;
/**
* metrics of true type font.
* @private
*/
public ttfMetrics : TtfMetrics;
/**
* Indicates whether the font is embedded or not.
* @private
*/
public isEmbed : boolean;
/**
* Pdf primitive describing the font.
*/
private fontDictionary : PdfDictionary;
/**
* Descendant font.
*/
private descendantFont : PdfDictionary;
/**
* font descripter.
*/
private fontDescriptor : PdfDictionary;
/**
* Font program.
*/
private fontProgram : PdfStream;
/**
* Cmap stream.
*/
private cmap : PdfStream;
/**
* C i d stream.
*/
private cidStream : PdfStream;
/**
* Font metrics.
*/
public metrics : PdfFontMetrics;
/**
* Specifies the Internal variable to store fields of `PdfDictionaryProperties`.
* @private
*/
private dictionaryProperties : DictionaryProperties = new DictionaryProperties();
/**
* Array of used chars.
* @private
*/
private usedChars : Dictionary<string, string>;
/**
* Indicates whether the font program is compressed or not.
* @private
*/
private isCompress : boolean = false;
/**
* Indicates whether the font is embedded or not.
*/
private isEmbedFont : boolean = false;
/**
* Cmap table's start prefix.
*/
/* tslint:disable */
private readonly cmapPrefix : string = '/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap' + Operators.newLine + '/CIDSystemInfo << /Registry (Adobe)/Ordering (UCS)/Supplement 0>> def\n/CMapName ' + '/Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange' + Operators.newLine;
/* tslint:enable */
/**
* Cmap table's start suffix.
*/
private readonly cmapEndCodespaceRange : string = 'endcodespacerange' + Operators.newLine;
/**
* Cmap's begin range marker.
*/
private readonly cmapBeginRange : string = 'beginbfrange' + Operators.newLine;
/**
* Cmap's end range marker.
*/
private readonly cmapEndRange : string = 'endbfrange' + Operators.newLine;
/**
* Cmap table's end
*/
/* tslint:disable */
private readonly cmapSuffix : string = 'endbfrange\nendcmap\nCMapName currentdict ' + '/CMap defineresource pop\nend end' + Operators.newLine;
/* tslint:enable */
//Constructors
/**
* Initializes a new instance of the `PdfTrueTypeFont` class.
* @private
*/
public constructor(base64String : string, size : number) {
if (base64String === null || base64String === undefined) {
throw new Error('ArgumentNullException:base64String');
}
this.fontSize = size;
this.fontString = base64String;
this.Initialize();
}
//Implementation
/**
* Returns width of the char symbol.
*/
public getCharWidth(charCode : string) : number {
let codeWidth : number = this.ttfReader.getCharWidth(charCode);
return codeWidth;
}
/**
* Returns width of the text line.
*/
public getLineWidth( line : string) : number {
// if (line == null) {
// throw new Error('ArgumentNullException : line');
// }
let width : number = 0;
for (let i : number = 0, len : number = line.length; i < len; i++) {
let ch : string = line[i];
let charWidth : number = this.getCharWidth(ch);
width += charWidth;
}
return width;
}
/**
* Initializes a new instance of the `PdfTrueTypeFont` class.
* @private
*/
private Initialize() : void {
let byteArray : ByteArray = new ByteArray(this.fontString.length);
byteArray.writeFromBase64String(this.fontString);
this.fontData = byteArray.internalBuffer;
this.ttfReader = new TtfReader(this.fontData);
this.ttfMetrics = this.ttfReader.metrics;
}
public createInternals() : void {
this.fontDictionary = new PdfDictionary();
this.fontProgram = new PdfStream();
this.cmap = new PdfStream();
this.descendantFont = new PdfDictionary();
this.metrics = new PdfFontMetrics();
this.ttfReader.createInternals();
this.ttfMetrics = this.ttfReader.metrics;
this.initializeMetrics();
// Create all the dictionaries of the font.
this.subsetName = this.getFontName();
this.createDescendantFont();
this.createCmap();
this.createFontDictionary();
this.createFontProgram();
}
public getInternals() : IPdfPrimitive {
return this.fontDictionary;
}
/**
* Initializes metrics.
*/
private initializeMetrics() : void {
let ttfMetrics : TtfMetrics = this.ttfReader.metrics;
this.metrics.ascent = ttfMetrics.macAscent;
this.metrics.descent = ttfMetrics.macDescent;
this.metrics.height = ttfMetrics.macAscent - ttfMetrics.macDescent + ttfMetrics.lineGap;
this.metrics.name = ttfMetrics.fontFamily;
this.metrics.postScriptName = ttfMetrics.postScriptName;
this.metrics.size = this.fontSize;
this.metrics.widthTable = new StandardWidthTable(ttfMetrics.widthTable);
this.metrics.lineGap = ttfMetrics.lineGap;
this.metrics.subScriptSizeFactor = ttfMetrics.subScriptSizeFactor;
this.metrics.superscriptSizeFactor = ttfMetrics.superscriptSizeFactor;
this.metrics.isBold = ttfMetrics.isBold;
}
/**
* Gets random string.
*/
private getFontName() : string {
let builder : string = '';
let name : string;
// if (this.isEmbed === false) {
for (let i : number = 0; i < 6; i++) {
let index : number = Math.floor(Math.random() * (25 - 0 + 1)) + 0;
builder += this.nameString[index];
}
builder += '+';
// }
builder += this.ttfReader.metrics.postScriptName;
name = builder.toString();
// if (name === '') {
// name = this.ttfReader.metrics.fontFamily;
// }
name = this.formatName(name);
return name;
}
/**
* Generates name of the font.
*/
private formatName(fontName : string) : string {
// if (fontName === null) {
// throw new Error('ArgumentNullException : fontName');
// }
// if (fontName === '') {
// throw new Error('ArgumentOutOfRangeException : fontName, Parameter can not be empty');
// }
let ret : string = fontName.replace('(', '#28');
ret = ret.replace(')', '#29');
ret = ret.replace('[', '#5B');
ret = ret.replace(']', '#5D');
ret = ret.replace('<', '#3C');
ret = ret.replace('>', '#3E');
ret = ret.replace('{', '#7B');
ret = ret.replace('}', '#7D');
ret = ret.replace('/', '#2F');
ret = ret.replace('%', '#25');
return ret.replace(' ', '#20');
}
/**
* Creates descendant font.
*/
private createDescendantFont() : void {
// Set property used to clone Font every time
this.descendantFont.isFont = true;
this.descendantFont.descendantFontBeginSave = new SaveDescendantFontEventHandler(this);
this.descendantFont.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.font));
this.descendantFont.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.cIDFontType2));
this.descendantFont.items.setValue(this.dictionaryProperties.baseFont, new PdfName(this.subsetName));
this.descendantFont.items.setValue(this.dictionaryProperties.cIDToGIDMap, new PdfName(this.dictionaryProperties.identity));
this.descendantFont.items.setValue(this.dictionaryProperties.dw, new PdfNumber(1000));
this.fontDescriptor = this.createFontDescriptor();
this.descendantFont.items.setValue(this.dictionaryProperties.fontDescriptor, new PdfReferenceHolder(this.fontDescriptor));
let systemInfo : IPdfPrimitive = this.createSystemInfo();
this.descendantFont.items.setValue(this.dictionaryProperties.cIDSystemInfo, systemInfo);
}
/**
* Creates font descriptor.
*/
private createFontDescriptor() : PdfDictionary {
let descriptor : PdfDictionary = new PdfDictionary();
let metrics : TtfMetrics = this.ttfReader.metrics;
// Set property used to clone Font every time
descriptor.isFont = true;
descriptor.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.fontDescriptor));
descriptor.items.setValue(this.dictionaryProperties.fontName, new PdfName(this.subsetName));
descriptor.items.setValue(this.dictionaryProperties.flags, new PdfNumber(this.getDescriptorFlags()));
descriptor.items.setValue(this.dictionaryProperties.fontBBox, PdfArray.fromRectangle(this.getBoundBox()));
descriptor.items.setValue(this.dictionaryProperties.missingWidth, new PdfNumber(metrics.widthTable[32]));
descriptor.items.setValue(this.dictionaryProperties.stemV, new PdfNumber(metrics.stemV));
descriptor.items.setValue(this.dictionaryProperties.italicAngle, new PdfNumber(metrics.italicAngle));
descriptor.items.setValue(this.dictionaryProperties.capHeight, new PdfNumber(metrics.capHeight));
descriptor.items.setValue(this.dictionaryProperties.ascent, new PdfNumber(metrics.winAscent));
descriptor.items.setValue(this.dictionaryProperties.descent, new PdfNumber(metrics.winDescent));
descriptor.items.setValue(this.dictionaryProperties.leading, new PdfNumber(metrics.leading));
descriptor.items.setValue(this.dictionaryProperties.avgWidth, new PdfNumber(metrics.widthTable[32]));
descriptor.items.setValue(this.dictionaryProperties.fontFile2, new PdfReferenceHolder(this.fontProgram));
descriptor.items.setValue(this.dictionaryProperties.maxWidth, new PdfNumber(metrics.widthTable[32]));
descriptor.items.setValue(this.dictionaryProperties.xHeight, new PdfNumber(0));
descriptor.items.setValue(this.dictionaryProperties.stemH, new PdfNumber(0));
return descriptor;
}
/**
* Generates cmap.
* @private
*/
private createCmap() : void {
this.cmap.cmapBeginSave = new SaveCmapEventHandler(this);
}
/**
* Generates font dictionary.
*/
private createFontDictionary() : void {
// Set property used to clone Font every time
this.fontDictionary.isFont = true;
this.fontDictionary.fontDictionaryBeginSave = new SaveFontDictionaryEventHandler(this);
this.fontDictionary.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.font));
this.fontDictionary.items.setValue(this.dictionaryProperties.baseFont, new PdfName(this.subsetName));
this.fontDictionary.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.type0));
this.fontDictionary.items.setValue(this.dictionaryProperties.encoding, new PdfName(this.dictionaryProperties.identityH));
let descFonts : PdfArray = new PdfArray();
let reference : PdfReferenceHolder = new PdfReferenceHolder(this.descendantFont);
// Set property used to clone Font every time
descFonts.isFont = true;
descFonts.add(reference);
this.fontDictionary.items.setValue(this.dictionaryProperties.descendantFonts, descFonts);
}
/**
* Creates font program.
*/
private createFontProgram() : void {
this.fontProgram.fontProgramBeginSave = new SaveFontProgramEventHandler(this);
}
/**
* Creates system info dictionary for CID font.
* @private
*/
private createSystemInfo() : IPdfPrimitive {
let systemInfo : PdfDictionary = new PdfDictionary();
systemInfo.items.setValue(this.dictionaryProperties.registry, new PdfString('Adobe'));
systemInfo.items.setValue(this.dictionaryProperties.ordering, new PdfString(this.dictionaryProperties.identity));
systemInfo.items.setValue(this.dictionaryProperties.supplement, new PdfNumber(0));
return systemInfo;
}
/**
* Runs before font Dictionary will be saved.
*/
public descendantFontBeginSave() : void {
if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0) {
let width : PdfArray = this.getDescendantWidth();
if (width !== null) {
this.descendantFont.items.setValue(this.dictionaryProperties.w, width);
}
}
}
/**
* Runs before font Dictionary will be saved.
*/
public cmapBeginSave() : void {
this.generateCmap();
}
/**
* Runs before font Dictionary will be saved.
*/
/* tslint:disable */
public fontDictionaryBeginSave() : void {
if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0 && !this.fontDictionary.containsKey(this.dictionaryProperties.toUnicode)) {
this.fontDictionary.items.setValue(this.dictionaryProperties.toUnicode, new PdfReferenceHolder(this.cmap));
}
}
/* tslint:enable */
/**
* Runs before font program stream save.
*/
public fontProgramBeginSave() : void {
this.isCompress = true;
this.generateFontProgram();
}
/**
* Gets width description pad array for c i d font.
*/
public getDescendantWidth() : PdfArray {
let array : PdfArray = new PdfArray();
if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0) {
let glyphInfo : TtfGlyphInfo[] = [];
// if (!this.isEmbedFont) {
let keys : string[] = this.usedChars.keys();
for (let i : number = 0; i < keys.length; i++) {
let chLen : string = keys[i];
let glyph : TtfGlyphInfo = this.ttfReader.getGlyph(chLen);
if (glyph.empty) {
continue;
}
glyphInfo.push(glyph);
}
// } else {
// glyphInfo = this.ttfReader.getAllGlyphs();
// }
glyphInfo.sort((a : TtfGlyphInfo, b : TtfGlyphInfo) => a.index - b.index);
let firstGlyphIndex : number = 0;
let lastGlyphIndex : number = 0;
let firstGlyphIndexWasSet : boolean = false;
let widthDetails : PdfArray = new PdfArray();
// if (!this.isEmbedFont) {
for (let i : number = 0; i < glyphInfo.length; i++) {
let glyph : TtfGlyphInfo = glyphInfo[i];
if (!firstGlyphIndexWasSet) {
firstGlyphIndexWasSet = true;
firstGlyphIndex = glyph.index;
lastGlyphIndex = glyph.index - 1;
}
if ((lastGlyphIndex + 1 !== glyph.index || (i + 1 === glyphInfo.length)) && glyphInfo.length > 1) {
// Add glyph index / width.
array.add(new PdfNumber(firstGlyphIndex));
if (i !== 0) {
array.add(widthDetails);
}
firstGlyphIndex = glyph.index;
widthDetails = new PdfArray();
}
widthDetails.add(new PdfNumber(glyph.width));
if (i + 1 === glyphInfo.length) {
array.add(new PdfNumber(firstGlyphIndex));
array.add(widthDetails);
}
lastGlyphIndex = glyph.index;
}
// } else {
// for (let i : number = 0; i < glyphInfo.length; i++) {
// let glyph : TtfGlyphInfo = glyphInfo[i];
// if (!firstGlyphIndexWasSet) {
// firstGlyphIndexWasSet = true;
// lastGlyphIndex = glyph.index - 1;
// }
// firstGlyphIndex = glyph.index;
// if ((lastGlyphIndex + 1 === glyph.index || (i + 1 === glyphInfo.length)) && glyphInfo.length > 1) {
// // Add glyph index / width.
// widthDetails.add(new PdfNumber(glyph.width));
// array.add(new PdfNumber(firstGlyphIndex));
// array.add(widthDetails);
// widthDetails = new PdfArray();
// }
// lastGlyphIndex = glyph.index;
// }
// }
}
return array;
}
/**
* Creates cmap.
*/
private generateCmap() : void {
if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0) {
let glyphChars : Dictionary<number, number> = this.ttfReader.getGlyphChars(this.usedChars);
if (glyphChars.size() > 0) {
let keys : number[] = glyphChars.keys().sort();
// add first and last glyph indexes
let first : number = keys[0];
let last : number = keys[keys.length - 1];
let middlePart : string = this.toHexString(first, false) + this.toHexString(last, false) + Operators.newLine;
let builder : string = '';
builder += this.cmapPrefix;
builder += middlePart;
builder += this.cmapEndCodespaceRange;
let nextRange : number = 0;
for (let i : number = 0; i < keys.length; i++) {
if (nextRange === 0) {
if (i !== 0) {
builder += this.cmapEndRange;
}
nextRange = Math.min(100, keys.length - i);
builder += nextRange;
builder += Operators.whiteSpace;
builder += this.cmapBeginRange;
}
nextRange -= 1;
let key : number = keys[i];
/* tslint:disable */
builder += this.toHexString(key, true) + this.toHexString(key, true) + this.toHexString(glyphChars.getValue(key), true) + '\n';
/* tslint:enable */
}
builder += this.cmapSuffix;
this.cmap.clearStream();
this.cmap.isFont = true;
this.cmap.write(builder);
}
}
}
/**
* Generates font program.
*/
private generateFontProgram() : void {
let fontProgram : number[] = null;
this.usedChars = (this.usedChars === null || this.usedChars === undefined) ? new Dictionary<string, string>() : this.usedChars;
this.ttfReader.setOffset(0);
fontProgram = this.ttfReader.readFontProgram(this.usedChars);
this.fontProgram.clearStream();
this.fontProgram.isFont = true;
this.fontProgram.writeBytes(fontProgram);
}
/**
* Calculates flags for the font descriptor.
* @private
*/
public getDescriptorFlags() : number {
let flags : number = 0;
let metrics : TtfMetrics = this.ttfReader.metrics;
if (metrics.isFixedPitch) {
flags |= FontDescriptorFlags.FixedPitch;
}
if (metrics.isSymbol) {
flags |= FontDescriptorFlags.Symbolic;
} else {
flags |= FontDescriptorFlags.Nonsymbolic;
}
if (metrics.isItalic) {
flags |= FontDescriptorFlags.Italic;
}
if (metrics.isBold) {
flags |= FontDescriptorFlags.ForceBold;
}
return flags;
}
/**
* Calculates BoundBox of the descriptor.
* @private
*/
private getBoundBox() : RectangleF {
let rect : Rectangle = this.ttfReader.metrics.fontBox;
let width : number = Math.abs(rect.right - rect.left);
let height : number = Math.abs(rect.top - rect.bottom);
let rectangle : RectangleF = new RectangleF(rect.left, rect.bottom, width, height);
return rectangle;
}
/**
* Converts integer of decimal system to hex integer.
*/
private toHexString(n : number, isCaseChange : boolean) : string {
let s : string = n.toString(16);
if (isCaseChange) {
s = s.toUpperCase();
}
return '<0000'.substring(0, 5 - s.length) + s + '>';
}
/**
* Stores used symbols.
*/
public setSymbols(text : string) : void {
if (text === null) {
throw new Error('Argument Null Exception : text');
}
if (this.usedChars === null || this.usedChars === undefined) {
this.usedChars = new Dictionary<string, string>();
}
for (let i : number = 0; i < text.length; i++) {
let ch : string = text[i];
this.usedChars.setValue(ch, String.fromCharCode(0));
}
// else {
// if (text === null) {
// throw new Error('Argument Null Exception : glyphs');
// }
// if (this.usedChars === null || this.usedChars === undefined) {
// this.usedChars = new Dictionary<string, string>();
// }
// for (let i : number = 0; i < text.length; i++) {
// let glyphIndex : number = text[i];
// let glyph : TtfGlyphInfo = this.ttfReader.getGlyph(glyphIndex);
// if (!glyph == null) {
// let c : string = glyph.charCode.toLocaleString();
// this.usedChars.setValue(c, String.fromCharCode(0));
// }
// }
// }
if (this.isEmbedFont === false) {
this.getDescendantWidth();
}
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/policy/cr_policy_pref_indicator.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js';
import '../settings_shared_css.js';
import './add_site_dialog.js';
import './edit_exception_dialog.js';
import './site_list_entry.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {ListPropertyUpdateMixin} from 'chrome://resources/js/list_property_update_mixin.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {PaperTooltipElement} from 'chrome://resources/polymer/v3_0/paper-tooltip/paper-tooltip.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
// <if expr="chromeos">
import {loadTimeData} from '../i18n_setup.js';
import {AndroidInfoBrowserProxyImpl, AndroidSmsInfo} from './android_info_browser_proxy.js';
// </if>
import {ContentSetting, ContentSettingsTypes, INVALID_CATEGORY_SUBTYPE} from './constants.js';
import {SiteSettingsMixin} from './site_settings_mixin.js';
import {RawSiteException, SiteException, SiteSettingsPrefsBrowserProxy, SiteSettingsPrefsBrowserProxyImpl} from './site_settings_prefs_browser_proxy.js';
export interface SiteListElement {
$: {
addSite: HTMLElement,
category: HTMLElement,
listContainer: HTMLElement,
tooltip: PaperTooltipElement,
};
}
const SiteListElementBase = ListPropertyUpdateMixin(
SiteSettingsMixin(WebUIListenerMixin(PolymerElement)));
export class SiteListElement extends SiteListElementBase {
static get is() {
return 'site-list';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Some content types (like Location) do not allow the user to manually
* edit the exception list from within Settings.
*/
readOnlyList: {
type: Boolean,
value: false,
},
categoryHeader: String,
/**
* The site serving as the model for the currently open action menu.
*/
actionMenuSite_: Object,
/**
* Whether the "edit exception" dialog should be shown.
*/
showEditExceptionDialog_: Boolean,
/**
* Array of sites to display in the widget.
*/
sites: {
type: Array,
value() {
return [];
},
},
/**
* The type of category this widget is displaying data for. Normally
* either 'allow' or 'block', representing which sites are allowed or
* blocked respectively.
*/
categorySubtype: {
type: String,
value: INVALID_CATEGORY_SUBTYPE,
},
hasIncognito_: Boolean,
/**
* Whether to show the Add button next to the header.
*/
showAddSiteButton_: {
type: Boolean,
computed: 'computeShowAddSiteButton_(readOnlyList, category, ' +
'categorySubtype)',
},
showAddSiteDialog_: Boolean,
/**
* Whether to show the Allow action in the action menu.
*/
showAllowAction_: Boolean,
/**
* Whether to show the Block action in the action menu.
*/
showBlockAction_: Boolean,
/**
* Whether to show the 'Clear on exit' action in the action
* menu.
*/
showSessionOnlyAction_: Boolean,
/**
* All possible actions in the action menu.
*/
actions_: {
readOnly: true,
type: Object,
values: {
ALLOW: 'Allow',
BLOCK: 'Block',
RESET: 'Reset',
SESSION_ONLY: 'SessionOnly',
}
},
lastFocused_: Object,
listBlurred_: Boolean,
tooltipText_: String,
searchFilter: String,
};
}
static get observers() {
return ['configureWidget_(category, categorySubtype)'];
}
readOnlyList: boolean;
categoryHeader: string;
private actionMenuSite_: SiteException|null;
private showEditExceptionDialog_: boolean;
sites: Array<SiteException>;
categorySubtype: ContentSetting;
private hasIncognito_: boolean;
private showAddSiteButton_: boolean;
private showAddSiteDialog_: boolean;
private showAllowAction_: boolean;
private showBlockAction_: boolean;
private showSessionOnlyAction_: boolean;
private lastFocused_: HTMLElement;
private listBlurred_: boolean;
private tooltipText_: string;
searchFilter: string;
private activeDialogAnchor_: HTMLElement|null;
private browserProxy_: SiteSettingsPrefsBrowserProxy =
SiteSettingsPrefsBrowserProxyImpl.getInstance();
// <if expr="chromeos">
private androidSmsInfo_: AndroidSmsInfo|null;
// </if>
constructor() {
super();
// <if expr="chromeos">
/**
* Android messages info object containing messages feature state and
* exception origin.
*/
this.androidSmsInfo_ = null;
// </if>
/**
* The element to return focus to, when the currently active dialog is
* closed.
*/
this.activeDialogAnchor_ = null;
}
ready() {
super.ready();
this.addWebUIListener(
'contentSettingSitePermissionChanged',
(category: ContentSettingsTypes) =>
this.siteWithinCategoryChanged_(category));
this.addWebUIListener(
'onIncognitoStatusChanged',
(hasIncognito: boolean) =>
this.onIncognitoStatusChanged_(hasIncognito));
// <if expr="chromeos">
this.addWebUIListener(
'settings.onAndroidSmsInfoChange', (info: AndroidSmsInfo) => {
this.androidSmsInfo_ = info;
this.populateList_();
});
// </if>
this.browserProxy.updateIncognitoStatus();
}
/**
* Called when a site changes permission.
* @param category The category of the site that changed.
*/
private siteWithinCategoryChanged_(category: ContentSettingsTypes) {
if (category === this.category) {
this.configureWidget_();
}
}
/**
* Called for each site list when incognito is enabled or disabled. Only
* called on change (opening N incognito windows only fires one message).
* Another message is sent when the *last* incognito window closes.
*/
private onIncognitoStatusChanged_(hasIncognito: boolean) {
this.hasIncognito_ = hasIncognito;
// The SESSION_ONLY list won't have any incognito exceptions. (Minor
// optimization, not required).
if (this.categorySubtype === ContentSetting.SESSION_ONLY) {
return;
}
// A change notification is not sent for each site. So we repopulate the
// whole list when the incognito profile is created or destroyed.
this.populateList_();
}
/**
* Configures the action menu, visibility of the widget and shows the list.
*/
private configureWidget_() {
if (this.category === undefined) {
return;
}
this.setUpActionMenu_();
// <if expr="not chromeos">
this.populateList_();
// </if>
// <if expr="chromeos">
this.updateAndroidSmsInfo_().then(() => this.populateList_());
// </if>
// The Session permissions are only for cookies.
if (this.categorySubtype === ContentSetting.SESSION_ONLY) {
this.$.category.hidden = this.category !== ContentSettingsTypes.COOKIES;
}
}
/**
* Whether there are any site exceptions added for this content setting.
*/
private hasSites_(): boolean {
return this.sites.length > 0;
}
/**
* Whether the Add Site button is shown in the header for the current category
* and category subtype.
*/
private computeShowAddSiteButton_(): boolean {
return !(
this.readOnlyList ||
(this.category === ContentSettingsTypes.FILE_SYSTEM_WRITE &&
this.categorySubtype === ContentSetting.ALLOW));
}
private showNoSearchResults_(): boolean {
return this.sites.length > 0 && this.getFilteredSites_().length === 0;
}
/**
* A handler for the Add Site button.
*/
private onAddSiteTap_() {
assert(!this.readOnlyList);
this.showAddSiteDialog_ = true;
}
private onAddSiteDialogClosed_() {
this.showAddSiteDialog_ = false;
focusWithoutInk(assert(this.$.addSite));
}
/**
* Need to use common tooltip since the tooltip in the entry is cut off from
* the iron-list.
*/
private onShowTooltip_(e: CustomEvent<{target: HTMLElement, text: string}>) {
this.tooltipText_ = e.detail.text;
const target = e.detail.target;
// paper-tooltip normally determines the target from the |for| property,
// which is a selector. Here paper-tooltip is being reused by multiple
// potential targets.
const tooltip = this.$.tooltip;
tooltip.target = target;
tooltip.updatePosition();
const hide = () => {
this.$.tooltip.hide();
target.removeEventListener('mouseleave', hide);
target.removeEventListener('blur', hide);
target.removeEventListener('click', hide);
this.$.tooltip.removeEventListener('mouseenter', hide);
};
target.addEventListener('mouseleave', hide);
target.addEventListener('blur', hide);
target.addEventListener('click', hide);
this.$.tooltip.addEventListener('mouseenter', hide);
this.$.tooltip.show();
}
// <if expr="chromeos">
/**
* Load android sms info if required and sets it to the |androidSmsInfo_|
* property. Returns a promise that resolves when load is complete.
*/
private updateAndroidSmsInfo_() {
// |androidSmsInfo_| is only relevant for NOTIFICATIONS category. Don't
// bother fetching it for other categories.
if (this.category === ContentSettingsTypes.NOTIFICATIONS &&
loadTimeData.valueExists('multideviceAllowedByPolicy') &&
loadTimeData.getBoolean('multideviceAllowedByPolicy') &&
!this.androidSmsInfo_) {
const androidInfoBrowserProxy = AndroidInfoBrowserProxyImpl.getInstance();
return androidInfoBrowserProxy.getAndroidSmsInfo().then(
(info: AndroidSmsInfo) => {
this.androidSmsInfo_ = info;
});
}
return Promise.resolve();
}
/**
* Processes exceptions and adds showAndroidSmsNote field to
* the required exception item.
*/
private processExceptionsForAndroidSmsInfo_(sites: Array<SiteException>):
Array<SiteException> {
if (!this.androidSmsInfo_ || !this.androidSmsInfo_.enabled) {
return sites;
}
return sites.map((site) => {
if (site.origin === this.androidSmsInfo_!.origin) {
return Object.assign({showAndroidSmsNote: true}, site);
} else {
return site;
}
});
}
// </if>
/**
* Populate the sites list for display.
*/
private populateList_() {
this.browserProxy_.getExceptionList(this.category).then(exceptionList => {
this.processExceptions_(exceptionList);
this.closeActionMenu_();
});
}
/**
* Process the exception list returned from the native layer.
*/
private processExceptions_(exceptionList: Array<RawSiteException>) {
let sites = exceptionList
.filter(
site => site.setting !== ContentSetting.DEFAULT &&
site.setting === this.categorySubtype)
.map(site => this.expandSiteException(site));
// <if expr="chromeos">
sites = this.processExceptionsForAndroidSmsInfo_(sites);
// </if>
this.updateList('sites', x => x.origin, sites);
}
/**
* Set up the values to use for the action menu.
*/
private setUpActionMenu_() {
this.showAllowAction_ = this.categorySubtype !== ContentSetting.ALLOW;
this.showBlockAction_ = this.categorySubtype !== ContentSetting.BLOCK;
this.showSessionOnlyAction_ =
this.categorySubtype !== ContentSetting.SESSION_ONLY &&
this.category === ContentSettingsTypes.COOKIES;
}
/**
* @return Whether to show the "Session Only" menu item for the currently
* active site.
*/
private showSessionOnlyActionForSite_(): boolean {
// It makes no sense to show "clear on exit" for exceptions that only apply
// to incognito. It gives the impression that they might under some
// circumstances not be cleared on exit, which isn't true.
if (!this.actionMenuSite_ || this.actionMenuSite_.incognito) {
return false;
}
return this.showSessionOnlyAction_;
}
private setContentSettingForActionMenuSite_(contentSetting: ContentSetting) {
assert(this.actionMenuSite_);
this.browserProxy.setCategoryPermissionForPattern(
this.actionMenuSite_!.origin, this.actionMenuSite_!.embeddingOrigin,
this.category, contentSetting, this.actionMenuSite_!.incognito);
}
private onAllowTap_() {
this.setContentSettingForActionMenuSite_(ContentSetting.ALLOW);
this.closeActionMenu_();
}
private onBlockTap_() {
this.setContentSettingForActionMenuSite_(ContentSetting.BLOCK);
this.closeActionMenu_();
}
private onSessionOnlyTap_() {
this.setContentSettingForActionMenuSite_(ContentSetting.SESSION_ONLY);
this.closeActionMenu_();
}
private onEditTap_() {
// Close action menu without resetting |this.actionMenuSite_| since it is
// bound to the dialog.
this.shadowRoot!.querySelector('cr-action-menu')!.close();
this.showEditExceptionDialog_ = true;
}
private onEditExceptionDialogClosed_() {
this.showEditExceptionDialog_ = false;
this.actionMenuSite_ = null;
if (this.activeDialogAnchor_) {
this.activeDialogAnchor_.focus();
this.activeDialogAnchor_ = null;
}
}
private onResetTap_() {
const site = assert(this.actionMenuSite_!);
this.browserProxy.resetCategoryPermissionForPattern(
site!.origin, site!.embeddingOrigin, this.category, site!.incognito);
this.closeActionMenu_();
}
private onShowActionMenu_(
e: CustomEvent<{anchor: HTMLElement, model: SiteException}>) {
this.activeDialogAnchor_ = e.detail.anchor;
this.actionMenuSite_ = e.detail.model;
this.shadowRoot!.querySelector('cr-action-menu')!.showAt(
this.activeDialogAnchor_);
}
private closeActionMenu_() {
this.actionMenuSite_ = null;
this.activeDialogAnchor_ = null;
const actionMenu = this.shadowRoot!.querySelector('cr-action-menu')!;
if (actionMenu.open) {
actionMenu.close();
}
}
private getFilteredSites_(): Array<SiteException> {
if (!this.searchFilter) {
return this.sites.slice();
}
type SearchableProperty = 'displayName'|'origin';
const propNames: Array<SearchableProperty> = ['displayName', 'origin'];
const searchFilter = this.searchFilter.toLowerCase();
return this.sites.filter(
site => propNames.some(
propName => site[propName].toLowerCase().includes(searchFilter)));
}
}
declare global {
interface HTMLElementTagNameMap {
'site-list': SiteListElement;
}
}
customElements.define(SiteListElement.is, SiteListElement); | the_stack |
import React, { useContext, useState } from 'react';
import {
CODE_TYPE,
DATA_SOURCE_ENUM,
DATA_SOURCE_TEXT,
DATA_SOURCE_VERSION,
FLINK_VERSIONS,
formItemLayout,
KAFKA_DATA_LIST,
KAFKA_DATA_TYPE,
SOURCE_TIME_TYPE,
} from '@/constant';
import { isAvro, isKafka, isShowTimeForOffsetReset } from '@/utils/is';
import {
Button,
Cascader,
Checkbox,
Col,
DatePicker,
Form,
Input,
InputNumber,
message,
Radio,
Row,
Select,
} from 'antd';
import { UpOutlined, DownOutlined } from '@ant-design/icons';
import { getColumnsByColumnsText } from '@/utils';
import Editor from '@/components/editor';
import type { IDataSourceUsedInSyncProps } from '@/interface';
import { NAME_FIELD } from '.';
import type { DefaultOptionType } from 'antd/lib/cascader';
import { FormContext } from '@/services/rightBarService';
import { generateValidDesSource } from '@/utils/saveTask';
import { CustomParams } from '../customParams';
import DataPreviewModal from '../../../components/streamCollection/source/dataPreviewModal';
const FormItem = Form.Item;
const { Option } = Select;
/**
* 源表类型下拉菜单
*/
const DATASOURCE_OPTIONS_TYPE = [
DATA_SOURCE_ENUM.KAFKA_2X,
DATA_SOURCE_ENUM.KAFKA,
DATA_SOURCE_ENUM.KAFKA_11,
DATA_SOURCE_ENUM.KAFKA_10,
];
interface ISourceFormProps {
/**
* 用于 form 的 name 前缀
*/
index: number;
componentVersion?: Valueof<typeof FLINK_VERSIONS>;
topicOptionType: string[];
originOptionType: IDataSourceUsedInSyncProps[];
timeZoneData: DefaultOptionType[];
}
export default function SourceForm({
index,
componentVersion,
originOptionType,
topicOptionType,
timeZoneData,
}: ISourceFormProps) {
const { form } = useContext(FormContext);
const [visible, setVisible] = useState(false);
const [params, setParams] = useState({});
const [showAdvancedParams, setShowAdvancedParams] = useState(false);
const showPreviewModal = () => {
const { sourceId, topic } = form?.getFieldValue(NAME_FIELD)?.[index] || {};
let nextParam = {};
if (!sourceId || !topic) {
message.error('数据预览需要选择数据源和Topic!');
return;
}
nextParam = { sourceId, topic };
setVisible(true);
setParams(nextParam);
};
const validDes = generateValidDesSource(
form?.getFieldValue(NAME_FIELD)?.[index],
componentVersion,
);
return (
<>
<FormItem label="类型" name={[index, 'type']} rules={validDes.type}>
<Select<DATA_SOURCE_ENUM>
placeholder="请选择类型"
className="right-select"
showSearch
filterOption={(input, option) =>
!!option?.value?.toString().toUpperCase().includes(input.toUpperCase())
}
options={DATASOURCE_OPTIONS_TYPE.map((t) => ({
label: DATA_SOURCE_TEXT[t],
value: t,
}))}
/>
</FormItem>
<FormItem label="数据源" name={[index, 'sourceId']} rules={validDes.sourceId}>
<Select
showSearch
placeholder="请选择数据源"
className="right-select"
filterOption={(input, option) =>
!!option?.value?.toString().toUpperCase().includes(input.toUpperCase())
}
>
{originOptionType.map((v) => (
<Option key={v.dataInfoId} value={`${v.dataInfoId}`}>
{v.dataName}
{DATA_SOURCE_VERSION[v.dataTypeCode] &&
` (${DATA_SOURCE_VERSION[v.dataTypeCode]})`}
</Option>
))}
</Select>
</FormItem>
<FormItem label="Topic" name={[index, 'topic']} rules={validDes.topic}>
<Select<string>
placeholder="请选择Topic"
className="right-select"
showSearch
filterOption={(input, option) =>
!!option?.value?.toString().toUpperCase().includes(input.toUpperCase())
}
>
{topicOptionType.map((v) => (
<Option key={v} value={`${v}`}>
{v}
</Option>
))}
</Select>
</FormItem>
<FormItem
label="编码类型"
style={{ marginBottom: '10px' }}
name={[index, 'charset']}
tooltip="编码类型:指Kafka数据的编码类型"
>
<Select placeholder="请选择编码类型" className="right-select" showSearch>
<Option value={CODE_TYPE.UTF_8}>{CODE_TYPE.UTF_8}</Option>
<Option value={CODE_TYPE.GBK_2312}>{CODE_TYPE.GBK_2312}</Option>
</Select>
</FormItem>
<FormItem noStyle dependencies={[[index, 'type']]}>
{({ getFieldValue }) =>
isKafka(getFieldValue(NAME_FIELD)?.[index].type) && (
<FormItem
{...formItemLayout}
label="读取类型"
className="right-select"
name={[index, 'sourceDataType']}
rules={validDes.sourceDataType}
>
<Select>
{getFieldValue(NAME_FIELD)?.[index].type ===
DATA_SOURCE_ENUM.KAFKA_CONFLUENT ? (
<Option
value={KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT}
key={KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT}
>
{KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT}
</Option>
) : (
KAFKA_DATA_LIST.map(({ text, value }) => (
<Option value={value} key={text + value}>
{text}
</Option>
))
)}
</Select>
</FormItem>
)
}
</FormItem>
<FormItem noStyle dependencies={[[index, 'sourceDataType']]}>
{({ getFieldValue }) =>
isAvro(getFieldValue(NAME_FIELD)?.[index].sourceDataType) && (
<FormItem
{...formItemLayout}
label="Schema"
name={[index, 'schemaInfo']}
rules={validDes.schemaInfo}
>
<Input.TextArea
rows={9}
placeholder={`填写Avro Schema信息,示例如下:\n{\n\t"name": "testAvro",\n\t"type": "record",\n\t"fields": [{\n\t\t"name": "id",\n\t\t"type": "string"\n\t}]\n}`}
/>
</FormItem>
)
}
</FormItem>
<FormItem
wrapperCol={{
sm: {
offset: formItemLayout.labelCol.sm.span,
span: formItemLayout.wrapperCol.sm.span,
},
}}
>
<Button block type="link" onClick={showPreviewModal}>
数据预览
</Button>
</FormItem>
<FormItem
label="映射表"
name={[index, 'table']}
rules={validDes.table}
tooltip="该表是kafka中的topic映射而成,可以以SQL的方式使用它。"
>
<Input placeholder="请输入映射表名" className="right-input" />
</FormItem>
<FormItem noStyle dependencies={[[index, 'type']]}>
{({ getFieldValue }) => (
<FormItem label="字段" required name={[index, 'columnsText']}>
<Editor
style={{ minHeight: 202 }}
className="bd"
sync
options={{
fontSize: 12,
minimap: {
enabled: false,
},
}}
placeholder={`字段 类型, 比如 id int 一行一个字段${getFieldValue(NAME_FIELD)?.[index].type !==
DATA_SOURCE_ENUM.KAFKA_CONFLUENT
? '\n\n仅支持JSON格式数据源,若为嵌套格式,\n字段名称由JSON的各层级key组合隔,例如:\n\nkey1.keya INT AS columnName \nkey1.keyb VARCHAR AS columnName'
: ''
}`}
/>
</FormItem>
)}
</FormItem>
<FormItem noStyle dependencies={[[index, 'type']]}>
{({ getFieldValue }) => (
<FormItem
label="Offset"
tooltip={
<div>
<p>latest:从Kafka Topic内最新的数据开始消费</p>
<p>earliest:从Kafka Topic内最老的数据开始消费</p>
</div>
}
name={[index, 'offsetReset']}
>
<Radio.Group className="right-select">
<Row>
<Col span={12}>
<Radio value="latest">latest</Radio>
</Col>
<Col span={12}>
<Radio value="earliest">earliest</Radio>
</Col>
{isShowTimeForOffsetReset(
getFieldValue(NAME_FIELD)?.[index]?.type,
) && (
<Col span={12}>
<Radio value="timestamp">time</Radio>
</Col>
)}
<Col span={12}>
<Radio value="custom">自定义参数</Radio>
</Col>
</Row>
</Radio.Group>
</FormItem>
)}
</FormItem>
<FormItem noStyle dependencies={[[index, 'offsetReset']]}>
{({ getFieldValue }) =>
getFieldValue(NAME_FIELD)?.[index].offsetReset === 'timestamp' && (
<FormItem
label="选择时间"
name={[index, 'timestampOffset']}
rules={[{ required: true, message: '请选择时间' }]}
>
<DatePicker
showTime
placeholder="请选择时间"
format={'YYYY-MM-DD HH:mm:ss'}
style={{ width: '100%' }}
/>
</FormItem>
)
}
</FormItem>
<FormItem noStyle shouldUpdate>
{({ getFieldValue }) =>
getFieldValue(NAME_FIELD)?.[index].offsetReset === 'custom' && (
<FormItem label="字段" required name={[index, "offsetValue"]}>
<Editor
style={{ minHeight: 202, height: '100%' }}
className="bd"
sync
placeholder="分区 偏移量,比如pt 2 一行一对值"
/>
</FormItem>
)
}
</FormItem>
<FormItem
label="时间特征"
tooltip={
<div>
<p>ProcTime:按照Flink的处理时间处理</p>
<p>EventTime:按照流式数据本身包含的业务时间戳处理</p>
<p>
Flink1.12后,基于事件时间的时态表 Join 开发需勾选ProcTime详情可参考
<a
href="https://ci.apache.org/projects/flink/flink-docs-release-1.12/zh/dev/table/streaming/joins.html"
target="_blank"
rel="noopener noreferrer"
>
帮助文档
</a>
</p>
</div>
}
name={[
index,
componentVersion !== FLINK_VERSIONS.FLINK_1_12 ? 'timeType' : 'timeTypeArr',
]}
>
{componentVersion !== FLINK_VERSIONS.FLINK_1_12 ? (
<Radio.Group className="right-select">
<Radio value={1}>ProcTime</Radio>
<Radio value={2}>EventTime</Radio>
</Radio.Group>
) : (
<Checkbox.Group
options={[
{ label: 'ProcTime', value: 1 },
{ label: 'EventTime', value: 2 },
]}
/>
)}
</FormItem>
<FormItem noStyle dependencies={[[index, 'timeTypeArr']]}>
{({ getFieldValue }) =>
componentVersion === FLINK_VERSIONS.FLINK_1_12 &&
getFieldValue(NAME_FIELD)?.[index].timeTypeArr?.includes?.(
SOURCE_TIME_TYPE.PROC_TIME,
) && (
<FormItem
label="ProcTime 名称"
name={[index, 'procTime']}
rules={[{ pattern: /^\w*$/, message: '仅支持输入英文、数字、下划线' }]}
>
<Input
className="right-input"
maxLength={64}
placeholder="自定义ProcTime名称,为空时默认为 proc_time"
/>
</FormItem>
)
}
</FormItem>
<FormItem
noStyle
dependencies={[
[index, 'timeType'],
[index, 'timeTypeArr'],
[index, 'columnsText'],
]}
>
{({ getFieldValue }) =>
((componentVersion !== FLINK_VERSIONS.FLINK_1_12 &&
getFieldValue(NAME_FIELD)?.[index].timeType ===
SOURCE_TIME_TYPE.EVENT_TIME) ||
(componentVersion === FLINK_VERSIONS.FLINK_1_12 &&
getFieldValue(NAME_FIELD)?.[index].timeTypeArr?.includes?.(
SOURCE_TIME_TYPE.EVENT_TIME,
))) && (
<React.Fragment>
<FormItem
label="时间列"
name={[index, 'timeColumn']}
rules={validDes.timeColumn}
>
<Select
placeholder="请选择"
className="right-select"
showSearch
filterOption={(input: any, option: any) =>
option.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{getColumnsByColumnsText(
getFieldValue(NAME_FIELD)?.[index].columnsText,
)?.map((v) => (
<Option key={v.field} value={v.field}>
{v.field}
</Option>
))}
</Select>
</FormItem>
<FormItem
label="最大延迟时间"
tooltip="当event time超过最大延迟时间时,系统自动丢弃此条数据"
name={[index, 'offset']}
rules={validDes.offset}
>
<InputNumber
min={0}
style={{
width: '100%',
height: '32px',
}}
addonAfter={
componentVersion === FLINK_VERSIONS.FLINK_1_12 ? (
<Form.Item
name={[index, 'offsetUnit']}
noStyle
initialValue="SECOND"
>
<Select
className="right-select"
>
<Option value="SECOND">sec</Option>
<Option value="MINUTE">min</Option>
<Option value="HOUR">hour</Option>
<Option value="DAY">day</Option>
<Option value="MONTH">mon</Option>
<Option value="YEAR">year</Option>
</Select>
</Form.Item>
) : (
'ms'
)
}
/>
</FormItem>
</React.Fragment>
)
}
</FormItem>
{/* 高级参数按钮 */}
<FormItem wrapperCol={{ span: 24 }}>
<Button
block
type="link"
onClick={() => setShowAdvancedParams(!showAdvancedParams)}
>
高级参数{showAdvancedParams ? <UpOutlined /> : <DownOutlined />}
</Button>
</FormItem>
{/* 高级参数抽屉 */}
<FormItem hidden={!showAdvancedParams} noStyle shouldUpdate>
{() => (
<>
<FormItem name={[index, 'parallelism']} label="并行度">
<InputNumber style={{ width: '100%' }} min={1} />
</FormItem>
<FormItem
label="时区"
tooltip="注意:时区设置功能目前只支持时间特征为EventTime的任务"
name={[index, 'timeZone']}
>
<Cascader
allowClear={false}
placeholder="请选择时区"
showSearch
options={timeZoneData}
/>
</FormItem>
<CustomParams index={index} />
</>
)}
</FormItem>
<FormItem noStyle shouldUpdate>
{({ getFieldValue }) => (
<DataPreviewModal
visible={visible}
type={getFieldValue(NAME_FIELD)?.[index]?.type}
onCancel={() => {
setVisible(false);
}}
params={params}
/>
)}
</FormItem>
</>
);
} | the_stack |
'use strict';
import * as http from 'http';
import { URL } from 'url';
import * as os from 'os';
import * as path from 'path';
import { Uri, window } from 'vscode';
import { planner, OutputAdaptor, utils } from 'pddl-workspace';
import { isHttp } from '../utils';
import { PlannerExecutable } from '../planning/PlannerExecutable';
import { AsyncServiceConfiguration, PlannerAsyncService, PlannerSyncService } from 'pddl-planning-service-client';
import { LongRunningPlannerProvider } from './plannerExecution';
export class CommandPlannerProvider implements planner.PlannerProvider {
get kind(): planner.PlannerKind {
return planner.WellKnownPlannerKind.COMMAND;
}
getNewPlannerLabel(): string {
return "$(terminal) Input a command...";
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration): Promise<planner.PlannerConfiguration | undefined> {
const existingValue = previousConfiguration?.path;
let newPlannerPath = await window.showInputBox({
prompt: "Enter PDDL planner path local command",
placeHolder: `planner.exe OR java -jar c:\\planner.jar`,
value: existingValue,
ignoreFocusOut: true
});
let syntax: string | undefined;
if (newPlannerPath) {
newPlannerPath = newPlannerPath.trim().replace(/\\/g, '/');
// todo: validate that this planner actually works by sending a dummy request to it
if (!isHttp(newPlannerPath)) {
syntax = await this.askPlannerSyntax(previousConfiguration);
if (syntax?.trim() === "") {
syntax = "$(planner) $(options) $(domain) $(problem)";
}
}
}
if (newPlannerPath && syntax) {
return this.createPlannerConfiguration(newPlannerPath, syntax);
} else {
return undefined;
}
}
createPlannerConfiguration(command: string, syntax: string | undefined): planner.PlannerConfiguration {
const title = isHttp(command)
? command
: path.basename(command);
return {
kind: this.kind.kind,
path: command,
syntax: syntax,
title: title,
canConfigure: true
};
}
async askPlannerSyntax(previousConfiguration?: planner.PlannerConfiguration): Promise<string | undefined> {
const existingValue = previousConfiguration?.syntax;
const newPlannerOptions = await window.showInputBox({
prompt: "In case you use command line switches and options, override the default syntax. For more info, see (the wiki)[https://github.com/jan-dolejsi/vscode-pddl/wiki/Configuring-the-PDDL-planner].",
placeHolder: `$(planner) $(options) $(domain) $(problem)`,
value: existingValue,
ignoreFocusOut: true
});
return newPlannerOptions;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
showHelp(_output: OutputAdaptor): void {
throw new Error("Method not implemented.");
}
}
export class SolveServicePlannerProvider extends LongRunningPlannerProvider {
get kind(): planner.PlannerKind {
return planner.WellKnownPlannerKind.SERVICE_SYNC;
}
getNewPlannerLabel(): string {
return "$(cloud-upload) Input a sync. service URL...";
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration): Promise<planner.PlannerConfiguration | undefined> {
const existingValue = previousConfiguration?.url ?? "http://solver.planning.domains/solve";
const existingUri = Uri.parse(existingValue);
const indexOf = existingValue.indexOf(existingUri.authority);
const existingHostAndPort: [number, number] | undefined
= indexOf > -1 ? [indexOf, indexOf + existingUri.authority.length] : undefined;
const newPlannerUrl = await window.showInputBox({
prompt: "Enter synchronous service URL",
placeHolder: `http://host:port/solve`,
valueSelection: existingHostAndPort,
value: existingValue,
ignoreFocusOut: true
});
if (!newPlannerUrl) { return undefined; }
return this.createPlannerConfiguration(newPlannerUrl, previousConfiguration);
}
createPlannerConfiguration(newPlannerUrl: string, previousConfiguration?: planner.PlannerConfiguration): planner.PlannerConfiguration {
return {
kind: this.kind.kind,
url: newPlannerUrl,
title: newPlannerUrl,
canConfigure: true,
path: previousConfiguration?.path
};
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
showHelp(_output: OutputAdaptor): void {
throw new Error("Method not implemented.");
}
/** Custom `Planner` implementation. */
createPlanner(configuration: planner.PlannerConfiguration, plannerInvocationOptions: planner.PlannerRunConfiguration): planner.Planner {
return SolveServicePlannerProvider.createDefaultPlanner(configuration, plannerInvocationOptions, this);
}
/** Default `Planner` implementation. */
static createDefaultPlanner(configuration: planner.PlannerConfiguration, plannerInvocationOptions: planner.PlannerRunConfiguration, plannerProvider?: planner.PlannerProvider): planner.Planner {
if (!configuration.url) {
throw new Error(`Planner ${configuration.title} does not specify 'url'.`);
}
const providerConfiguration: planner.ProviderConfiguration = {
configuration: configuration,
provider: plannerProvider
};
return new PlannerSyncService(configuration.url, plannerInvocationOptions, providerConfiguration);
}
/**
* Checks if the server is responsive
* @param configuration planning service configuration
* @returns true of the service responds
*/
async isServiceAccessible(configuration: planner.PlannerConfiguration): Promise<boolean> {
const url = configuration.url;
if (!url) {
throw new Error(`Expected planning configuration with the 'url' attribute.`);
}
return new Promise<boolean>(resolve => {
const req = http.request(new URL(url), { method: 'post' }, response => {
resolve((response.statusCode !== undefined) && (response.statusCode >= 400));
}).once("error", () => {
resolve(false);
});
req.write(JSON.stringify({ domain: "", problem: "" }));
req.end();
});
}
}
export class RequestServicePlannerProvider extends LongRunningPlannerProvider {
get kind(): planner.PlannerKind {
return planner.WellKnownPlannerKind.SERVICE_ASYNC;
}
getNewPlannerLabel(): string {
// compare-changes, $(arrow-both)
return "$(cloud-upload)$(cloud-download) Input a async. service URL...";
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration): Promise<planner.PlannerConfiguration | undefined> {
const existingValue = previousConfiguration?.url ?? "http://localhost:8080/request";
const existingUri = Uri.parse(existingValue);
const indexOf = existingValue.indexOf(existingUri.authority);
const existingHostAndPort: [number, number] | undefined
= indexOf > -1 ? [indexOf, indexOf + existingUri.authority.length] : undefined;
const newPlannerUrl = await window.showInputBox({
prompt: "Enter asynchronous service URL",
placeHolder: `http://host:port/request`,
valueSelection: existingHostAndPort, //
value: existingValue,
ignoreFocusOut: true
});
if (!newPlannerUrl) { return undefined; }
return this.createPlannerConfiguration(newPlannerUrl, previousConfiguration);
}
createPlannerConfiguration(newPlannerUrl: string, previousConfiguration?: planner.PlannerConfiguration): planner.PlannerConfiguration {
return {
kind: this.kind.kind,
url: newPlannerUrl,
title: newPlannerUrl,
canConfigure: true,
path: previousConfiguration?.path
};
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
showHelp(_output: OutputAdaptor): void {
throw new Error("Method not implemented.");
}
/** Custom `Planner` implementation. */
createPlanner(configuration: planner.PlannerConfiguration, plannerInvocationOptions: planner.PlannerRunConfiguration): planner.Planner {
return RequestServicePlannerProvider.createDefaultPlanner(configuration, plannerInvocationOptions as AsyncServiceConfiguration, this);
}
/** Default `Planner` implementation. */
static createDefaultPlanner(configuration: planner.PlannerConfiguration, plannerInvocationOptions: AsyncServiceConfiguration, plannerProvider?: planner.PlannerProvider): planner.Planner {
if (configuration.url === undefined) {
throw new Error(`Planner ${configuration.title} does not specify 'url'.`);
}
const providerConfiguration: planner.ProviderConfiguration = {
configuration: configuration,
provider: plannerProvider
};
return new PlannerAsyncService(configuration.url, plannerInvocationOptions, providerConfiguration);
}
/**
* Checks if the server is responsive
* @param configuration planning service configuration
* @returns true of the service responds
*/
async isServiceAccessible(configuration: planner.PlannerConfiguration): Promise<boolean> {
const url = configuration.url;
if (!url) {
throw new Error(`Expected planning configuration with the 'url' attribute.`);
}
return new Promise<boolean>(resolve => {
const req = http.request(new URL(url), { method: 'post' }, response => {
resolve((response.statusCode !== undefined) && (response.statusCode >= 400));
}).once("error", () => {
resolve(false);
});
req.write(JSON.stringify(this.createDummyRequestBody()));
req.end();
});
}
private createDummyRequestBody(): unknown {
return {
'domain': {
'name': 'dummy-domain',
'format': 'PDDL',
'content': '' // empty
},
'problem': {
'name': 'dummy-problem',
'format': 'PDDL',
'content': '' // empty
},
'configuration': {}
};
}
}
export class JavaPlannerProvider implements planner.PlannerProvider {
get kind(): planner.PlannerKind {
return planner.WellKnownPlannerKind.JAVA_JAR;
}
getNewPlannerLabel(): string {
return "$(file-binary) Select a Java JAR file...";
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration): Promise<planner.PlannerConfiguration | undefined> {
const filters =
{
'Java executable archive': ['jar'],
};
const defaultUri = previousConfiguration?.path ? Uri.file(previousConfiguration.path) : undefined;
const executableUri = await selectedFile(`Select executable JAR`, defaultUri, filters);
if (!executableUri) { return undefined; }
const newPlannerConfiguration: planner.PlannerConfiguration = {
kind: this.kind.kind,
canConfigure: true,
path: executableUri.fsPath,
title: path.basename(executableUri.fsPath)
};
return newPlannerConfiguration;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
showHelp(_output: OutputAdaptor): void {
// do nothing
}
createPlanner(configuration: planner.PlannerConfiguration, plannerRunConfiguration: planner.PlannerRunConfiguration): planner.Planner {
if (!configuration.path) {
throw new Error('Incomplete planner configuration. Mandatory attributes: path');
}
const providerConfiguration: planner.ProviderConfiguration = {
configuration: configuration,
provider: this
};
// todo: use java.home setting
return new PlannerExecutable(`java -jar ${utils.Util.q(configuration.path)}`,
plannerRunConfiguration as planner.PlannerExecutableRunConfiguration, providerConfiguration);
}
}
export class Pddl4jProvider extends JavaPlannerProvider {
get kind(): planner.PlannerKind {
return new planner.PlannerKind('pddl4j');
}
getNewPlannerLabel(): string {
return "$(file-binary) Select a pddl4j-<ver>.jar Java JAR file...";
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration): Promise<planner.PlannerConfiguration | undefined> {
const filters =
{
'Java pddl4j-<ver>.jar': ['jar'],
};
const defaultUri = previousConfiguration?.path ? Uri.file(previousConfiguration.path) : undefined;
const executableUri = await selectedFile(`Select pddl4j-<ver>.jar`, defaultUri, filters);
if (!executableUri) { return undefined; }
const newPlannerConfiguration: planner.PlannerConfiguration = {
kind: this.kind.kind,
canConfigure: true,
path: executableUri.fsPath,
title: path.basename(executableUri.fsPath).replace('.jar', ''),
syntax: '$(planner) -o $(domain) -f $(problem) $(options)',
};
return newPlannerConfiguration;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
showHelp(_output: OutputAdaptor): void {
// do nothing
}
getPlannerOptions(): planner.PlannerOption[] {
return [
{ label: "-w <num>", option: "-w 1", description: "weight used in the a star search (default: 1)" },
{ label: "-t <num>", option: "-t 300", description: "specifies the maximum CPU-time in seconds (preset: 300)" },
{ option: "-p 0", description: "HSP planner. Simple forward planner based on A* algorithm (default)" },
{ option: "-p 1", description: "FF planner. Fast Forward planner based on Enforced Hill Climbing Algorithm and Greedy Best First Search" },
{ option: "-p 2", description: "FF Anytime planner" },
{ option: "-u 0", description: "ff heuristic" },
{ option: "-u 1", description: "sum heuristic" },
{ option: "-u 2", description: "sum mutex heuristic" },
{ option: "-u 3", description: "adjusted sum heuristic" },
{ option: "-u 4", description: "adjusted sum 2 heuristic" },
{ option: "-u 5", description: "adjusted sum 2M heuristic" },
{ option: "-u 6", description: "combo heuristic" },
{ option: "-u 7", description: "max heuristic" },
{ option: "-u 8", description: "set-level heuristic" },
{ option: "-u 9", description: "min cost heuristic" },
{ label: "-i", option: "-i 1", description: "run-time information level from 0 to 8, see -h (preset: 1)" },
{ label: "-s", option: "-s false", description: "generate statistics (default: true)" },
{ label: "-d", option: "-d true", description: "print cost in solution plan (preset: false)" },
{ option: "-h", description: "print help" },
];
}
}
export class ExecutablePlannerProvider implements planner.PlannerProvider {
get kind(): planner.PlannerKind {
return planner.WellKnownPlannerKind.EXECUTABLE;
}
getNewPlannerLabel(): string {
return "$(symbol-event) Select an executable on this computer...";
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration): Promise<planner.PlannerConfiguration | undefined> {
const filters = os.platform() === 'win32' ?
{
'Executable or batch file': ['exe', 'bat', 'cmd'],
'Executable': ['exe'],
'Batch file': ['bat', 'cmd'],
'All files': ['*']
}
: undefined;
const defaultUri = previousConfiguration?.path ? Uri.file(previousConfiguration.path) : undefined;
const executableUri = await selectedFile(`Select planner executable`, defaultUri, filters);
if (!executableUri) { return undefined; }
const newPlannerConfiguration: planner.PlannerConfiguration = {
kind: this.kind.kind,
canConfigure: true,
path: executableUri.fsPath,
title: path.basename(executableUri.fsPath)
};
return newPlannerConfiguration;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
showHelp(_output: OutputAdaptor): void {
throw new Error("Method not implemented.");
}
}
export class Popf implements planner.PlannerProvider {
get kind(): planner.PlannerKind {
return new planner.PlannerKind('popf');
}
getNewPlannerLabel(): string {
return '$(mortar-board) POPF';
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration | undefined): Promise<planner.PlannerConfiguration | undefined> {
const filters = os.platform() === 'win32' ?
{
'POPF Executable': ['exe']
}
: undefined;
const defaultUri: Uri | undefined = !!(previousConfiguration?.path) ?
Uri.file(previousConfiguration.path) :
undefined;
const popfUri = await selectedFile(`Select POPF`, defaultUri, filters);
if (!popfUri) { return undefined; }
const newPlannerConfiguration: planner.PlannerConfiguration = {
kind: this.kind.kind,
canConfigure: true,
path: popfUri.fsPath,
syntax: '$(planner) $(options) $(domain) $(problem)',
title: 'POPF'
};
return newPlannerConfiguration;
}
getPlannerOptions(): planner.PlannerOption[] {
return [
{ option: "-n", description: "Continuous searching after the first plan is reached in quest for alternative plans with a better metric" },
{ option: "-citation", description: "Display citation to relevant conference paper (ICAPS 2010)" },
{ option: "-b", description: "Disable best-first search - if EHC fails, abort" },
{ option: "-E", description: "Skip EHC: go straight to best-first search" },
{ option: "-e", description: "Use standard EHC instead of steepest descent" },
{ option: "-h", description: "Disable helpful-action pruning" },
{ option: "-k", description: "Disable compression-safe action detection" },
{ option: "-c", description: "Enable the tie-breaking in RPG that favour actions that slot into the partial order earlier" },
{ option: "-S", description: "Sort initial layer facts in RPG by availability order (only use if using -c)" },
{ option: "-m", description: "Disable the tie-breaking in search that favours plans with shorter makespans" },
{ option: "-F", description: "Full FF helpful actions (rather than just those in the RP applicable in the current state)" },
{ option: "-I", description: "Disable the hybrid Bellman-Ford--LP solver" },
{ option: "-T", description: "Rather than building a partial order, build a total-order" },
// { option: "-J123", description: "Generate search graph" },
{ option: "-v16", description: "Info about RPG generation instanciation of action found (Number of applicable actions)" },
{ option: "-v64", description: "Numeric fluents output" },
{ option: "-v1048576", description: "Verbose output details the relaxed plan for each action applied (in the standard output)." },
{ option: "-L4", description: "Prints out some LP stuff to the console " },
{ option: "-L8", description: "Outputs the LP program into a stateevaluation.lp file" },
{ option: "-L16", description: "Generates the lp program with bounds of the state variables; but overwrites the files, so you only get files for the last variable" },
];
}
}
export class Lpg implements planner.PlannerProvider {
get kind(): planner.PlannerKind {
return new planner.PlannerKind('lpg-td');
}
getNewPlannerLabel(): string {
return '$(mortar-board) LPG-td';
}
async configurePlanner(previousConfiguration?: planner.PlannerConfiguration | undefined): Promise<planner.PlannerConfiguration | undefined> {
const filters = os.platform() === 'win32' ?
{
'LPG-td Executable': ['exe']
}
: undefined;
const defaultUri: Uri | undefined = !!(previousConfiguration?.path) ?
Uri.file(previousConfiguration.path) :
undefined;
const popfUri = await selectedFile(`Select LPG-td`, defaultUri, filters);
if (!popfUri) { return undefined; }
const newPlannerConfiguration: planner.PlannerConfiguration = {
kind: this.kind.kind,
canConfigure: true,
path: popfUri.fsPath,
syntax: '$(planner) -o $(domain) -f $(problem) $(options)',
title: 'LPG-td'
};
return newPlannerConfiguration;
}
createPlanner(configuration: planner.PlannerConfiguration, plannerRunConfiguration: planner.PlannerRunConfiguration): planner.Planner {
if (!plannerRunConfiguration.options) {
// ensure mandatory option is set
plannerRunConfiguration.options = "-n 1";
}
if (!configuration.path) {
throw new Error('Incomplete planner configuration. Mandatory attributes: path');
}
const providerConfiguration: planner.ProviderConfiguration = {
configuration: configuration,
provider: this
};
return new PlannerExecutable(configuration.path,
plannerRunConfiguration as planner.PlannerExecutableRunConfiguration, providerConfiguration);
}
getPlannerOptions(): planner.PlannerOption[] {
// see https://lpg.unibs.it/lpg/README-LPGTD
return [
{
option: "-speed", description: "finds a solution (of any quality) as quickly as possible"
}, {
option: "-quality", description: "slower than in speed mode, but the planner finds a solution with better quality"
}, {
label: "-n <max number of desired solutions>", option: "-n 3"
}, {
option: "-noout", description: "no output file is produced"
}, {
option: "-v off", description: "switches off the verbose output of LPG (the planner provides only essential information)"
}, {
label: "-search_steps <integer>",
option: "-search_steps 500", description: "Specifies the initial number of search steps after which the search is "
+ "restarted. After each search restart, this number is automatically "
+ "incremented by a factor of 1.1. The default initial value for -search_steps "
+ "is 500. Note that for simple problems this value could be significantly "
+ "reduced, obtaining better performance."
}, {
label: "-restarts <integer>",
option: "-restarts 9", description: `maximum number of search restarts after which the search `
+ `is repeated for a certain number of times(see the "-repeat" parameter). `
+ `After each restart, the value of some dynamic parameters (e.g., number `
+ `of search step) is automatically changed. The default value of -restarts `
+ `is 9.`
}, {
option: "-repeats 5",
label: "-repeats <integer>", description: `maximum number of times (repeats) the local search is `
+ `repeated to find the first solution. If no solution has been found within `
+ `the specified number of repeats (and the CPU-time limit for the local `
+ `search has not been exceeded), the best-first search is activated. `
+ `Each time the local search is repeated, the dynamic settings of the `
+ `planner (e.g., the number of search steps) are set to their initial value. `
+ `When LPG-td is run in quality mode or incremental mode ("-n x", x > 1), `
+ `if a solution is found by the local search (under the specified CPU-time `
+ `limit and number of repeats), the local search is repeated until the `
+ `CPU-time limit of the local search is reached, or the number of solutions `
+ `specified by the "-n" parameter have been found. `
+ `The default value of -repeats is 5. `
}, {
option: "-noise 0.1",
label: "-noise <number between 0 and 1>", description: `Specifies the initial noise value for Walkplan. Such value is dynamically `
+ `modified during each restart using a technique described in in Gerevini, `
+ `Saetti, Serina "An Empirical Analysis of Some Heuristic Features for Local `
+ `Search in LPG", ICAPS'04. The default value of -noise is 0.1. `
}, {
option: "-maxnoise <number>", description: "Specifies the maximum noise value that can (automatically) be reached by "
+ "the dynamic noise. "
}, {
option: "-static_noise 0.1",
label: "-static_noise", description: `Switches off the dynamic noise during each restart. The value of the `
+ `noise is fixed. The default value is 0.1, and it can be changed by using `
+ `the "-noise" parameter. `
}, {
label: "-seed <integer>", option: "-seed 2004",
description: `Specifies the seed for the random number generator used by Walkplan `
+ `(a stochastic local search procedure). By using the same seed number, `
+ `it is possible to repeat identical runs. The output files containing the `
+ `solutions produced by LPG include the seed number used by the planner to `
+ `generate them. In the 4th IPC, we used "-seed 2004". `
}, {
option: "-lowmemory", description: `With this option, the mutex relations between actions are computed at `
+ `runtime (instead of being computed before searching). We recommend the `
+ `use of this option only for very large problems. `
}, {
label: "-cputime <sec>", option: "-cputime 1800",
description: "Specifies the maximum CPU-time (in seconds) after which termination of "
+ "the planning process is forced. The default value is 1800 (30 minutes). "
}, {
label: "-cputime_localsearch <sec>", option: "-cputime_localsearch 1200",
description: `When all restarts of the local search have been performed without finding `
+ `a solution, LPG runs in a best-first search based on Joerg Hoffman's `
+ `implementation (FF package v2.3). This option specifies the maximum `
+ `CPU-time (in seconds) after which the best-first search starts. `
+ `The default value is 1200 (20 minutes). `
}, {
option: "-nobestfirst", description: "With this option, LPG-td does not run best-first search. "
}, {
option: "-onlybestfirst", description: "Forces the immediate run of the best-first search (no local search is performed). "
}, {
option: "-timesteps", description: "This option can be used in STRIPS domains to define the plan quality "
+ "metric as number of (Graphplan) time steps. "
},
];
}
}
// const node: QuickPickItem = {
// label: "$(file-code) Select a Node.js file..."
// };
// const python: QuickPickItem = {
// label: "$(file-text) Select a Python file..."
// };
// ${command:python.interpreterPath}
async function selectedFile(label: string, defaultUri?: Uri, filters?: { [name: string]: string[] }): Promise<Uri | undefined> {
const selectedUris = await window.showOpenDialog({
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
openLabel: label,
filters: filters,
defaultUri: defaultUri
});
if (!selectedUris) {
return undefined;
}
return selectedUris[0];
} | the_stack |
import AWS from 'aws-sdk'
import { PutObjectRequest } from 'aws-sdk/clients/s3'
import { PackageStatus, DomainPackageStatus } from 'aws-sdk/clients/es'
import { ElasticsearchIndexLocale } from '@island.is/content-search-index-manager'
import { logger } from '@island.is/logging'
import { environment } from '../../environments/environment'
import { Dictionary } from './dictionary'
AWS.config.update({ region: environment.awsRegion })
const awsEs = new AWS.ES()
const s3 = new AWS.S3()
const sleep = (sec: number) => {
return new Promise((resolve) => {
setTimeout(resolve, sec * 1000)
})
}
// construct the name used for packages in AWS ES
const createPackageName = (
locale: string,
analyzerType: string,
version: string,
) => {
return `${locale}-${analyzerType}-${version}`
}
// break down the name used for packages in AWS ES
export const parsePackageName = (packageName: string) => {
const [locale, analyzerType, version] = packageName.split('-')
return {
locale,
analyzerType,
version,
}
}
interface PackageStatuses {
packageStatus: PackageStatus
domainStatus: DomainPackageStatus
}
const getPackageStatuses = async (
packageId: string,
): Promise<PackageStatuses> => {
const params = {
Filters: [
{
Name: 'PackageID',
Value: [packageId],
},
],
}
const packages = await awsEs.describePackages(params).promise()
const domainPackageList = await awsEs
.listPackagesForDomain({
DomainName: environment.esDomain,
})
.promise()
const domainPackage = domainPackageList.DomainPackageDetailsList.find(
(listItem) => listItem.PackageID === packageId,
)
return {
packageStatus: packages.PackageDetailsList[0].PackageStatus,
domainStatus: domainPackage?.DomainPackageStatus ?? 'DISSOCIATED',
}
}
export const getAssociatedEsPackages = async (
requestedVersion: string,
): Promise<AwsEsPackage[]> => {
const domainPackageList = await awsEs
.listPackagesForDomain({
DomainName: environment.esDomain,
})
.promise()
return (
domainPackageList.DomainPackageDetailsList
// we only want to return packages for current version
.filter((esPackage) => {
const { version, locale, analyzerType } = parsePackageName(
esPackage.PackageName,
)
logger.info('Found associated package for domain', {
version,
locale,
analyzerType,
requestedVersion,
willBeUsed: requestedVersion === version,
})
return requestedVersion === version
})
.map((esPackage) => {
const { locale, analyzerType } = parsePackageName(esPackage.PackageName)
return {
packageName: esPackage.PackageName,
packageId: esPackage.PackageID,
locale: locale as ElasticsearchIndexLocale,
analyzerType,
}
})
)
}
// AWS ES wont let us make multiple requests at once so we wait
const waitForPackageStatus = async (
packageId: string,
desiredStatus: PackageStatus | DomainPackageStatus,
totalSecondsWaited = 0,
) => {
const secondsBetweenRequests = 5
const timeoutSeconds = 300
if (totalSecondsWaited >= timeoutSeconds) {
throw new Error(`Failed to get status for package ${packageId}`)
}
// if we find the desired status in either the domain package list or the unassigned package list we assume success
const { packageStatus, domainStatus } = await getPackageStatuses(packageId)
if (packageStatus === desiredStatus || domainStatus === desiredStatus) {
return true
}
logger.info('Waiting for correct package status', {
packageId,
desiredStatus,
currentPackageStatus: packageStatus,
currentDomainStatus: domainStatus,
secondsBetweenRequests,
totalSecondsWaited,
})
// wait X seconds to make next status request
await sleep(secondsBetweenRequests)
return await waitForPackageStatus(
packageId,
desiredStatus,
(totalSecondsWaited = totalSecondsWaited + secondsBetweenRequests),
)
}
// checks connection and validates that we have access to requested domain
export const checkAWSAccess = async (): Promise<boolean> => {
if (!environment.s3Bucket) {
logger.info('No credentials provided for AWS')
return false
}
const domains = await awsEs
.listDomainNames()
.promise()
.then((domains) => domains.DomainNames)
.catch((error) => {
logger.error('Failed to check aws access', { error })
// return empty list to indicate no access
return []
})
logger.info('Validating esDomain agains aws domain list', { domains })
return !!domains.find((domain) => domain.DomainName === environment.esDomain)
}
interface CreateS3KeyInput {
filename: string
locale: ElasticsearchIndexLocale
version: string
}
const createS3Key = ({
filename,
locale,
version,
}: CreateS3KeyInput): string => {
const prefix = [locale, version, '']
.filter((parameter) => parameter !== undefined)
.join('/') // creates folder prefix e.g. is/4cc9840/
return `${environment.s3Folder}${prefix}${filename}.txt`
}
const uploadFileToS3 = (options: Omit<PutObjectRequest, 'Bucket'>) => {
const params = {
Bucket: environment.s3Bucket,
...options,
}
logger.info('Uploading file to s3', {
Bucket: params.Bucket,
Key: params.Key,
})
return s3
.upload(params)
.promise()
.catch((error) => {
logger.error('Failed to upload s3 package', error)
throw error
})
}
const checkIfS3Exists = (key: string) => {
return s3
.headObject({
Bucket: environment.s3Bucket,
Key: key,
})
.promise()
.then(() => true)
.catch(() => false) // we don't want this to throw on error so we can handle if not exists manually
}
interface S3DictionaryFile {
locale: ElasticsearchIndexLocale
analyzerType: string
version: string
}
export const uploadS3DictionaryFiles = async (
dictionaries: Dictionary[],
): Promise<S3DictionaryFile[]> => {
const uploads = dictionaries.map(async (dictionary) => {
const { analyzerType, locale, file, version } = dictionary
// we will upload the files into subfolders by locale
const s3Key = createS3Key({ filename: analyzerType, locale, version })
const exists = await checkIfS3Exists(s3Key)
if (!exists) {
logger.info('S3 file not found, uploading file', { key: s3Key })
await uploadFileToS3({ Key: s3Key, Body: file })
} else {
logger.info('S3 file found, skipping upload of file', { key: s3Key })
}
// the following processes just need a way to point correctly to the files
return {
locale,
analyzerType,
version,
}
})
return await Promise.all(uploads)
}
const getAwsEsPackagesDetails = async () => {
logger.info('Getting all AWS ES packages')
const packages = await awsEs.describePackages({ MaxResults: 100 }).promise()
return packages.PackageDetailsList
}
const checkIfAwsEsPackageExists = async (
packageName: string,
): Promise<string | null> => {
const esPackages = await getAwsEsPackagesDetails()
logger.info('Checking if package exists', { packageName })
const foundPackage = esPackages.find(
(esPackage) => esPackage.PackageName === packageName,
)
return foundPackage?.PackageID ?? null
}
/*
createAwsEsPackages should only run when we are updating, we can therefore assume no assigned packages exist in AWS ES for this version
We run a remove packages for this version function to handle failed partial updates that might not have associated the package to the domain
*/
export interface AwsEsPackage {
packageName?: string
packageId: string
locale: ElasticsearchIndexLocale
analyzerType: string
}
export const createAwsEsPackages = async (
uploadedDictionaryFiles: S3DictionaryFile[],
): Promise<AwsEsPackage[]> => {
// create a new package for each uploaded s3 file
const createdPackages = uploadedDictionaryFiles.map(async (uploadedFile) => {
const { analyzerType, locale, version } = uploadedFile
const packageName = createPackageName(locale, analyzerType, version)
const foundPackageId = await checkIfAwsEsPackageExists(packageName)
let uploadedPackageId
if (!foundPackageId) {
const params = {
PackageName: createPackageName(locale, analyzerType, version), // version is here so we don't conflict with older packages
PackageType: 'TXT-DICTIONARY',
PackageSource: {
S3BucketName: environment.s3Bucket,
S3Key: createS3Key({ filename: analyzerType, locale, version }),
},
}
logger.info('Creating AWS ES package', params)
const esPackage = await awsEs.createPackage(params).promise()
// we have to wait for package to be ready cause AWS ES can only process one request at a time
await waitForPackageStatus(
esPackage.PackageDetails.PackageID,
'AVAILABLE',
)
logger.info('Created AWS ES package', { esPackage })
uploadedPackageId = esPackage.PackageDetails.PackageID
} else {
logger.info('AWS ES package found, skipping upload of package', {
packageId: foundPackageId,
})
}
return {
packageId: uploadedPackageId ?? foundPackageId,
locale,
analyzerType,
}
})
return Promise.all(createdPackages)
}
const getDomainPackages = () => {
return awsEs
.listPackagesForDomain({
DomainName: environment.esDomain,
})
.promise()
}
const getPackageAssociationStatus = async (
packageId,
): Promise<'missing' | 'active' | 'broken'> => {
const domainPackageList = await getDomainPackages()
const domainPackage = domainPackageList.DomainPackageDetailsList.find(
(domainPackageEntry) => domainPackageEntry.PackageID === packageId,
)
if (!domainPackage) {
return 'missing'
}
return domainPackage.DomainPackageStatus === 'ACTIVE' ? 'active' : 'broken'
}
const dissociatePackageWithAwsEsSearchDomain = async (packageId: string) => {
const params = {
DomainName: environment.esDomain,
PackageID: packageId,
}
logger.info('Disassociating package from AWS ES domain', params)
const result = await awsEs.dissociatePackage(params).promise()
await waitForPackageStatus(packageId, 'DISSOCIATED')
return result
}
export const associatePackagesWithAwsEsSearchDomain = async (
packages: AwsEsPackage[],
) => {
// we have to do one at a time due to limitations in AWS API
for (const awsEsPackage of packages) {
const packageId = awsEsPackage.packageId
const packageStatus = await getPackageAssociationStatus(packageId)
if (packageStatus === 'broken') {
logger.error('Package failed to associate correctly attempting to remove')
await dissociatePackageWithAwsEsSearchDomain(packageId)
logger.error('Dissociation successful, continuing')
}
if (packageStatus === 'missing' || packageStatus === 'broken') {
const params = {
DomainName: environment.esDomain,
PackageID: packageId,
}
logger.info('Associating package with AWS ES domain', params)
const esPackage = await awsEs.associatePackage(params).promise()
// we have to wait for package to be ready cause AWS ES can only process one request at a time
await waitForPackageStatus(
esPackage.DomainPackageDetails.PackageID,
'ACTIVE',
)
} else {
logger.info(
'AWS ES package already associated, skipping association of package',
{
packageId,
},
)
}
}
logger.info('Successfully associated all packages with AWS ES instance')
return true
} | the_stack |
import { mergeStyles, Separator, Stack } from 'office-ui-fabric-react';
import React from 'react';
import { HideAt, ShowAt } from 'react-with-breakpoints';
import { logEvent } from '../Shared/AppInsights';
import { ArtObject, ArtMatch, loadingMatch, loadingArtwork } from "../Shared/ArtSchemas";
import bannerImage from "../images/banner5.jpg";
import { defaultArtworks, idToArtwork } from './DefaultArtwork';
import ListCarousel from './ListCarousel';
import Options from './Options';
import QueryArtwork from './QueryArtwork';
import ResultArtwork from './ResultArtwork';
import SubmitControl from './SubmitControl';
import { nMatches } from '../Shared/SearchTools';
import { lookupWithMatches, lookup, cultures, media } from '../Shared/SearchTools'
import NavBar from '../Shared/NavBar';
import Popup from 'reactjs-popup';
import { isBeta, betaMessageDiv } from '../Shared/BetaTools';
interface IProps {
match: any
history: any
};
interface IState {
queryArtwork: ArtObject,
chosenArtwork: ArtObject,
imageDataURI: string | null,
cultureItems: ArtMatch[],
mediumItems: ArtMatch[],
cultureFilter: string,
mediumFilter: string,
shareLink: string | null,
open: boolean
}
const halfStack = mergeStyles({
width: "50%",
height: "100%"
})
const startingCultures = ["american", "asian", "ancient_asian", "greek", "italian", "african", "chinese", "roman", "egyptian"]
const startingMedia = ["paintings", "ceramics", "stone", "sculptures", "prints", "glass", "textiles", "photographs", "drawings"]
/**
* The Page thats shown when the user first lands onto the website
*/
export default class ExplorePage extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
queryArtwork: loadingArtwork,
chosenArtwork: loadingArtwork,
imageDataURI: null,
cultureItems: Array(nMatches).fill(loadingMatch),
mediumItems: Array(nMatches).fill(loadingMatch),
cultureFilter: startingCultures[Math.floor(Math.random() * Math.floor(startingCultures.length))],
mediumFilter: startingMedia[Math.floor(Math.random() * Math.floor(startingMedia.length))],
shareLink: null,
open: false
}
// Bind everything for children
this.setResultArtwork = this.setResultArtwork.bind(this);
this.scrollToReference = this.scrollToReference.bind(this);
this.changeCulture = this.changeCulture.bind(this);
this.changeMedium = this.changeMedium.bind(this);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
}
// Reference for scrolling to the start of the compare block
startRef = React.createRef<HTMLDivElement>();
/**
* Executes a smooth scroll effect to a specified reference
* @param reference the reference object to scroll to
*/
scrollToReference(reference: any): void {
window.scrollTo({ top: reference.current.offsetTop, left: 0, behavior: "smooth" });
}
changeCulture(option: string): void {
this.setState({ cultureFilter: option }, () => this.executeQuery(this.state.queryArtwork.id!, true));
}
changeMedium(option: string): void {
this.setState({ mediumFilter: option }, () => this.executeQuery(this.state.queryArtwork.id!, false));
}
openModal() {
this.setState({ open: true });
}
closeModal() {
this.setState({ open: false });
}
/**
* Updates the result artwork; enables the rationale button if either artwork have rationale overlays
* @param newResultArtwork the artwork to set as the new result
* @param originalArtwork the original artwork
*/
setResultArtwork(newResultArtwork: ArtMatch): void {
let self = this;
this.updateBestMatch(self, newResultArtwork.id!)
}
updateBestMatch(component: any, id: string) {
lookup(id)
.then(function (responseJson) {
component.setState({
chosenArtwork: new ArtObject(
responseJson.Artist,
responseJson.Classification,
responseJson.Culture,
responseJson.Image_Url,
responseJson.Museum,
responseJson.Museum_Page,
responseJson.Thumbnail_Url,
responseJson.Title,
responseJson.id),
}, component.updateImageDataURI)
})
}
executeQueryWithDefaults(artworkID: string) {
if (artworkID in idToArtwork) {
this.setState({
cultureFilter: idToArtwork[artworkID].defaultCulture || this.state.cultureFilter,
mediumFilter: idToArtwork[artworkID].defaultMedium || this.state.mediumFilter
}, () => {
this.executeQuery(artworkID!, false)
});
} else {
this.executeQuery(artworkID!, false);
};
}
/**
* Queries API with the original artwork with conditional qualities
*/
executeQuery(artworkID: string, promoteCultureMatch: boolean) {
let self = this;
lookupWithMatches(artworkID, self.state.cultureFilter, self.state.mediumFilter)
.then(function (responseJson) {
const cultureInfo = responseJson.matches.culture[self.state.cultureFilter]
const mediumInfo = responseJson.matches.medium[self.state.mediumFilter]
function infoToMatches(info: any): ArtMatch[] {
return info.ids.map(function (id: string, i: any) {
return new ArtMatch(info.urls[i], id, null);
})
}
const cultureMatches = infoToMatches(cultureInfo).filter(match => match.id !== artworkID)
const mediumMatches = infoToMatches(mediumInfo).filter(match => match.id !== artworkID)
self.setState({
queryArtwork: new ArtObject(
responseJson.Artist,
responseJson.Classification,
responseJson.Culture,
responseJson.Image_Url,
responseJson.Museum,
responseJson.Museum_Page,
responseJson.Thumbnail_Url,
responseJson.Title,
responseJson.id),
cultureItems: cultureMatches,
mediumItems: mediumMatches
});
if (promoteCultureMatch) {
return cultureMatches
} else {
return mediumMatches
}
})
.then(function (matches) {
if (artworkID in idToArtwork
&& "defaultResultId" in idToArtwork[artworkID]
&& matches.map(m => m.id!).indexOf(idToArtwork[artworkID].defaultResultId) >= 0) {
self.updateBestMatch(self, idToArtwork[artworkID].defaultResultId)
} else {
self.updateBestMatch(self, matches[0].id!)
}
})
}
/**
* Intialization code for the explore webpage
*/
componentDidMount() {
let artworkID: string | null = null;
//Get State from URL
if (this.props.match.params.data) {
const url = decodeURIComponent(this.props.match.params.data);
if (url != null) {
artworkID = url.split("&")[0].slice(4);
}
}
//If the url has no parameters, randomly pick one from the default list.
//Every art in the default list has Rationale available.
if (artworkID == null) {
let numDefaults = defaultArtworks.length;
let randIndex = Math.floor(Math.random() * Math.floor(numDefaults));
artworkID = defaultArtworks[randIndex].id;
}
this.executeQueryWithDefaults(artworkID)
}
render() {
return (
<Stack className="main" role="main">
<NavBar />
<div className="page-wrap" style={{ position: "relative", top: "-20px", width: "100%", overflow: "hidden" }}>
<HideAt breakpoint="mediumAndBelow">
<div className="explore__background-banner">
<img className="explore__parallax" alt={"Banner comparing two artworks"} src={bannerImage} />
<div className="explore__banner-text">Explore the hidden connections between art of different cultures and media.</div>
</div>
<div className="explore__solid">
<Stack horizontal horizontalAlign="center" verticalAlign="center" wrap>
<div className="explore__pick-image-text">Pick an image to get started:</div>
<ListCarousel
items={defaultArtworks}
selectorCallback={(am) => {
this.props.history.push("/app/" + encodeURIComponent('?id=' + am.id!));
this.executeQueryWithDefaults(am.id!)
}}
selectedArtwork={this.state.queryArtwork} />
</Stack>
</div>
<div style={{ backgroundColor: "white" }}><Separator /></div>
<div ref={this.startRef} className="explore__compare-block explore__solid">
<Stack horizontal>
<Stack.Item className={halfStack} grow={1}>
<QueryArtwork artwork={this.state.queryArtwork} />
</Stack.Item>
<Stack.Item className={halfStack} grow={1}>
<ResultArtwork artwork={this.state.chosenArtwork} />
</Stack.Item>
</Stack>
</div>
</HideAt>
<ShowAt breakpoint="mediumAndBelow">
<div className="explore__solid">
<Stack horizontal horizontalAlign="center" verticalAlign="center" wrap>
<div className="explore__pick-image-text">Pick an image to get started:</div>
<ListCarousel
items={defaultArtworks}
selectorCallback={(am) => {
this.props.history.push("/app/" + encodeURIComponent('?id=' + am.id!));
this.executeQueryWithDefaults(am.id!)
}}
selectedArtwork={this.state.chosenArtwork!} />
</Stack>
</div>
<Separator />
<div className="explore__compare-block explore__solid">
<Stack horizontal horizontalAlign="center" wrap>
<Stack.Item grow={1}>
<QueryArtwork artwork={this.state.queryArtwork} />
</Stack.Item>
<Stack.Item grow={1}>
<ResultArtwork artwork={this.state.chosenArtwork} />
</Stack.Item>
</Stack>
</div>
</ShowAt>
<div className="explore__solid">
<Stack horizontalAlign="center">
<Stack horizontal horizontalAlign="center">
<button
onClick={() => {
if (isBeta) {
this.props.history.push("/app/" + encodeURIComponent('?id=' + this.state.chosenArtwork.id!));
this.executeQueryWithDefaults(this.state.chosenArtwork.id!);
logEvent("Matches", { "Location": "ResultImage" });
} else {
this.openModal()
};
}}
className="explore__buttons button">Use Match as Query</button>
<Popup
open={this.state.open}
closeOnDocumentClick
onClose={this.closeModal}
>
<div className="modal">
<button className="close" onClick={this.closeModal}>
×
</button>
{betaMessageDiv}
</div>
</Popup>
</Stack>
</Stack>
<Separator />
<div className="explore__big-text">Choose Different Cultures and Media:</div>
<Stack horizontal horizontalAlign="start" verticalAlign="center" wrap>
<Options
value={this.state.cultureFilter}
choices={cultures}
changeConditional={this.changeCulture} />
<ListCarousel
items={this.state.cultureItems!}
selectorCallback={this.setResultArtwork}
selectedArtwork={this.state.chosenArtwork!} />
</Stack>
<Separator />
<Stack horizontal horizontalAlign="start" verticalAlign="center" wrap>
<Options
value={this.state.mediumFilter}
choices={media}
changeConditional={this.changeMedium} />
<ListCarousel
items={this.state.mediumItems!}
selectorCallback={this.setResultArtwork}
selectedArtwork={this.state.chosenArtwork!} />
</Stack>
<Separator />
<Stack horizontal horizontalAlign="center">
<SubmitControl placeholder="Search the collection for other artworks" />
</Stack>
<Stack horizontalAlign="center">
<div className="explore__big-text">Learn More:</div>
<HideAt breakpoint="small">
<div className="explore__horizontal-img-container">
<a target="_blank" rel="noopener noreferrer" href="https://arxiv.org/abs/2007.07177" >
<button className="explore__buttons button">Read The Paper</button></a>
<a target="_blank" rel="noopener noreferrer" href="https://note.microsoft.com/MSR-Webinar-Visual-Analogies-Registration-Live.html" >
<button className="explore__buttons button">Watch The Webinar</button></a>
<a target="_blank" rel="noopener noreferrer" href="https://github.com/microsoft/art" >
<button className="explore__buttons button">Github</button></a>
</div>
</HideAt>
<ShowAt breakpoint="small">
<a target="_blank" rel="noopener noreferrer" href="https://arxiv.org/abs/2007.07177" >
<button className="explore__buttons button">Read The Paper</button></a>
<a target="_blank" rel="noopener noreferrer" href="https://note.microsoft.com/MSR-Webinar-Visual-Analogies-Registration-Live.html" >
<button className="explore__buttons button">Watch The Webinar</button></a>
<a target="_blank" rel="noopener noreferrer" href="https://github.com/microsoft/art" >
<button className="explore__buttons button">Github</button></a>
</ShowAt>
</Stack>
</div>
</div>
</Stack>
)
}
} | the_stack |
import * as ts from 'typescript';
import {
Finding,
EffectiveConfiguration,
LintAndFixFileResult,
Replacement,
RuleContext,
Severity,
RuleConstructor,
MessageHandler,
AbstractProcessor,
DeprecationHandler,
DeprecationTarget,
FindingFilterFactory,
FindingFilter,
} from '@fimbul/ymir';
import { applyFixes } from './fix';
import * as debug from 'debug';
import { injectable } from 'inversify';
import { RuleLoader } from './services/rule-loader';
import { calculateChangeRange, emptyArray, invertChangeRange, mapDefined } from './utils';
import { ConvertedAst, convertAst, isCompilerOptionEnabled, getTsCheckDirective } from 'tsutils';
const log = debug('wotan:linter');
export interface LinterOptions {
reportUselessDirectives?: Severity;
}
/** This factory is used to lazily create or update the Program only when necessary. */
export interface ProgramFactory {
/** Get the CompilerOptions used to create the Program. */
getCompilerOptions(): ts.CompilerOptions;
/** This method is called to retrieve the Program on the first use. It should create or update the Program if necessary. */
getProgram(): ts.Program;
}
class StaticProgramFactory implements ProgramFactory {
constructor(private program: ts.Program) {}
public getCompilerOptions() {
return this.program.getCompilerOptions();
}
public getProgram() {
return this.program;
}
}
class CachedProgramFactory implements ProgramFactory {
private program: ts.Program | undefined = undefined;
private options: ts.CompilerOptions | undefined = undefined;
constructor(private factory: ProgramFactory) {}
public getCompilerOptions() {
return this.options ??= this.factory.getCompilerOptions();
}
public getProgram() {
if (this.program === undefined) {
this.program = this.factory.getProgram();
this.options = this.program.getCompilerOptions();
}
return this.program;
}
}
/**
* Creates a new SourceFile from the updated source.
*
* @returns the new `SourceFile` on success or `undefined` to roll back the latest set of changes.
*/
export type UpdateFileCallback = (content: string, range: ts.TextChangeRange) => ts.SourceFile | undefined;
@injectable()
export class Linter {
constructor(
private ruleLoader: RuleLoader,
private logger: MessageHandler,
private deprecationHandler: DeprecationHandler,
private filterFactory: FindingFilterFactory,
) {}
public lintFile(
file: ts.SourceFile,
config: EffectiveConfiguration,
programOrFactory?: ProgramFactory | ts.Program,
options: LinterOptions = {},
): ReadonlyArray<Finding> {
return this.getFindings(
file,
config,
programOrFactory !== undefined && 'getTypeChecker' in programOrFactory
? new StaticProgramFactory(programOrFactory)
: programOrFactory,
undefined,
options,
);
}
public lintAndFix(
file: ts.SourceFile,
content: string,
config: EffectiveConfiguration,
updateFile: UpdateFileCallback,
iterations: number = 10,
programFactory?: ProgramFactory,
processor?: AbstractProcessor,
options: LinterOptions = {},
/** Initial set of findings from a cache. If provided, the initial linting is skipped and these findings are used for fixing. */
findings = this.getFindings(file, config, programFactory, processor, options),
): LintAndFixFileResult {
let totalFixes = 0;
for (let i = 0; i < iterations; ++i) {
if (findings.length === 0)
break;
const fixes = mapDefined(findings, (f) => f.fix);
if (fixes.length === 0) {
log('No fixes');
break;
}
log('Trying to apply %d fixes in %d. iteration', fixes.length, i + 1);
const fixed = applyFixes(content, fixes);
log('Applied %d fixes', fixed.fixed);
let newSource: string;
let fixedRange: ts.TextChangeRange;
if (processor !== undefined) {
const {transformed, changeRange} = processor.updateSource(fixed.result, fixed.range);
fixedRange = changeRange ?? calculateChangeRange(file.text, transformed);
newSource = transformed;
} else {
newSource = fixed.result;
fixedRange = fixed.range;
}
const updateResult = updateFile(newSource, fixedRange);
if (updateResult === undefined) {
log('Rolling back latest fixes and abort linting');
processor?.updateSource(content, invertChangeRange(fixed.range)); // reset processor state
break;
}
file = updateResult;
content = fixed.result;
totalFixes += fixed.fixed;
findings = this.getFindings(file, config, programFactory, processor, options);
}
return {
content,
findings,
fixes: totalFixes,
};
}
// @internal
public getFindings(
sourceFile: ts.SourceFile,
config: EffectiveConfiguration,
programFactory: ProgramFactory | undefined,
processor: AbstractProcessor | undefined,
options: LinterOptions,
) {
// make sure that all rules get the same Program and CompilerOptions for this run
programFactory &&= new CachedProgramFactory(programFactory);
let suppressMissingTypeInfoWarning = false;
log('Linting file %s', sourceFile.fileName);
if (programFactory !== undefined) {
const directive = getTsCheckDirective(sourceFile.text);
if (
directive !== undefined
? !directive.enabled
: /\.jsx?/.test(sourceFile.fileName) && !isCompilerOptionEnabled(programFactory.getCompilerOptions(), 'checkJs')
) {
log('Not using type information for this unchecked file');
programFactory = undefined;
suppressMissingTypeInfoWarning = true;
}
}
const rules = this.prepareRules(config, sourceFile, programFactory, suppressMissingTypeInfoWarning);
let findings;
if (rules.length === 0) {
log('No active rules');
if (options.reportUselessDirectives !== undefined) {
findings = this.filterFactory
.create({sourceFile, getWrappedAst() { return convertAst(sourceFile).wrapped; }, ruleNames: emptyArray})
.reportUseless(options.reportUselessDirectives);
log('Found %d useless directives', findings.length);
} else {
findings = emptyArray;
}
} else {
findings = this.applyRules(sourceFile, programFactory, rules, config.settings, options);
}
return processor === undefined ? findings : processor.postprocess(findings);
}
private prepareRules(
config: EffectiveConfiguration,
sourceFile: ts.SourceFile,
programFactory: ProgramFactory | undefined,
noWarn: boolean,
) {
const rules: PreparedRule[] = [];
for (const [ruleName, {options, severity, rulesDirectories, rule}] of config.rules) {
if (severity === 'off')
continue;
const ctor = this.ruleLoader.loadRule(rule, rulesDirectories);
if (ctor === undefined)
continue;
if (ctor.deprecated)
this.deprecationHandler.handle(
DeprecationTarget.Rule,
ruleName,
typeof ctor.deprecated === 'string' ? ctor.deprecated : undefined,
);
if (programFactory === undefined && ctor.requiresTypeInformation) {
if (noWarn) {
log('Rule %s requires type information', ruleName);
} else {
this.logger.warn(`Rule '${ruleName}' requires type information.`);
}
continue;
}
if (ctor.supports !== undefined) {
const supports = ctor.supports(sourceFile, {
get program() { return programFactory && programFactory.getProgram(); },
get compilerOptions() { return programFactory && programFactory.getCompilerOptions(); },
options,
settings: config.settings,
});
if (supports !== true) {
if (!supports) {
log(`Rule %s does not support this file`, ruleName);
} else {
log(`Rule %s does not support this file: %s`, ruleName, supports);
}
continue;
}
}
rules.push({ruleName, options, severity, ctor});
}
return rules;
}
private applyRules(
sourceFile: ts.SourceFile,
programFactory: ProgramFactory | undefined,
rules: PreparedRule[],
settings: Map<string, any>,
options: LinterOptions,
) {
const result: Finding[] = [];
let findingFilter: FindingFilter | undefined;
let ruleName: string;
let severity: Severity;
let ctor: RuleConstructor;
let convertedAst: ConvertedAst | undefined;
const getFindingFilter = () => {
return findingFilter ??= this.filterFactory.create({sourceFile, getWrappedAst, ruleNames: rules.map((r) => r.ruleName)});
};
const addFinding = (pos: number, end: number, message: string, fix?: Replacement | ReadonlyArray<Replacement>) => {
const finding: Finding = {
ruleName,
severity,
message,
start: {
position: pos,
...ts.getLineAndCharacterOfPosition(sourceFile, pos),
},
end: {
position: end,
...ts.getLineAndCharacterOfPosition(sourceFile, end),
},
fix: fix === undefined
? undefined
: !Array.isArray(fix)
? {replacements: [fix]}
: fix.length === 0
? undefined
: {replacements: fix},
};
if (getFindingFilter().filter(finding))
result.push(finding);
};
const context: { -readonly [K in keyof RuleContext]: RuleContext[K] } = {
addFinding,
getFlatAst,
getWrappedAst,
get program() { return programFactory?.getProgram(); },
get compilerOptions() { return programFactory?.getCompilerOptions(); },
sourceFile,
settings,
options: undefined,
};
for ({ruleName, severity, ctor, options: context.options} of rules) {
log('Executing rule %s', ruleName);
new ctor(context).apply();
}
log('Found %d findings', result.length);
if (options.reportUselessDirectives !== undefined) {
const useless = getFindingFilter().reportUseless(options.reportUselessDirectives);
log('Found %d useless directives', useless.length);
result.push(...useless);
}
return result;
function getFlatAst() {
return (convertedAst ??= convertAst(sourceFile)).flat;
}
function getWrappedAst() {
return (convertedAst ??= convertAst(sourceFile)).wrapped;
}
}
}
interface PreparedRule {
ctor: RuleConstructor;
options: any;
ruleName: string;
severity: Severity;
} | the_stack |
namespace ts.projectSystem {
function createExportingModuleFile(path: string, exportPrefix: string, exportCount: number): File {
return {
path,
content: fill(exportCount, i => `export const ${exportPrefix}_${i} = ${i};`).join("\n"),
};
}
function createExportingModuleFiles(pathPrefix: string, fileCount: number, exportCount: number, getExportPrefix: (fileIndex: number) => string): File[] {
return fill(fileCount, fileIndex => createExportingModuleFile(
`${pathPrefix}_${fileIndex}.ts`,
getExportPrefix(fileIndex),
exportCount));
}
function createNodeModulesPackage(packageName: string, fileCount: number, exportCount: number, getExportPrefix: (fileIndex: number) => string): File[] {
const exportingFiles = createExportingModuleFiles(`/node_modules/${packageName}/file`, fileCount, exportCount, getExportPrefix);
return [
{
path: `/node_modules/${packageName}/package.json`,
content: `{ "types": "index.d.ts" }`,
},
{
path: `/node_modules/${packageName}/index.d.ts`,
content: exportingFiles
.map(f => `export * from "./${removeFileExtension(convertToRelativePath(f.path, `/node_modules/${packageName}/`, identity))}";`)
.join("\n") + `\nexport default function main(): void;`,
},
...exportingFiles,
];
}
const indexFile: File = {
path: "/index.ts",
content: ""
};
const tsconfigFile: File = {
path: "/tsconfig.json",
content: `{ "compilerOptions": { "module": "commonjs" } }`
};
const packageJsonFile: File = {
path: "/package.json",
content: `{ "dependencies": { "dep-a": "*" } }`,
};
describe("unittests:: tsserver:: completionsIncomplete", () => {
it("works", () => {
const excessFileCount = Completions.moduleSpecifierResolutionLimit + 50;
const exportingFiles = createExportingModuleFiles(`/lib/a`, Completions.moduleSpecifierResolutionLimit + excessFileCount, 1, i => `aa_${i}_`);
const { typeToTriggerCompletions, session } = setup([tsconfigFile, indexFile, ...exportingFiles]);
openFilesForSession([indexFile], session);
typeToTriggerCompletions(indexFile.path, "a", completions => {
assert(completions.isIncomplete);
assert.lengthOf(completions.entries.filter(entry => (entry.data as any)?.moduleSpecifier), Completions.moduleSpecifierResolutionLimit);
assert.lengthOf(completions.entries.filter(entry => entry.source && !(entry.data as any)?.moduleSpecifier), excessFileCount);
})
.continueTyping("a", completions => {
assert(completions.isIncomplete);
assert.lengthOf(completions.entries.filter(entry => (entry.data as any)?.moduleSpecifier), Completions.moduleSpecifierResolutionLimit * 2);
})
.continueTyping("_", completions => {
assert(!completions.isIncomplete);
assert.lengthOf(completions.entries.filter(entry => (entry.data as any)?.moduleSpecifier), exportingFiles.length);
});
});
it("resolves more when available from module specifier cache (1)", () => {
const exportingFiles = createExportingModuleFiles(`/lib/a`, 50, 50, i => `aa_${i}_`);
const { typeToTriggerCompletions, session } = setup([tsconfigFile, indexFile, ...exportingFiles]);
openFilesForSession([indexFile], session);
typeToTriggerCompletions(indexFile.path, "a", completions => {
assert(!completions.isIncomplete);
});
});
it("resolves more when available from module specifier cache (2)", () => {
const excessFileCount = 50;
const exportingFiles = createExportingModuleFiles(`/lib/a`, Completions.moduleSpecifierResolutionLimit + excessFileCount, 1, i => `aa_${i}_`);
const { typeToTriggerCompletions, session } = setup([tsconfigFile, indexFile, ...exportingFiles]);
openFilesForSession([indexFile], session);
typeToTriggerCompletions(indexFile.path, "a", completions => assert(completions.isIncomplete))
.backspace()
.type("a", completions => assert(!completions.isIncomplete));
});
it("ambient module specifier resolutions do not count against the resolution limit", () => {
const ambientFiles = fill(100, (i): File => ({
path: `/lib/ambient_${i}.ts`,
content: `declare module "ambient_${i}" { export const aa_${i} = ${i}; }`,
}));
const exportingFiles = createExportingModuleFiles(`/lib/a`, Completions.moduleSpecifierResolutionLimit, 5, i => `aa_${i}_`);
const { typeToTriggerCompletions, session } = setup([tsconfigFile, indexFile, ...ambientFiles, ...exportingFiles]);
openFilesForSession([indexFile], session);
typeToTriggerCompletions(indexFile.path, "a", completions => {
assert(!completions.isIncomplete);
assert.lengthOf(completions.entries.filter(e => (e.data as any)?.moduleSpecifier), ambientFiles.length * 5 + exportingFiles.length);
});
});
it("works with PackageJsonAutoImportProvider", () => {
const exportingFiles = createExportingModuleFiles(`/lib/a`, Completions.moduleSpecifierResolutionLimit, 1, i => `aa_${i}_`);
const nodeModulesPackage = createNodeModulesPackage("dep-a", 50, 1, i => `depA_${i}_`);
const { typeToTriggerCompletions, assertCompletionDetailsOk, session } = setup([tsconfigFile, packageJsonFile, indexFile, ...exportingFiles, ...nodeModulesPackage]);
openFilesForSession([indexFile], session);
typeToTriggerCompletions(indexFile.path, "a", completions => assert(completions.isIncomplete))
.continueTyping("_", completions => {
assert(!completions.isIncomplete);
assert.lengthOf(completions.entries.filter(entry => (entry.data as any)?.moduleSpecifier?.startsWith("dep-a")), 50);
assertCompletionDetailsOk(
indexFile.path,
completions.entries.find(entry => (entry.data as any)?.moduleSpecifier?.startsWith("dep-a"))!);
});
});
it("works for transient symbols between requests", () => {
const constantsDts: File = {
path: "/lib/foo/constants.d.ts",
content: `
type Signals = "SIGINT" | "SIGABRT";
declare const exp: {} & { [K in Signals]: K };
export = exp;`,
};
const exportingFiles = createExportingModuleFiles("/lib/a", Completions.moduleSpecifierResolutionLimit, 1, i => `S${i}`);
const { typeToTriggerCompletions, session } = setup([tsconfigFile, indexFile, ...exportingFiles, constantsDts]);
openFilesForSession([indexFile], session);
typeToTriggerCompletions(indexFile.path, "s", completions => {
const sigint = completions.entries.find(e => e.name === "SIGINT");
assert(sigint);
assert(!(sigint.data as any).moduleSpecifier);
})
.continueTyping("i", completions => {
const sigint = completions.entries.find(e => e.name === "SIGINT");
assert((sigint!.data as any).moduleSpecifier);
});
});
});
function setup(files: File[]) {
const host = createServerHost(files);
const session = createSession(host);
const projectService = session.getProjectService();
session.executeCommandSeq<protocol.ConfigureRequest>({
command: protocol.CommandTypes.Configure,
arguments: {
preferences: {
allowIncompleteCompletions: true,
includeCompletionsForModuleExports: true,
includeCompletionsWithInsertText: true,
includeCompletionsForImportStatements: true,
includePackageJsonAutoImports: "auto",
}
}
});
return { host, session, projectService, typeToTriggerCompletions, assertCompletionDetailsOk };
function typeToTriggerCompletions(fileName: string, typedCharacters: string, cb?: (completions: protocol.CompletionInfo) => void) {
const project = projectService.getDefaultProjectForFile(server.toNormalizedPath(fileName), /*ensureProject*/ true)!;
return type(typedCharacters, cb, /*isIncompleteContinuation*/ false);
function type(typedCharacters: string, cb: ((completions: protocol.CompletionInfo) => void) | undefined, isIncompleteContinuation: boolean) {
const file = Debug.checkDefined(project.getLanguageService(/*ensureSynchronized*/ true).getProgram()?.getSourceFile(fileName));
const { line, character } = getLineAndCharacterOfPosition(file, file.text.length);
const oneBasedEditPosition = { line: line + 1, offset: character + 1 };
session.executeCommandSeq<protocol.UpdateOpenRequest>({
command: protocol.CommandTypes.UpdateOpen,
arguments: {
changedFiles: [{
fileName,
textChanges: [{
newText: typedCharacters,
start: oneBasedEditPosition,
end: oneBasedEditPosition,
}],
}],
},
});
const response = session.executeCommandSeq<protocol.CompletionsRequest>({
command: protocol.CommandTypes.CompletionInfo,
arguments: {
file: fileName,
line: oneBasedEditPosition.line,
offset: oneBasedEditPosition.offset,
triggerKind: isIncompleteContinuation
? protocol.CompletionTriggerKind.TriggerForIncompleteCompletions
: undefined,
}
}).response as protocol.CompletionInfo;
cb?.(Debug.checkDefined(response));
return {
backspace,
continueTyping: (typedCharacters: string, cb: (completions: protocol.CompletionInfo) => void) => {
return type(typedCharacters, cb, !!response.isIncomplete);
},
};
}
function backspace(n = 1) {
const file = Debug.checkDefined(project.getLanguageService(/*ensureSynchronized*/ true).getProgram()?.getSourceFile(fileName));
const startLineCharacter = getLineAndCharacterOfPosition(file, file.text.length - n);
const endLineCharacter = getLineAndCharacterOfPosition(file, file.text.length);
const oneBasedStartPosition = { line: startLineCharacter.line + 1, offset: startLineCharacter.character + 1 };
const oneBasedEndPosition = { line: endLineCharacter.line + 1, offset: endLineCharacter.character + 1 };
session.executeCommandSeq<protocol.UpdateOpenRequest>({
command: protocol.CommandTypes.UpdateOpen,
arguments: {
changedFiles: [{
fileName,
textChanges: [{
newText: "",
start: oneBasedStartPosition,
end: oneBasedEndPosition,
}],
}],
},
});
return {
backspace,
type: (typedCharacters: string, cb: (completions: protocol.CompletionInfo) => void) => {
return type(typedCharacters, cb, /*isIncompleteContinuation*/ false);
},
};
}
}
function assertCompletionDetailsOk(fileName: string, entry: protocol.CompletionEntry) {
const project = projectService.getDefaultProjectForFile(server.toNormalizedPath(fileName), /*ensureProject*/ true)!;
const file = Debug.checkDefined(project.getLanguageService(/*ensureSynchronized*/ true).getProgram()?.getSourceFile(fileName));
const { line, character } = getLineAndCharacterOfPosition(file, file.text.length - 1);
const details = session.executeCommandSeq<protocol.CompletionDetailsRequest>({
command: protocol.CommandTypes.CompletionDetails,
arguments: {
file: fileName,
line: line + 1,
offset: character + 1,
entryNames: [{
name: entry.name,
source: entry.source,
data: entry.data,
}]
}
}).response as protocol.CompletionEntryDetails[];
assert(details[0]);
assert(details[0].codeActions);
assert(details[0].codeActions[0].changes[0].textChanges[0].newText.includes(`"${(entry.data as any).moduleSpecifier}"`));
return details;
}
}
} | the_stack |
declare module "qdtNova" {
function _default(supernova: any): (Component: any, options: any) => () => {
component(): void;
};
export default _default;
}
declare module "components/QdtModal/QdtModalStyles" {
export default styles;
function styles(theme: any): {
modalContainer: {
position: string;
width: string;
maxWidth: number;
backgroundColor: any;
border: string;
boxShadow: any;
padding: number;
top: string;
left: string;
transform: string;
};
modalHeader: {
padding: number;
fontSize: string;
fontWeight: number;
backgroundColor: any;
width: string;
position: string;
};
modalBody: {
padding: number;
width: string;
position: string;
};
modalFooter: {
padding: number;
borderTop: string;
backgroundColor: any;
textAlign: string;
position: string;
width: string;
};
};
}
declare module "components/QdtModal/QdtModal" {
export default QdtModal;
function QdtModal({ open, header, body, footer, handleClose, }: {
open: any;
header: any;
body: any;
footer: any;
handleClose: any;
}): JSX.Element;
namespace QdtModal {
export namespace propTypes {
export const open: PropTypes.Validator<boolean>;
export const handleClose: PropTypes.Requireable<(...args: any[]) => any>;
export const header: PropTypes.Requireable<string>;
export const body: PropTypes.Requireable<string>;
export const footer: PropTypes.Requireable<PropTypes.ReactElementLike>;
}
export namespace defaultProps {
const handleClose_1: null;
export { handleClose_1 as handleClose };
const header_1: null;
export { header_1 as header };
const body_1: null;
export { body_1 as body };
const footer_1: null;
export { footer_1 as footer };
}
}
import PropTypes from "prop-types";
}
declare module "utils/ConnectionLost" {
function _default({ refreshUrl, timeoutMessage }: {
refreshUrl: any;
timeoutMessage: any;
}): void;
export default _default;
}
declare module "qdtEnigma" {
export default qdtEnigma;
function qdtEnigma(config: any): Promise<any>;
}
declare module "qdtCapabilityApp" {
export default qApp;
function qApp(config: any): Promise<any>;
}
declare module "hooks/useSessionObject" {
export default useSessionObject;
function useSessionObject({ app, properties: propertiesProp, onLayoutChange }: {
app: any;
properties: any;
onLayoutChange: any;
}): {
model: null;
layout: null;
};
}
declare module "components/QdtComponent/QdtComponent" {
export default QdtComponent;
const QdtComponent: React.ForwardRefExoticComponent<React.RefAttributes<any>>;
import React from "react";
}
declare module "components/QdtExtension/QdtExtension" {
export default QdtExtension;
const QdtExtension: React.ForwardRefExoticComponent<React.RefAttributes<any>>;
import React from "react";
}
declare module "qdtCompose" {
function _default({ element, theme: themeProp, component: componentProp, options: optionsProp, app: appProp, model: modelProp, layout: layoutProp, properties: propertiesProp, loading: loadingProp, onLayoutChange: onLayoutChangeProp }: {
element: any;
theme?: any;
component: any;
options?: any;
app: any;
model?: any;
layout?: any;
properties?: any;
loading?: any;
onLayoutChange?: any;
}): void;
export default _default;
}
declare module "qdtCompose2" {
function _default({ element, theme: themeProp, component: componentProp, options: optionsProp, app: appProp, model: modelProp, layout: layoutProp, properties: propertiesProp, loading: loadingProp, onLayoutChange: onLayoutChangeProp, }: {
element: any;
theme: any;
component: any;
options: any;
app: any;
model: any;
layout: any;
properties: any;
loading: any;
onLayoutChange: any;
}): {
element: any;
theme: import("@material-ui/core").Theme;
update: ({ theme: updatedThemeProp, component: updatedComponentProp, options: updatedOptionsProp, app: updatedAppProp, properties: updatedPropertiesProp, loading: updatedLoadingProp, onLayoutChange: updatedOnLayoutChangeProp, }: {
theme: any;
component: any;
options: any;
app: any;
properties: any;
loading: any;
onLayoutChange: any;
}) => void;
clear: () => void;
destroy: () => void;
componentRef: React.RefObject<any>;
modelRef: React.RefObject<any>;
layoutRef: React.RefObject<any>;
};
export default _default;
import React from "react";
}
declare module "hooks/useThree" {
export default useThree;
function useThree({ layout, options }: {
layout: any;
options: any;
}): {
scene: any;
layout: any;
createBar: ({ posx, posz, posy, width, height, depth, order, maxBarΝumberFromData, color, }: {
posx?: number | undefined;
posz?: number | undefined;
posy?: number | undefined;
width?: number | undefined;
height?: number | undefined;
depth?: number | undefined;
order?: number | undefined;
maxBarΝumberFromData?: number | undefined;
color?: number | undefined;
}) => Promise<any>;
minimizeBars: () => void;
raiseBars: () => void;
renderScene: (mapboxgl: any, matrix: any) => void;
createGroundPlane: () => void;
finalRender: () => void;
};
}
declare module "components/QdtButton/QdtButton" {
export default QdtButton;
function QdtButton({ app, options: optionsProp, }: {
app: any;
options: any;
}): JSX.Element;
namespace QdtButton {
export namespace propTypes {
export const app: PropTypes.Validator<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtKpi/QdtKpi" {
export default QdtKpi;
function QdtKpi({ layout, options: optionsProp }: {
layout: any;
options: any;
}): JSX.Element;
namespace QdtKpi {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtSelect/QdtSelect" {
export default QdtSelect;
function QdtSelect({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtSelect {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtSelect/QdtSelectSimple" {
export default QdtSelect;
function QdtSelect({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtSelect {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtList/QdtList" {
export default QdtList;
function QdtList({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtList {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtTable/QdtTable" {
export default QdtTable;
function QdtTable({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtTable {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtSequencer/QdtSequencer" {
export default QdtSequencer;
function QdtSequencer({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtSequencer {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtSlider/QdtSlider" {
export default QdtSlider;
function QdtSlider({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtSlider {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "styles/index" {
export default theme;
namespace theme {
export { palette };
export const primary: string;
export const primaryLight: string;
export const secondary: string;
export const secondaryLight: string;
export const tertiary: string;
export const tertiaryLight: string;
export const quaternary: {};
export const quinary: {};
export const senary: {};
}
const palette: string[];
}
declare module "components/QdtMapbox/QdtMapBox" {
export default QdtMapBox;
function QdtMapBox({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtMapBox {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtSelections/QdtSelectionsStyles" {
export default useStyles;
const useStyles: (props?: any) => Record<"icon" | "selected" | "container" | "field" | "menuList" | "primaryGrid" | "buttonGroup" | "selectedItemButton" | "linearProgressRoot" | "linearProgressBar", string>;
}
declare module "components/QdtSelections/QdtPopperContents" {
export default QdtSelectionsPopper;
function QdtSelectionsPopper({ open, qField, app }: {
open: any;
qField: any;
app: any;
}): JSX.Element;
namespace QdtSelectionsPopper {
export namespace propTypes {
export const open: PropTypes.Validator<boolean>;
export const app: PropTypes.Validator<object>;
export const qField: PropTypes.Requireable<string>;
}
export namespace defaultProps {
const qField_1: null;
export { qField_1 as qField };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtPopper/QdtPopperStyles" {
export default useStyles;
const useStyles: (props?: any) => Record<"popper" | "popperPaper", string>;
}
declare module "components/QdtPopper/QdtPopper" {
export default QdtPopper;
function QdtPopper({ open, anchorEl, contents, onCallback, }: {
open: any;
anchorEl: any;
contents: any;
onCallback: any;
}): JSX.Element;
namespace QdtPopper {
export namespace propTypes {
export const open: PropTypes.Validator<boolean>;
export const anchorEl: PropTypes.Validator<object>;
export const contents: PropTypes.Requireable<(...args: any[]) => any>;
export const onCallback: PropTypes.Requireable<(...args: any[]) => any>;
}
export namespace defaultProps {
const onCallback_1: null;
export { onCallback_1 as onCallback };
const contents_1: null;
export { contents_1 as contents };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtSelections/QdtSelections" {
export default QdtSelections;
function QdtSelections({ layout, app }: {
layout: any;
app: any;
}): JSX.Element;
namespace QdtSelections {
export namespace propTypes {
export const layout: PropTypes.Validator<object>;
export const app: PropTypes.Validator<object>;
}
export const defaultProps: {};
}
import PropTypes from "prop-types";
}
declare module "components/QdtSearch/QdtPopperContents" {
export default QdtPopperContents;
function QdtPopperContents({ open, layout, model, options, handleClose, }: {
open: any;
layout: any;
model: any;
options: any;
handleClose: any;
}): JSX.Element;
namespace QdtPopperContents {
export namespace propTypes {
export const open: PropTypes.Validator<boolean>;
export const layout: PropTypes.Validator<object>;
export const model: PropTypes.Validator<object>;
export const options: PropTypes.Validator<object>;
export const handleClose: PropTypes.Validator<(...args: any[]) => any>;
}
export const defaultProps: {};
}
import PropTypes from "prop-types";
}
declare module "components/QdtSearch/QdtSearchStyles" {
export default styles;
namespace styles {
export namespace alignMiddle {
export const display: string;
export const alignItems: string;
}
}
}
declare module "components/QdtSearch/QdtSearch" {
export default QdtSearch;
function QdtSearch({ layout, model, options: optionsProp }: {
layout: any;
model: any;
options: any;
}): JSX.Element;
namespace QdtSearch {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
export const model: PropTypes.Requireable<object>;
export const options: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
const model_1: null;
export { model_1 as model };
const options_1: {};
export { options_1 as options };
}
}
import PropTypes from "prop-types";
}
declare module "components/QdtThree/QdtThree" {
export default QdtThree;
function QdtThree({ layout }: {
layout: any;
}): JSX.Element;
namespace QdtThree {
export namespace propTypes {
export const layout: PropTypes.Requireable<object>;
}
export namespace defaultProps {
const layout_1: null;
export { layout_1 as layout };
}
}
import PropTypes from "prop-types";
}
declare module "utils/merge" {
export default merge;
function merge(x: any, y: any): any;
namespace merge {
export function all(arr: any): object;
}
}
declare module "components/QdtModal/QdtSelectionModal" {
export default QdtSelectionModal;
function QdtSelectionModal({ isOpen, onCancelSelections, onConfirmSelections, }: {
isOpen: any;
onCancelSelections: any;
onConfirmSelections: any;
}): JSX.Element;
namespace QdtSelectionModal {
export namespace propTypes {
export const isOpen: PropTypes.Validator<boolean>;
export const onCancelSelections: PropTypes.Validator<(...args: any[]) => any>;
export const onConfirmSelections: PropTypes.Validator<(...args: any[]) => any>;
}
export const defaultProps: {};
}
import PropTypes from "prop-types";
}
declare module "components/QdtPicasso/components/domPointLabel" {
var _default: {
require: string[];
renderer: string;
defaultSettings: {
settings: {};
};
beforeRender(options: any): void;
generatePoints(data: any): any;
render(h: any, { data }: {
data: any;
}): any;
};
export default _default;
}
declare module "components/QdtPicasso/components/domPointImage" {
var _default: {
require: string[];
renderer: string;
defaultSettings: {
settings: {};
};
beforeRender(options: any): void;
generatePoints(data: any): any;
render(h: any, { data }: {
data: any;
}): any;
};
export default _default;
}
declare module "components/QdtPicasso/components/treemap" {
var _default: {
require: string[];
defaultSettings: {
settings: {};
data: {};
};
render({ data }: {
data: any;
}): any;
};
export default _default;
}
declare module "components/QdtPicasso/QdtPicasso" {
export default QdtPicasso;
const QdtPicasso: React.ForwardRefExoticComponent<React.RefAttributes<any>>;
import React from "react";
}
declare module "components/QdtPicasso/settings/components/axis" {
export default axis;
function axis({ theme: themeProp, properties: propertiesProp, scale, formatter, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
scale?: string | undefined;
formatter?: any;
}): any;
}
declare module "components/QdtPicasso/settings/components/box" {
export default box;
function box({ theme: themeProp, properties: propertiesProp, orientation, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
orientation?: string | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/point" {
export default point;
function point({ theme: themeProp, properties: propertiesProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/lineArea" {
export default lineArea;
function lineArea({ theme: themeProp, properties: propertiesProp, showLine, showArea, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
showLine?: boolean | undefined;
showArea?: boolean | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/grid" {
export default grid;
function grid({ theme: themeProp, properties: propertiesProp, x, y, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
x?: boolean | undefined;
y?: boolean | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/labels" {
export default labels;
function labels({ theme: themeProp, properties: propertiesProp, type, component, orientation, format: formatSpec, labels: labelsProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
type?: string | undefined;
component?: string | undefined;
orientation?: string | undefined;
format?: string | undefined;
labels?: any;
}): any;
}
declare module "components/QdtPicasso/settings/components/range" {
export default range;
function range({ theme: themeProp, properties: propertiesProp, scale, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
scale?: string | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/tooltip" {
export default tooltip;
function tooltip({ theme: themeProp, properties: propertiesProp, format: formatSpec, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
format?: string | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/legend" {
export default legend;
function legend({ theme: themeProp, properties: propertiesProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/index" {
namespace _default {
export { axis };
export { box };
export { point };
export { lineArea };
export { grid };
export { labels };
export { range };
export { tooltip };
export { legend };
}
export default _default;
import axis from "components/QdtPicasso/settings/components/axis";
import box from "components/QdtPicasso/settings/components/box";
import point from "components/QdtPicasso/settings/components/point";
import lineArea from "components/QdtPicasso/settings/components/lineArea";
import grid from "components/QdtPicasso/settings/components/grid";
import labels from "components/QdtPicasso/settings/components/labels";
import range from "components/QdtPicasso/settings/components/range";
import tooltip from "components/QdtPicasso/settings/components/tooltip";
import legend from "components/QdtPicasso/settings/components/legend";
}
declare module "components/QdtViz/QdtViz" {
function _default({ element, app, options }: {
element: any;
app: any;
options: any;
}): void;
export default _default;
}
declare module "components/QdtPicasso/settings/interactions/rangePan" {
export default rangePan;
function rangePan({ properties: propertiesProp, scale, }?: {
properties?: {} | undefined;
scale?: string | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/interactions/tooltipHover" {
export default tooltipHover;
function tooltipHover({ properties: propertiesProp, }?: {
properties?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/utils/formatters" {
export {};
}
declare module "components/QdtPicasso/settings/barchart" {
export default BarChart;
function BarChart({ theme: themeProp, properties: propertiesProp, orientation, type, xAxis: xAxisProp, yAxis: yAxisProp, grid: gridProp, box: boxProp, labels: labelsProp, legend: legendProp, range: rangeProp, tooltip: tooltipProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
orientation?: string | undefined;
type?: string | undefined;
xAxis?: {} | undefined;
yAxis?: {} | undefined;
grid?: {} | undefined;
box?: {} | undefined;
labels?: {} | undefined;
legend?: {} | undefined;
range?: {} | undefined;
tooltip?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/lineChart" {
export default lineChart;
function lineChart({ theme: themeProp, properties: propertiesProp, type, showArea, xAxis: xAxisProp, yAxis: yAxisProp, grid: gridProp, lineArea: lineAreaProp, point: pointProp, range: rangeProp, tooltip: tooltipProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
type?: string | undefined;
showArea?: boolean | undefined;
xAxis?: {} | undefined;
yAxis?: {} | undefined;
grid?: {} | undefined;
lineArea?: {} | undefined;
point?: {} | undefined;
range?: {} | undefined;
tooltip?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/components/pie" {
export default pie;
function pie({ theme: themeProp, properties: propertiesProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/pieChart" {
export default pieChart;
function pieChart(): {
scales: {
c: {
data: {
extract: {
field: string;
};
};
type: string;
};
};
components: any[];
interactions: any[];
};
}
declare module "components/QdtPicasso/settings/components/domPointLabel" {
export default domPointLabel;
function domPointLabel({ theme: themeProp, properties: propertiesProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/interactions/legendClick" {
export default legendClick;
function legendClick({ properties: propertiesProp, }?: {
properties?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/scatterPlot" {
export default ScatterPlot;
function ScatterPlot({ theme: themeProp, properties: propertiesProp, point: pointProp, pointImage: pointImageProp, labels: labelsProp, legend: legendProp, tooltip: tooltipProp, range: rangeProp, xAxis: xAxisProp, yAxis: yAxisProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
point?: {} | undefined;
pointImage?: any;
labels?: {} | undefined;
legend?: {} | undefined;
tooltip?: {} | undefined;
range?: {} | undefined;
xAxis?: {} | undefined;
yAxis?: {} | undefined;
}): any;
}
declare module "components/QdtPicasso/settings/merimekko" {
export default MerimekkoChart;
function MerimekkoChart({ theme: themeProp, }?: {
theme?: {} | undefined;
}): {
collections: ({
key: string;
data: {
extract: {
field: string;
props: {
series: {
field: string;
};
metric: {
field: string;
reduce: string;
};
end: {
field: string;
reduce: string;
};
};
trackBy?: undefined;
reduce?: undefined;
};
stack: {
stackKey: (d: any) => any;
value: (d: any) => any;
offset: string;
};
};
} | {
key: string;
data: {
extract: {
field: string;
trackBy: (d: any) => any;
reduce: string;
props: {
series: {
field: string;
};
metric: {
field: string;
reduce?: undefined;
};
end: {
field: string;
reduce?: undefined;
};
};
};
stack: {
stackKey: () => number;
value: (d: any) => any;
offset: string;
};
};
})[];
scales: {
y: {
data: {
collection: {
key: string;
};
};
invert: boolean;
};
b: {
data: {
collection: {
key: string;
};
};
type: string;
};
x: {
data: {
collection: {
key: string;
};
};
max: number;
};
c: {
data: {
extract: {
field: string;
};
};
range: any;
type: string;
};
};
components: any[];
interactions: any[];
};
}
declare module "components/QdtPicasso/settings/treemap" {
export default Treemap;
function Treemap({ theme: themeProp, properties: propertiesProp, tooltip: tooltipProp, }?: {
theme?: {} | undefined;
properties?: {} | undefined;
tooltip?: {} | undefined;
}): any;
}
declare module "qdt-components" {
// export * from "qdtNova";
// export * from "qdtEnigma";
// export * from "qdtCapabilityApp";
// export * from "qdtCompose";
// export * from "hooks/useThree";
// export * from "components/QdtButton/QdtButton";
// export * from "components/QdtKpi/QdtKpi";
// export * from "components/QdtSelect/QdtSelect";
// export * from "components/QdtSelect/QdtSelectSimple";
// export * from "components/QdtList/QdtList";
// export * from "components/QdtTable/QdtTable";
// export * from "components/QdtSequencer/QdtSequencer";
// export * from "components/QdtSlider/QdtSlider";
// export * from "components/QdtMapbox/QdtMapBox";
// export * from "components/QdtSelections/QdtSelections";
// export * from "components/QdtSearch/QdtSearch";
// export * from "components/QdtThree/QdtThree";
// export * from "components/QdtPicasso/QdtPicasso";
// // export * from "components/QdtPicasso/settings/components";
// export * from "components/QdtViz/QdtViz";
// export * from "hooks/useSessionObject";
// export * from "components/QdtPicasso/settings/barchart";
// export * from "components/QdtPicasso/settings/lineChart";
// export * from "components/QdtPicasso/settings/pieChart";
// export * from "components/QdtPicasso/settings/scatterPlot";
// export * from "components/QdtPicasso/settings/merimekko";
// export * from "components/QdtPicasso/settings/treemap";
export { default as qdtNova } from "qdtNova";
export { default as qdtEnigma } from "qdtEnigma";
export { default as qdtCapabilityApp } from "qdtCapabilityApp";
export { default as qdtCompose } from "qdtCompose";
export { default as useThree } from "hooks/useThree";
export { default as QdtButton } from "components/QdtButton/QdtButton";
export { default as QdtKpi } from "components/QdtKpi/QdtKpi";
export { default as QdtSelect } from "components/QdtSelect/QdtSelect";
export { default as QdtSelectSimple } from "components/QdtSelect/QdtSelectSimple";
export { default as QdtList } from "components/QdtList/QdtList";
export { default as QdtTable } from "components/QdtTable/QdtTable";
export { default as QdtSequencer } from "components/QdtSequencer/QdtSequencer";
export { default as QdtSlider } from "components/QdtSlider/QdtSlider";
export { default as QdtMapBox } from "components/QdtMapbox/QdtMapBox";
export { default as QdtSelections } from "components/QdtSelections/QdtSelections";
export { default as QdtSearch } from "components/QdtSearch/QdtSearch";
export { default as QdtThree } from "components/QdtThree/QdtThree";
export { default as QdtPicasso } from "components/QdtPicasso/QdtPicasso";
export { default as QdtPicassoComponents } from "components/QdtPicasso/settings/components/index";
export { default as QdtViz } from "components/QdtViz/QdtViz";
export { default as useSessionObject } from "hooks/useSessionObject";
export { default as useBarChartSettings } from "components/QdtPicasso/settings/barchart";
export { default as useLineChartSettings } from "components/QdtPicasso/settings/lineChart";
export { default as usePieChartSettings } from "components/QdtPicasso/settings/pieChart";
export { default as useScatterPlotSettings } from "components/QdtPicasso/settings/scatterPlot";
export { default as useMerimekkoSettings } from "components/QdtPicasso/settings/merimekko";
export { default as useTreemapSettings } from "components/QdtPicasso/settings/treemap";
// export { default as qdtNova } from "./qdtNova";
// export { default as qdtEnigma } from "./qdtEnigma";
// export { default as qdtCapabilityApp } from "./qdtCapabilityApp";
// export { default as qdtCompose } from "./qdtCompose";
// export { default as useThree } from "./hooks/useThree";
// export { default as QdtButton } from "./components/QdtButton/QdtButton";
// export { default as QdtKpi } from "./components/QdtKpi/QdtKpi";
// export { default as QdtSelect } from "./components/QdtSelect/QdtSelect";
// export { default as QdtSelectSimple } from "./components/QdtSelect/QdtSelectSimple";
// export { default as QdtList } from "./components/QdtList/QdtList";
// export { default as QdtTable } from "./components/QdtTable/QdtTable";
// export { default as QdtSequencer } from "./components/QdtSequencer/QdtSequencer";
// export { default as QdtSlider } from "./components/QdtSlider/QdtSlider";
// export { default as QdtMapBox } from "./components/QdtMapbox/QdtMapBox";
// export { default as QdtSelections } from "./components/QdtSelections/QdtSelections";
// export { default as QdtSearch } from "./components/QdtSearch/QdtSearch";
// export { default as QdtThree } from "./components/QdtThree/QdtThree";
// export { default as QdtPicasso } from "./components/QdtPicasso/QdtPicasso";
// export { default as QdtPicassoComponents } from "./components/QdtPicasso/settings/components";
// export { default as QdtViz } from "./components/QdtViz/QdtViz";
// export { default as useSessionObject } from "./hooks/useSessionObject";
// export { default as useBarChartSettings } from "./components/QdtPicasso/settings/barchart";
// export { default as useLineChartSettings } from "./components/QdtPicasso/settings/lineChart";
// export { default as usePieChartSettings } from "./components/QdtPicasso/settings/pieChart";
// export { default as useScatterPlotSettings } from "./components/QdtPicasso/settings/scatterPlot";
// export { default as useMerimekkoSettings } from "./components/QdtPicasso/settings/merimekko";
// export { default as useTreemapSettings } from "./components/QdtPicasso/settings/treemap";
} | the_stack |
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import {
Address,
B2BApprovalProcess,
B2BUnit,
B2BUser,
CostCenter,
EntitiesModel,
SearchConfig,
StateUtils,
StateWithProcess,
UserIdService,
} from '@spartacus/core';
import { Observable, queueScheduler, using } from 'rxjs';
import { auditTime, filter, map, observeOn, tap } from 'rxjs/operators';
import { OrganizationItemStatus } from '../model/organization-item-status';
import { B2BUnitNode } from '../model/unit-node.model';
import { OrgUnitActions } from '../store/actions/index';
import { StateWithOrganization } from '../store/organization-state';
import {
getApprovalProcesses,
getAssignedUsers,
getB2BAddress,
getB2BAddresses,
getOrgUnit,
getOrgUnitList,
getOrgUnitState,
getOrgUnitTree,
getOrgUnitValue,
} from '../store/selectors/org-unit.selector';
import { getItemStatus } from '../utils/get-item-status';
@Injectable({ providedIn: 'root' })
export class OrgUnitService {
constructor(
protected store: Store<StateWithOrganization | StateWithProcess<void>>,
protected userIdService: UserIdService
) {}
clearAssignedUsersList(
orgUnitId: string,
roleId: string,
params: SearchConfig
): void {
this.store.dispatch(
new OrgUnitActions.ClearAssignedUsers({ orgUnitId, roleId, params })
);
}
load(orgUnitId: string): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.LoadOrgUnit({ userId, orgUnitId })
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
loadList(): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(new OrgUnitActions.LoadOrgUnitNodes({ userId })),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
loadTree(): void {
this.userIdService.takeUserId(true).subscribe(
(userId) => this.store.dispatch(new OrgUnitActions.LoadTree({ userId })),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
loadApprovalProcesses(): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.LoadApprovalProcesses({ userId })
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
loadUsers(orgUnitId: string, roleId: string, params: SearchConfig): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.LoadAssignedUsers({
userId,
orgUnitId,
roleId,
params,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
loadAddresses(orgUnitId: string): void {
// TODO: replace it after turn on loadAddresses$
// this.store.dispatch(
// new OrgUnitActions.LoadAddresses({ userId, orgUnitId })
// );
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.LoadOrgUnit({ userId, orgUnitId })
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
private getOrgUnit(
orgUnitId: string
): Observable<StateUtils.LoaderState<B2BUnit>> {
return this.store.select(getOrgUnit(orgUnitId));
}
private getOrgUnitValue(orgUnitId: string): Observable<B2BUnit> {
return this.store.select(getOrgUnitValue(orgUnitId)).pipe(filter(Boolean));
}
private getTreeState(): Observable<StateUtils.LoaderState<B2BUnitNode>> {
return this.store.select(getOrgUnitTree());
}
private getOrgUnitsList(): Observable<StateUtils.LoaderState<B2BUnitNode[]>> {
return this.store.select(getOrgUnitList());
}
private getAddressesState(
orgUnitId: string
): Observable<StateUtils.LoaderState<EntitiesModel<Address>>> {
return this.store.select(getB2BAddresses(orgUnitId, null));
}
private getAddressState(
addressId: string
): Observable<StateUtils.LoaderState<Address>> {
return this.store.select(getB2BAddress(addressId));
}
private getAssignedUsers(
orgUnitId: string,
roleId: string,
params: SearchConfig
): Observable<StateUtils.LoaderState<EntitiesModel<B2BUser>>> {
return this.store.select(getAssignedUsers(orgUnitId, roleId, params));
}
private getApprovalProcessesList(): Observable<
StateUtils.LoaderState<B2BApprovalProcess[]>
> {
return this.store.select(getApprovalProcesses());
}
get(orgUnitId: string): Observable<B2BUnit> {
const loading$ = this.getOrgUnit(orgUnitId).pipe(
auditTime(0),
tap((state) => {
if (!(state.loading || state.success || state.error)) {
this.load(orgUnitId);
}
})
);
return using(
() => loading$.subscribe(),
() => this.getOrgUnitValue(orgUnitId)
);
}
getCostCenters(orgUnitId: string): Observable<EntitiesModel<CostCenter>> {
return this.get(orgUnitId).pipe(
map((orgUnit) => ({
values: orgUnit.costCenters ?? [],
}))
);
}
protected findUnitChildrenInTree(
orginitId,
unit: B2BUnitNode
): B2BUnitNode[] {
return unit.id === orginitId
? unit.children
: unit.children.flatMap((child) =>
this.findUnitChildrenInTree(orginitId, child)
);
}
getChildUnits(orgUnitId: string): Observable<EntitiesModel<B2BUnitNode>> {
return this.getTree().pipe(
map((tree) => ({
values: this.findUnitChildrenInTree(orgUnitId, tree),
}))
);
}
getTree(): Observable<B2BUnitNode> {
return this.getTreeState().pipe(
observeOn(queueScheduler),
tap((process: StateUtils.LoaderState<B2BUnitNode>) => {
if (!(process.loading || process.success || process.error)) {
this.loadTree();
}
}),
filter(
(process: StateUtils.LoaderState<B2BUnitNode>) =>
process.success || process.error
),
map((result) => result.value)
);
}
getApprovalProcesses(): Observable<B2BApprovalProcess[]> {
return this.getApprovalProcessesList().pipe(
observeOn(queueScheduler),
tap((process: StateUtils.LoaderState<B2BApprovalProcess[]>) => {
if (!(process.loading || process.success || process.error)) {
this.loadApprovalProcesses();
}
}),
filter(
(process: StateUtils.LoaderState<B2BApprovalProcess[]>) =>
process.success || process.error
),
map((result) => result.value)
);
}
getList(): Observable<B2BUnitNode[]> {
return this.getOrgUnitsList().pipe(
observeOn(queueScheduler),
tap((process: StateUtils.LoaderState<B2BUnitNode[]>) => {
if (!(process.loading || process.success || process.error)) {
this.loadList();
}
}),
filter(
(process: StateUtils.LoaderState<B2BUnitNode[]>) =>
process.success || process.error
),
map((result) => result.value)
);
}
getActiveUnitList(): Observable<B2BUnitNode[]> {
return this.getList().pipe(
map((units) => units.filter((unit) => unit.active)),
map((units) => units.sort(this.sortUnitList))
);
}
protected sortUnitList(a: B2BUnitNode, b: B2BUnitNode) {
return a.id.toLowerCase() < b.id.toLowerCase()
? -1
: a.id.toLowerCase() > b.id.toLowerCase()
? 1
: 0;
}
getUsers(
orgUnitId: string,
roleId: string,
params: SearchConfig
): Observable<EntitiesModel<B2BUser>> {
return this.getAssignedUsers(orgUnitId, roleId, params).pipe(
observeOn(queueScheduler),
tap((process: StateUtils.LoaderState<EntitiesModel<B2BUser>>) => {
if (!(process.loading || process.success || process.error)) {
this.loadUsers(orgUnitId, roleId, params);
}
}),
filter(
(process: StateUtils.LoaderState<EntitiesModel<B2BUser>>) =>
process.success || process.error
),
map((result) => result.value)
);
}
getErrorState(orgCustomerId): Observable<boolean> {
return this.getOrgUnitState(orgCustomerId).pipe(
map((state) => state.error)
);
}
create(unit: B2BUnit): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(new OrgUnitActions.CreateUnit({ userId, unit })),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
update(unitCode: string, unit: B2BUnit): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.UpdateUnit({ userId, unitCode, unit })
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
getLoadingStatus(
orgUnitId: string
): Observable<OrganizationItemStatus<B2BUnit>> {
return getItemStatus(this.getOrgUnit(orgUnitId));
}
assignRole(orgCustomerId: string, roleId: string): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.AssignRole({
userId,
orgCustomerId,
roleId,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
unassignRole(orgCustomerId: string, roleId: string): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.UnassignRole({
userId,
orgCustomerId,
roleId,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
assignApprover(
orgUnitId: string,
orgCustomerId: string,
roleId: string
): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.AssignApprover({
orgUnitId,
userId,
orgCustomerId,
roleId,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
unassignApprover(
orgUnitId: string,
orgCustomerId: string,
roleId: string
): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.UnassignApprover({
orgUnitId,
userId,
orgCustomerId,
roleId,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
createAddress(orgUnitId: string, address: Address): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.CreateAddress({
userId,
orgUnitId,
address,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
getAddresses(orgUnitId: string): Observable<EntitiesModel<Address>> {
return this.getAddressesState(orgUnitId).pipe(
observeOn(queueScheduler),
tap((state) => {
if (!(state.loading || state.success || state.error)) {
this.loadAddresses(orgUnitId);
}
}),
filter((state) => state.success || state.error),
map((state) => state.value)
);
}
getAddress(orgUnitId: string, addressId: string): Observable<Address> {
return this.getAddressState(addressId).pipe(
observeOn(queueScheduler),
tap((state) => {
if (!(state.loading || state.success || state.error)) {
this.loadAddresses(orgUnitId);
}
}),
filter((state) => state.success || state.error),
map((state) => state.value)
);
}
updateAddress(orgUnitId: string, addressId: string, address: Address): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.UpdateAddress({
userId,
orgUnitId,
addressId,
address,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
getAddressLoadingStatus(
addressId: string
): Observable<OrganizationItemStatus<Address>> {
return getItemStatus(this.getAddressState(addressId));
}
deleteAddress(orgUnitId: string, addressId: string): void {
this.userIdService.takeUserId(true).subscribe(
(userId) =>
this.store.dispatch(
new OrgUnitActions.DeleteAddress({
userId,
orgUnitId,
addressId,
})
),
() => {
// TODO: for future releases, refactor this part to thrown errors
}
);
}
private getOrgUnitState(
orgUnitId: string
): Observable<StateUtils.LoaderState<B2BUnit>> {
return this.store.select(getOrgUnitState(orgUnitId));
}
} | the_stack |
import * as argparse from 'argparse';
import * as fs from 'fs';
import assert from 'assert';
import * as util from 'util';
import * as path from 'path';
import { Ast, Type } from 'thingtalk';
import * as I18N from '../../../lib/i18n';
import { serializePrediction } from '../../../lib/utils/thingtalk';
import { getElementType, getItemLabel, argnameFromLabel, readJson, Domains } from './utils';
import { makeDummyEntities } from "../../../lib/utils/entity-utils";
import { loadClassDef } from '../lib/utils';
export interface CSQADialogueTurn {
speaker : 'USER'|'SYSTEM',
utterance : string,
ques_type_id : 1|2|3|4|5|6|7|8,
sec_ques_type ?: 1|2,
sec_ques_sub_type ?: 1|2|3|4,
is_inc ?: 0|1,
is_incomplete ?: 0|1,
bool_ques_type ?: 1|2|3|4|5|6,
inc_ques_type ?: 1|2|3,
set_op_choice ?: 1|2|3,
set_op ?: 1|2,
count_ques_sub_type ?: 1|2|3|4|5|6|7|8|9,
type_list ?: string[],
entities_in_utterance ?: string[],
active_set ?: string[]
}
interface CSQADialogueTurnPair {
file : string,
system : CSQADialogueTurn,
user : CSQADialogueTurn,
}
interface ParameterRecord {
value : string,
preprocessed : string
}
interface CSQAConverterOptions {
locale : string;
timezone ?: string;
domains : Domains,
includeEntityValue : boolean,
filter : string,
softMatchId : boolean,
inputDir : string,
output : string,
thingpedia : string,
wikidataProperties : string,
items : string,
values : string,
types : string,
filteredExamples : string
}
class CsqaConverter {
private _locale : string;
private _timezone ?: string;
private _domains : Domains;
private _includeEntityValue : boolean;
private _softMatchId : boolean;
private _filters : Record<string, number[]>;
private _paths : Record<string, string>;
private _classDef : Ast.ClassDef|null;
private _items : Map<string, Record<string, string>>;
private _values : Map<string, string>;
private _types : Map<string, string>;
private _wikidataProperties : Map<string, string>;
private _examples : CSQADialogueTurnPair[];
private _tokenizer : I18N.BaseTokenizer;
private _unsupportedCounter : Record<string, number>;
constructor(options : CSQAConverterOptions) {
this._locale = options.locale;
this._timezone = options.timezone;
this._domains = options.domains;
this._includeEntityValue = options.includeEntityValue;
this._softMatchId = options.softMatchId;
this._filters = {};
for (const filter of options.filter || []) {
assert(filter.indexOf('=') > 0 && filter.indexOf('=') === filter.lastIndexOf('='));
const [key, values] = filter.split('=');
this._filters[key] = values.split(',').map((v) => parseInt(v));
}
this._paths = {
inputDir: options.inputDir,
output: options.output,
thingpedia: options.thingpedia,
wikidataProperties: options.wikidataProperties,
items: options.items,
values: options.values,
types: options.types,
filteredExamples: options.filteredExamples
};
this._classDef = null;
this._items = new Map();
this._values = new Map();
this._types = new Map();
this._wikidataProperties = new Map();
this._examples = [];
this._tokenizer = I18N.get('en-US').getTokenizer();
this._unsupportedCounter = {
indirect: 0,
setOp: 0,
typeConstraint: 0,
wrongAnnotation: 0
};
}
private async _getArgValue(qid : string) : Promise<ParameterRecord> {
let value;
if (this._values.has(qid)) {
value = this._values.get(qid);
} else {
value = await getItemLabel(qid);
if (value)
this._values.set(qid, value);
}
if (value)
return { value: qid, preprocessed: this._tokenizer.tokenize(value).tokens.join(' ') };
throw new Error(`Label not found for ${qid}`);
}
private _invocationTable(domain : string) : Ast.Expression {
const selector = new Ast.DeviceSelector(null, 'org.wikidata', null, null);
return new Ast.InvocationExpression(null, new Ast.Invocation(null, selector, domain, [], null), null);
}
private _generateFilter(domain : string, param : string, value : ParameterRecord) : Ast.BooleanExpression {
let ttValue, op;
if (param === 'id') {
if (this._softMatchId) {
ttValue = new Ast.Value.String(value.preprocessed);
op = '=~';
} else {
ttValue = new Ast.Value.Entity(value.value, `org.wikidata:${domain}`, value.preprocessed);
op = '==';
}
} else {
const propertyType = this._classDef!.getFunction('query', domain)!.getArgType(param)!;
const entityType = this._types.get(value.value);
const valueType = entityType ? new Type.Entity(`org.wikidata:${entityType}`) : getElementType(propertyType);
if (valueType instanceof Type.Entity) {
ttValue = new Ast.Value.Entity(value.value, valueType.type, value.preprocessed);
op = propertyType.isArray ? 'contains' : '==';
} else { // Default to string
ttValue = new Ast.Value.String(value.preprocessed);
op = propertyType.isArray ? 'contains~' : '=~';
}
}
return new Ast.BooleanExpression.Atom(null, param, op, ttValue);
}
private _getDomainBySubject(x : string) : string|null {
if (x.startsWith('c'))
return this._domains.getDomainByCSQAType(x.slice(1));
for (const [domain, items] of this._items) {
if (x in items)
return domain;
}
return null;
}
// returns [domain, projection, filter]
private async _processOneActiveSet(activeSet : string[][]) : Promise<[string, string[]|Ast.BooleanExpression|null, Ast.BooleanExpression]> {
const triple = activeSet[0];
const domain = this._getDomainBySubject(triple[0]);
assert(domain);
const subject = triple[0].startsWith('c') ? null : await this._getArgValue(triple[0]);
const relation = await argnameFromLabel(this._wikidataProperties.get(triple[1])!);
const object = triple[2].startsWith('c') ? null : await this._getArgValue(triple[2]);
// when object is absent, return a projection on relation with filtering on id = subject
if (subject && !object)
return [domain, [relation], this._generateFilter(domain, 'id', subject)];
// when subject is absent, return a filter on the relation with the object value
if (!subject && object)
return [domain, null, this._generateFilter(domain, relation, object)];
// when both subject and object exists, then it's a verification question
// return a boolean expression as projection, and a filter on id = subject
if (subject && object)
return [domain, this._generateFilter(domain, relation, object), this._generateFilter(domain, 'id', subject)];
throw new Error('Both subject and object absent in the active set entry: ' + activeSet);
}
// returns [domain, projection, filter]
private async _processOneActiveSetWithSetOp(activeSet : string[][], setOp : number) : Promise<[string, string[]|null, Ast.BooleanExpression|null]> {
assert(activeSet.length === 1 && activeSet[0].length > 3 && activeSet[0].length % 3 === 0);
const triples = [];
for (let i = 0; i < activeSet[0].length; i += 3)
triples.push(activeSet[0].slice(i, i + 3));
// when the subjects of some triples are different, it requires set operation
// in ThingTalk to represent, which is not supported yet
const subjects = new Set(triples.map(((triple) => triple[0])));
if (subjects.size > 1)
return ['unknown', null, null];
// process tripes in active set
const domains = [];
const projections = [];
const filters = [];
for (let i = 0; i < triples.length; i ++) {
const [domain, projection, filter] = await this._processOneActiveSet(triples.slice(i, i+1));
domains.push(domain);
projections.push(projection as string[]); // it won't be boolean question for set ops
filters.push(filter);
}
// FIXME: we current don't handle multiple domains
assert((new Set(domains)).size === 1);
const domain = domains[0];
// when projection is not null, it means we should have the same id filter on
// both triple, and different projection
if (projections[0] && projections[0].length > 0) {
const uniqueProjections = [...new Set(projections.flat())];
return [domain, uniqueProjections, filters[0]];
}
// when projection is null, then we merge two filters according to setOp
switch (setOp) {
case 1: return [domain, null, new Ast.BooleanExpression.Or(null, filters)]; // OR
case 2: return [domain, null, new Ast.BooleanExpression.And(null, filters)]; // AND
case 3: { // DIFF
assert(filters.length === 2);
const negateFilter = new Ast.BooleanExpression.Not(null, filters[1]);
return [domain, null, new Ast.BooleanExpression.And(null, [filters[0], negateFilter])];
}
default:
throw new Error(`Unknown set_op_choice: ${setOp}`);
}
}
// ques_type_id=1
private async _simpleQuestion(activeSet : string[][]) : Promise<Ast.Expression> {
assert(activeSet.length === 1);
const [domain, projection, filter] = await this._processOneActiveSet(activeSet);
const filterTable = new Ast.FilterExpression(null, this._invocationTable(domain), filter, null);
if (projection && Array.isArray(projection) && projection.length > 0)
return new Ast.ProjectionExpression(null, filterTable, projection, [], [], null);
return filterTable;
}
// ques_type_id=2
private async _secondaryQuestion(activeSet : string[][], secQuesType : number, secQuesSubType : number) : Promise<Ast.Expression|null> {
if (secQuesSubType === 2 || secQuesSubType === 3) {
this._unsupportedCounter.indirect += 1;
return null;
}
if (secQuesSubType === 1) {
if (activeSet.length !== 1) {
this._unsupportedCounter.wrongAnnotation += 1;
return null;
}
return this._simpleQuestion(activeSet);
}
if (secQuesSubType === 4) {
// this it basically is asking multiple questions in one sentence.
// it is sometimes ambiguous with set-based questions
if (activeSet.length <= 1)
throw new Error('Only one active set found for secondary plural question');
const domains = [];
const projections = [];
const filters = [];
for (let i = 0; i < activeSet.length; i ++) {
const [domain, projection, filter] = await this._processOneActiveSet(activeSet.slice(i, i+1));
domains.push(domain);
projections.push(projection as string[]);
filters.push(filter);
}
// FIXME: we current don't handle multiple domains
assert((new Set(domains)).size === 1);
const domain = domains[0];
const filter = new Ast.BooleanExpression.Or(null, filters);
const filterTable = new Ast.FilterExpression(null, this._invocationTable(domain), filter, null);
// when subjects of triples are entity, we are asking the same projection for multiple entities
if (secQuesType === 1) {
const uniqueProjection = [...new Set(projections.flat())];
assert(uniqueProjection.length === 1);
return new Ast.ProjectionExpression(null, filterTable, uniqueProjection, [], [], null);
}
// when subjects of triples are type (domain), we are asking multiple questions, each of which
// satisfies a different filter
if (secQuesType === 2)
return filterTable;
throw new Error('Invalid sec_ques_type for secondary question');
}
throw new Error('Invalid sec_sub_ques_type for secondary question');
}
// ques_type_id=4
private async _setBasedQuestion(activeSet : string[][], setOpChoice : number) : Promise<Ast.Expression|null> {
assert(activeSet.length === 1);
const [domain, projection, filter] = await this._processOneActiveSetWithSetOp(activeSet, setOpChoice);
if (!projection && !filter) {
this._unsupportedCounter.setOp += 1;
return null;
}
const filterTable = new Ast.FilterExpression(null, this._invocationTable(domain!), filter!, null);
if (projection && projection.length > 0)
return new Ast.ProjectionExpression(null, filterTable, projection, [], [], null);
return filterTable;
}
// ques_type_id=5
private async _booleanQuestion(activeSet : string[][], boolQuesType : number) : Promise<Ast.Expression|null> {
if (boolQuesType === 1) {
assert(activeSet.length === 1);
const [domain, projection, filter] = await this._processOneActiveSet(activeSet);
const filterTable = new Ast.FilterExpression(null, this._invocationTable(domain), filter, null);
return new Ast.BooleanQuestionExpression(null, filterTable, projection as Ast.BooleanExpression, null);
}
if (boolQuesType === 4) {
assert(activeSet.length === 2);
const [domain1, projection1, filter] = await this._processOneActiveSet(activeSet);
const [domain2, projection2, ] = await this._processOneActiveSet(activeSet.slice(1));
// FIXME: we current don't handle multiple domains
assert(domain1 === domain2);
const filterTable = new Ast.FilterExpression(null, this._invocationTable(domain1), filter, null);
const projection = new Ast.BooleanExpression.And(null, [projection1, projection2]);
return new Ast.BooleanQuestionExpression(null, filterTable, projection, null);
}
// indirect questions
this._unsupportedCounter.indirect += 1;
return null;
}
// ques_type_id=7
private async _quantitativeQuestionsSingleEntity(activeSet : string[][], entities : string[], countQuesSubType : number, utterance : string) : Promise<Ast.Expression|null> {
switch (countQuesSubType) {
case 1: { // Quantitative (count)
assert(activeSet.length === 1);
const [domain, projection, filter] = await this._processOneActiveSet(activeSet);
return this._quantitativeQuestionCount(domain, projection as string[], filter);
}
case 2: // Quantitative (min/max)
return this._quantitativeQuestionMinMax(activeSet, utterance);
case 3: // Quantitative (atleast/atmost/~~/==)
return this._quantitativeQuestionCompareCount(activeSet, utterance);
case 4: // Comparative (more/less/~~)
return this._comparativeQuestion(activeSet, entities, utterance);
case 5: { // Quantitative (count over atleast/atmost/~~/==)
const filterTable = await this._quantitativeQuestionCompareCount(activeSet, utterance);
return new Ast.AggregationExpression(null, filterTable, '*', 'count', null);
}
case 6: { // Comparative (count over more/less/~~)
const filterTable = await this._comparativeQuestion(activeSet, entities, utterance);
return new Ast.AggregationExpression(null, filterTable, '*', 'count', null);
}
case 7:
case 8:
case 9:
// indirect questions
this._unsupportedCounter.indirect += 1;
return null;
default:
throw new Error(`Unknown count_ques_sub_type: ${countQuesSubType}`);
}
}
// ques_type_id=8
private async _quantitativeQuestionsMultiEntity(activeSet : string[][], entities : string[], countQuesSubType : number, setOpChoice : number, utterance : string) : Promise<Ast.Expression|null> {
// Somehow set op is reverse of question type 4, there is no diff set op in this category
const setOp = setOpChoice === 2 ? 1:2;
switch (countQuesSubType) {
case 1: { // Quantitative with logical operators
assert(activeSet.length === 2);
activeSet = [activeSet[0].concat(activeSet[1])];
const [domain, projection, filter] = await this._processOneActiveSetWithSetOp(activeSet, setOp);
if (!projection && !filter) {
this._unsupportedCounter.setOp += 1;
return null;
}
return this._quantitativeQuestionCount(domain, projection as string[], filter!);
}
case 2: // Quantitative (count)
case 3: // Quantitative (min/max)
case 4: // Quantitative (atleast/atmost/~~/==)
case 5: // Comparative (more/less/~~)
case 6: // Quantitative (count over atleast/atmost/~~/==)
case 7: // Comparative (count over more/less/~~)
this._unsupportedCounter.typeConstraint += 1;
return null;
case 8:
case 9:
case 10:
// indirect questions
this._unsupportedCounter.indirect += 1;
return null;
default:
throw new Error(`Unknown count_ques_sub_type: ${countQuesSubType}`);
}
}
private _quantitativeOperator(utterance : string) : string {
// there is literally only one single way to talk about most aggregation
// operators in CSQA, so it's easy to decide
if (utterance.includes(' min '))
return 'asc';
if (utterance.includes(' max '))
return 'desc';
if (utterance.includes(' atleast' ))
return '>=';
if (utterance.includes(' atmost '))
return '<=';
if (utterance.includes(' exactly '))
return '==';
if (utterance.includes(' approximately ') || utterance.includes(' around '))
return '~~';
throw new Error('Failed to identify quantitative operator based on the utterance');
}
private _comparativeOperator(utterance : string) : string {
if (utterance.includes(' more ') || utterance.includes(' greater number '))
return '>=';
if (utterance.includes(' less ') || utterance.includes(' lesser number '))
return '<=';
if (utterance.includes(' same number '))
return '~~';
throw new Error('Failed to identify comparative operator based on the utterance');
}
private _numberInUtterance(utterance : string) : number {
// we expect exactly one number in the utterance
const matches = utterance.match(/\d+/);
if (!matches || matches.length === 0)
throw new Error('Failed to locate numbers from the utterance');
if (matches.length > 1)
throw new Error('Multiple numbers found in the utterance');
return parseInt(matches[0]);
}
// Quantitative (count)
private async _quantitativeQuestionCount(domain : string, projection : string[], filter : Ast.BooleanExpression) : Promise<Ast.Expression> {
const filterTable = new Ast.FilterExpression(null, this._invocationTable(domain), filter, null);
// when projection exists, it is counting parameter on a table with id filter
if (projection) {
const computation = new Ast.Value.Computation(
'count',
projection.map((param) => new Ast.Value.VarRef(param))
);
return new Ast.ProjectionExpression(null, filterTable, [], [computation], [null], null);
}
// when projection is absent, it is counting a table with a regular filter
return new Ast.AggregationExpression(null, filterTable, '*', 'count', null);
}
// Quantitative (min/max)
private async _quantitativeQuestionMinMax(activeSet : string[][], utterance : string) : Promise<Ast.Expression|null> {
assert(activeSet.length === 1);
const triple = activeSet[0];
if (!triple[0].startsWith('c') || !triple[2].startsWith('c')) {
this._unsupportedCounter.wrongAnnotation += 1;
return null;
}
const propertyLabel = this._wikidataProperties.get(triple[1]);
assert(propertyLabel);
const param = await argnameFromLabel(propertyLabel);
const computation = new Ast.Value.Computation(
'count',
[new Ast.Value.VarRef(param)]
);
const domain = this._getDomainBySubject(triple[0]);
assert(domain);
const countTable = new Ast.ProjectionExpression(null, this._invocationTable(domain), [], [computation], [null], null);
const direction = this._quantitativeOperator(utterance);
const sortTable = new Ast.SortExpression(null, countTable, new Ast.Value.VarRef('count'), direction as "asc"|"desc", null);
return new Ast.IndexExpression(null, sortTable, [new Ast.Value.Number(1)], null);
}
// Quantitative (atleast/atmost/~~/==)
private async _quantitativeQuestionCompareCount(activeSet : string[][], utterance : string) : Promise<Ast.Expression> {
assert(activeSet.length === 1);
const triple = activeSet[0];
assert(triple[0].startsWith('c') && triple[2].startsWith('c'));
const propertyLabel = this._wikidataProperties.get(triple[1]);
assert(propertyLabel);
const param = await argnameFromLabel(propertyLabel);
const computation = new Ast.Value.Computation(
'count',
[new Ast.Value.VarRef(param)]
);
const filter = new Ast.BooleanExpression.Compute(
null,
computation,
this._quantitativeOperator(utterance),
new Ast.Value.Number(this._numberInUtterance(utterance)),
null
);
const domain = this._getDomainBySubject(triple[0]);
assert(domain);
return new Ast.FilterExpression(null, this._invocationTable(domain), filter, null);
}
// comparative (more/less/~~)
private async _comparativeQuestion(activeSet : string[][], entities : string[], utterance : string) : Promise<Ast.Expression> {
assert(activeSet.length === 1 && entities.length === 1);
const triple = activeSet[0];
assert(triple[0].startsWith('c') && triple[2].startsWith('c'));
const domain = this._getDomainBySubject(triple[0]);
const propertyLabel = this._wikidataProperties.get(triple[1]);
assert(domain && propertyLabel);
const param = await argnameFromLabel(propertyLabel);
const comparisonTarget = await this._getArgValue(entities[0]);
const filter = this._generateFilter(domain, 'id', comparisonTarget);
const subquery = new Ast.ProjectionExpression(
null,
new Ast.FilterExpression(null, this._invocationTable(domain), filter, null),
[],
[new Ast.Value.Computation('count', [new Ast.Value.VarRef(param)])],
[null],
null
);
return new Ast.FilterExpression(
null,
this._invocationTable(domain),
new Ast.ComparisonSubqueryBooleanExpression(
null,
new Ast.Value.Computation('count', [new Ast.Value.VarRef(param)]),
this._comparativeOperator(utterance),
subquery,
null
),
null
);
}
async csqaToThingTalk(dialog : CSQADialogueTurnPair) : Promise<Ast.Expression|null> {
const user = dialog.user;
const system = dialog.system;
if (user.is_incomplete || user.is_inc) {
this._unsupportedCounter.indirect += 1;
return null;
}
const activeSet = [];
assert(system.active_set);
for (const active of system.active_set)
activeSet.push(active.replace(/[^0-9PQc,|]/g, '').split(','));
switch (user.ques_type_id) {
case 1: // Simple Question (subject-based)
return this._simpleQuestion(activeSet);
case 2: // Secondary question
return this._secondaryQuestion(activeSet, user.sec_ques_type!, user.sec_ques_sub_type!);
case 3: // Clarification (for secondary) question
this._unsupportedCounter.indirect += 1;
return null;
case 4: // Set-based question
return this._setBasedQuestion(activeSet, user.set_op_choice!);
case 5: // Boolean (Factual Verification) question
return this._booleanQuestion(activeSet, user.bool_ques_type!);
case 6: // Incomplete question (for secondary)
this._unsupportedCounter.indirect += 1;
return null;
case 7: // Comparative and Quantitative questions (involving single entity)
return this._quantitativeQuestionsSingleEntity(activeSet, user.entities_in_utterance!, user.count_ques_sub_type!, user.utterance);
case 8: // Comparative and Quantitative questions (involving multiple(2) entities)
return this._quantitativeQuestionsMultiEntity(activeSet, user.entities_in_utterance!, user.count_ques_sub_type!, user.set_op!, user.utterance);
default:
throw new Error(`Unknown ques_type_id: ${user.ques_type_id}`);
}
}
private async _filterTurnsByDomain(dialog : CSQADialogueTurn[], file : string) {
let userTurn;
for (const turn of dialog) {
const speaker = turn.speaker;
if (speaker === 'USER') {
let skip = false;
for (const [key, values] of Object.entries(this._filters)) {
if (!values.includes(turn[key as keyof CSQADialogueTurn] as number))
skip = true;
}
userTurn = skip ? null : turn;
} else {
if (!userTurn)
continue;
assert(turn.active_set);
// only consider examples that contain _only_ the given domain
let inDomain = true;
for (const active of turn.active_set) {
const triples = active.replace(/[^0-9PQc,|]/g, '').split(',');
for (let i = 0; i < triples.length; i += 3) {
const subject = triples[i];
const domain = this._getDomainBySubject(subject);
if (!domain && !this._items.has(subject))
inDomain = false;
}
}
if (inDomain) {
this._examples.push({
file: file,
user: userTurn,
system: turn,
});
}
}
}
}
async _filterExamples() {
for (const dir of fs.readdirSync(this._paths.inputDir)) {
for (const file of fs.readdirSync(path.join(this._paths.inputDir, dir))) {
const dialog = JSON.parse(fs.readFileSync(path.join(this._paths.inputDir, dir, file), { encoding: 'utf-8' }));
this._filterTurnsByDomain(dialog, file);
}
}
console.log(`${this._examples.length} QA pairs found`);
await util.promisify(fs.writeFile)(this._paths.filteredExamples, JSON.stringify(this._examples, undefined, 2));
}
async _loadFilteredExamples() {
this._examples = JSON.parse(await util.promisify(fs.readFile)(this._paths.filteredExamples, { encoding: 'utf-8' }));
}
async _convert() {
const annotated = [];
const skipped = [];
const error = [];
for (const example of this._examples) {
let expression;
try {
expression = await this.csqaToThingTalk(example);
} catch(e) {
console.log('Error during conversion:');
console.log('question:', example.user.utterance);
console.log('triples:', example.system.active_set);
console.error(e.message);
expression = null;
}
if (!expression) {
skipped.push(example);
continue;
}
try {
const program = new Ast.Program(null, [], [], [new Ast.ExpressionStatement(null, expression)]);
const user = example.user;
const preprocessed = this._tokenizer.tokenize(user.utterance).tokens.join(' ');
const entities = makeDummyEntities(preprocessed);
const thingtalk = serializePrediction(program, preprocessed, entities, { locale: this._locale, timezone: this._timezone, includeEntityValue : this._includeEntityValue }).join(' ');
annotated.push({
id : annotated.length + 1,
raw: user.utterance,
preprocessed,
thingtalk
});
} catch(e) {
console.log('Error during serializing:');
console.log('question:', example.user.utterance);
console.log('triples:', example.system.active_set);
console.error(e.message);
error.push(example);
}
}
console.log(`${annotated.length} annotated, ${skipped.length} skipped, ${error.length} thrown error.`);
console.log(`Among skipped questions:`);
console.log(`(1) indirect questions: ${this._unsupportedCounter.indirect}`);
console.log(`(2) set operations: ${this._unsupportedCounter.setOp}`);
console.log(`(3) type constraint: ${this._unsupportedCounter.typeConstraint}`);
console.log(`(4) wrong annotation: ${this._unsupportedCounter.wrongAnnotation}`);
return annotated;
}
async run() {
this._classDef = await loadClassDef(this._paths.thingpedia, { locale: this._locale, timezone: this._timezone });
this._items = await readJson(this._paths.items);
this._values = await readJson(this._paths.values);
this._types = await readJson(this._paths.types);
this._wikidataProperties = await readJson(this._paths.wikidataProperties);
// load in-domain examples
if (fs.existsSync(this._paths.filteredExamples))
await this._loadFilteredExamples();
else
await this._filterExamples();
// convert dataset annotation into thingtalk
const dataset = await this._convert();
// output thingtalk dataset
await util.promisify(fs.writeFile)(this._paths.output, dataset.map((example) => {
return `${example.id}\t${example.preprocessed}\t${example.thingtalk}`;
}).join('\n'), { encoding: 'utf8' });
}
}
module.exports = {
initArgparse(subparsers : argparse.SubParser) {
const parser = subparsers.add_parser('wikidata-convert-csqa', {
add_help: true,
description: "Generate parameter-datasets.tsv from processed wikidata dump. "
});
parser.add_argument('-l', '--locale', {
default: 'en-US',
help: `BGP 47 locale tag of the natural language being processed (defaults to en-US).`
});
parser.add_argument('--timezone', {
required: false,
default: undefined,
help: `Timezone to use to interpret dates and times (defaults to the current timezone).`
});
parser.add_argument('-o', '--output', {
required: true,
});
parser.add_argument('-i', '--input', {
required: true,
});
parser.add_argument('--domains', {
required: true,
help: 'the path to the file containing type mapping for each domain'
});
parser.add_argument('--thingpedia', {
required: true,
help: 'Path to ThingTalk file containing class definitions.'
});
parser.add_argument('--wikidata-property-list', {
required: true,
help: "full list of properties in the wikidata dump, named filtered_property_wikidata4.json"
+ "in CSQA, in the form of a dictionary with PID as keys and canonical as values."
});
parser.add_argument('--items', {
required: true,
help: "A json file containing the labels for items of the domain"
});
parser.add_argument('--values', {
required: true,
help: "A json file containing the labels for value entities for the domain"
});
parser.add_argument('--types', {
required: true,
help: "A json file containing the entity types for value entities in the domain"
});
parser.add_argument('--filtered-examples', {
required: true,
help: "A json file containing in-domain examples of the given CSQA dataset"
});
parser.add_argument('--include-entity-value', {
action: 'store_true',
help: "Include entity value in thingtalk",
default: false
});
parser.add_argument('--soft-match-id', {
action: 'store_true',
help: "Do string soft match on id property",
default: false
});
parser.add_argument('--filter', {
required: false,
default: [],
nargs: '+',
help: 'filters to be applied to CSQA dataset, in the format of [key]=[value(int)]'
});
},
async execute(args : any) {
const domains = new Domains({ path: args.domains });
await domains.init();
const csqaConverter = new CsqaConverter({
locale: args.locale,
timezone : args.timezone,
domains,
inputDir: args.input,
output: args.output,
thingpedia: args.thingpedia,
wikidataProperties: args.wikidata_property_list,
items: args.items,
values: args.values,
types: args.types,
filteredExamples: args.filtered_examples,
includeEntityValue: args.include_entity_value,
softMatchId: args.soft_match_id,
filter: args.filter
});
csqaConverter.run();
},
CsqaConverter
}; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Manages a Key Vault Managed Storage Account.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleClientConfig = azure.core.getClientConfig({});
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const exampleAccountSAS = exampleAccount.primaryConnectionString.apply(primaryConnectionString => azure.storage.getAccountSAS({
* connectionString: primaryConnectionString,
* httpsOnly: true,
* resourceTypes: {
* service: true,
* container: false,
* object: false,
* },
* services: {
* blob: true,
* queue: false,
* table: false,
* file: false,
* },
* start: "2021-04-30T00:00:00Z",
* expiry: "2023-04-30T00:00:00Z",
* permissions: {
* read: true,
* write: true,
* "delete": false,
* list: false,
* add: true,
* create: true,
* update: false,
* process: false,
* },
* }));
* const exampleKeyVault = new azure.keyvault.KeyVault("exampleKeyVault", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* tenantId: data.azurerm_client_config.current.tenant_id,
* skuName: "standard",
* accessPolicies: [{
* tenantId: data.azurerm_client_config.current.tenant_id,
* objectId: data.azurerm_client_config.current.object_id,
* secretPermissions: [
* "Get",
* "Delete",
* ],
* storagePermissions: [
* "Get",
* "List",
* "Set",
* "SetSAS",
* "GetSAS",
* "DeleteSAS",
* "Update",
* "RegenerateKey",
* ],
* }],
* });
* const exampleManagedStorageAccount = new azure.keyvault.ManagedStorageAccount("exampleManagedStorageAccount", {
* keyVaultId: exampleKeyVault.id,
* storageAccountId: exampleAccount.id,
* storageAccountKey: "key1",
* regenerateKeyAutomatically: false,
* });
* ```
* ### Automatically Regenerate Storage Account Access Key)
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleClientConfig = azure.core.getClientConfig({});
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const exampleAccountSAS = exampleAccount.primaryConnectionString.apply(primaryConnectionString => azure.storage.getAccountSAS({
* connectionString: primaryConnectionString,
* httpsOnly: true,
* resourceTypes: {
* service: true,
* container: false,
* object: false,
* },
* services: {
* blob: true,
* queue: false,
* table: false,
* file: false,
* },
* start: "2021-04-30T00:00:00Z",
* expiry: "2023-04-30T00:00:00Z",
* permissions: {
* read: true,
* write: true,
* "delete": false,
* list: false,
* add: true,
* create: true,
* update: false,
* process: false,
* },
* }));
* const exampleKeyVault = new azure.keyvault.KeyVault("exampleKeyVault", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* tenantId: data.azurerm_client_config.current.tenant_id,
* skuName: "standard",
* accessPolicies: [{
* tenantId: data.azurerm_client_config.current.tenant_id,
* objectId: data.azurerm_client_config.current.object_id,
* secretPermissions: [
* "Get",
* "Delete",
* ],
* storagePermissions: [
* "Get",
* "List",
* "Set",
* "SetSAS",
* "GetSAS",
* "DeleteSAS",
* "Update",
* "RegenerateKey",
* ],
* }],
* });
* const exampleAssignment = new azure.authorization.Assignment("exampleAssignment", {
* scope: exampleAccount.id,
* roleDefinitionName: "Storage Account Key Operator Service Role",
* principalId: "727055f9-0386-4ccb-bcf1-9237237ee102",
* });
* const exampleManagedStorageAccount = new azure.keyvault.ManagedStorageAccount("exampleManagedStorageAccount", {
* keyVaultId: exampleKeyVault.id,
* storageAccountId: exampleAccount.id,
* storageAccountKey: "key1",
* regenerateKeyAutomatically: true,
* regenerationPeriod: "P1D",
* });
* ```
*
* ## Import
*
* Key Vault Managed Storage Accounts can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:keyvault/managedStorageAccount:ManagedStorageAccount example https://example-keyvault.vault.azure.net/storage/exampleStorageAcc01
* ```
*/
export class ManagedStorageAccount extends pulumi.CustomResource {
/**
* Get an existing ManagedStorageAccount 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?: ManagedStorageAccountState, opts?: pulumi.CustomResourceOptions): ManagedStorageAccount {
return new ManagedStorageAccount(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:keyvault/managedStorageAccount:ManagedStorageAccount';
/**
* Returns true if the given object is an instance of ManagedStorageAccount. 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 ManagedStorageAccount {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === ManagedStorageAccount.__pulumiType;
}
/**
* The ID of the Key Vault where the Managed Storage Account should be created. Changing this forces a new resource to be created.
*/
public readonly keyVaultId!: pulumi.Output<string>;
/**
* The name which should be used for this Key Vault Managed Storage Account. Changing this forces a new Key Vault Managed Storage Account to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* Should Storage Account access key be regenerated periodically?
*/
public readonly regenerateKeyAutomatically!: pulumi.Output<boolean | undefined>;
/**
* How often Storage Account access key should be regenerated. Value needs to be in [ISO 8601 duration format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
*/
public readonly regenerationPeriod!: pulumi.Output<string | undefined>;
/**
* The ID of the Storage Account.
*/
public readonly storageAccountId!: pulumi.Output<string>;
/**
* Which Storage Account access key that is managed by Key Vault. Possible values are `key1` and `key2`.
*/
public readonly storageAccountKey!: pulumi.Output<string>;
/**
* A mapping of tags which should be assigned to the Key Vault Managed Storage Account.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Create a ManagedStorageAccount 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: ManagedStorageAccountArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ManagedStorageAccountArgs | ManagedStorageAccountState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ManagedStorageAccountState | undefined;
inputs["keyVaultId"] = state ? state.keyVaultId : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["regenerateKeyAutomatically"] = state ? state.regenerateKeyAutomatically : undefined;
inputs["regenerationPeriod"] = state ? state.regenerationPeriod : undefined;
inputs["storageAccountId"] = state ? state.storageAccountId : undefined;
inputs["storageAccountKey"] = state ? state.storageAccountKey : undefined;
inputs["tags"] = state ? state.tags : undefined;
} else {
const args = argsOrState as ManagedStorageAccountArgs | undefined;
if ((!args || args.keyVaultId === undefined) && !opts.urn) {
throw new Error("Missing required property 'keyVaultId'");
}
if ((!args || args.storageAccountId === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageAccountId'");
}
if ((!args || args.storageAccountKey === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageAccountKey'");
}
inputs["keyVaultId"] = args ? args.keyVaultId : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["regenerateKeyAutomatically"] = args ? args.regenerateKeyAutomatically : undefined;
inputs["regenerationPeriod"] = args ? args.regenerationPeriod : undefined;
inputs["storageAccountId"] = args ? args.storageAccountId : undefined;
inputs["storageAccountKey"] = args ? args.storageAccountKey : undefined;
inputs["tags"] = args ? args.tags : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(ManagedStorageAccount.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering ManagedStorageAccount resources.
*/
export interface ManagedStorageAccountState {
/**
* The ID of the Key Vault where the Managed Storage Account should be created. Changing this forces a new resource to be created.
*/
keyVaultId?: pulumi.Input<string>;
/**
* The name which should be used for this Key Vault Managed Storage Account. Changing this forces a new Key Vault Managed Storage Account to be created.
*/
name?: pulumi.Input<string>;
/**
* Should Storage Account access key be regenerated periodically?
*/
regenerateKeyAutomatically?: pulumi.Input<boolean>;
/**
* How often Storage Account access key should be regenerated. Value needs to be in [ISO 8601 duration format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
*/
regenerationPeriod?: pulumi.Input<string>;
/**
* The ID of the Storage Account.
*/
storageAccountId?: pulumi.Input<string>;
/**
* Which Storage Account access key that is managed by Key Vault. Possible values are `key1` and `key2`.
*/
storageAccountKey?: pulumi.Input<string>;
/**
* A mapping of tags which should be assigned to the Key Vault Managed Storage Account.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
}
/**
* The set of arguments for constructing a ManagedStorageAccount resource.
*/
export interface ManagedStorageAccountArgs {
/**
* The ID of the Key Vault where the Managed Storage Account should be created. Changing this forces a new resource to be created.
*/
keyVaultId: pulumi.Input<string>;
/**
* The name which should be used for this Key Vault Managed Storage Account. Changing this forces a new Key Vault Managed Storage Account to be created.
*/
name?: pulumi.Input<string>;
/**
* Should Storage Account access key be regenerated periodically?
*/
regenerateKeyAutomatically?: pulumi.Input<boolean>;
/**
* How often Storage Account access key should be regenerated. Value needs to be in [ISO 8601 duration format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
*/
regenerationPeriod?: pulumi.Input<string>;
/**
* The ID of the Storage Account.
*/
storageAccountId: pulumi.Input<string>;
/**
* Which Storage Account access key that is managed by Key Vault. Possible values are `key1` and `key2`.
*/
storageAccountKey: pulumi.Input<string>;
/**
* A mapping of tags which should be assigned to the Key Vault Managed Storage Account.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
} | the_stack |
* Created by Dolkkok on 2017. 7. 18..
*/
import {AfterViewInit, Component, ElementRef, Injector, Input, OnDestroy, OnInit} from '@angular/core';
import {BaseChart, ChartSelectInfo} from '../base-chart';
import {BaseOption} from '../option/base-option';
import {
CellColorTarget,
CHART_STRING_DELIMITER,
ChartColorList,
ChartColorType,
ChartSelectMode,
ColorCustomMode,
FontSize,
GridViewType,
ShelveFieldType,
ShelveType,
UIOrient,
UIPosition
} from '../option/define/common';
import {ColorOptionConverter} from '@common/component/chart/option/converter/color-option-converter';
import {Pivot} from '@domain/workbook/configurations/pivot';
import {Field} from '@domain/workbook/configurations/field/field';
import {Format} from '@domain/workbook/configurations/format';
import * as _ from 'lodash';
import {UIChartColorByCell} from '../option/ui-option';
import {TotalValueStyle, UIGridChart} from '../option/ui-option/ui-grid-chart';
import {UIChartColorGradationByCell} from '../option/ui-option/ui-color';
declare let pivot: any;
@Component({
selector: 'grid-chart',
template: '<div class="chartCanvas" style="width: 100%; height: 100%; display: block;"></div>'
})
export class GridChartComponent extends BaseChart<UIGridChart> implements OnInit, OnDestroy, AfterViewInit {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
private gridModel: any;
// 원본보기일때 원본보기 데이터
private originData: any;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@Input()
public viewMode: boolean = false;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(
protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
// Init
super.ngOnInit();
}
// Destory
public ngOnDestroy() {
// Destory
super.ngOnDestroy();
}
// After View Init
public ngAfterViewInit(): void {
setTimeout(() => {
this.isLoaded = true;
});
const browserLang = this.translateService.getBrowserLang();
pivot.ui.common.lang = (browserLang.match(/ko/)) ? 'ko' : 'en';
// Chart Instance 생성
pivot.ui.style.summaryLabel = {
SUM: this.translateService.instant('msg.page.calc.label.operator.sum'),
AVERAGE: this.translateService.instant('msg.page.calc.label.operator.average'),
MAX: this.translateService.instant('msg.page.calc.label.operator.max'),
MIN: this.translateService.instant('msg.page.calc.label.operator.min'),
COUNT: this.translateService.instant('msg.page.calc.label.operator.count')
};
pivot.ui.style.subSummaryLabel = {
SUM: this.translateService.instant('msg.page.calc.label.operator.sub-sum'),
AVERAGE: this.translateService.instant('msg.page.calc.label.operator.sub-average'),
MAX: this.translateService.instant('msg.page.calc.label.operator.sub-max'),
MIN: this.translateService.instant('msg.page.calc.label.operator.sub-min'),
COUNT: this.translateService.instant('msg.page.calc.label.operator.sub-count')
};
this.chart = new pivot.ui.pivot.Viewer(this.$element.find('.chartCanvas')[0]);
// 초기에 주입된 데이터를 기준으로 차트를 표현한다.
if (this.data) {
this.draw();
}
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 차트에 설정된 옵션으로 차트를 그린다.
* - 각 차트에서 Override
* @param _isKeepRange: 현재 스크롤 위치를 기억해야 할 경우
*/
public draw(_isKeepRange?: boolean): void {
////////////////////////////////////////////////////////
// Valid 체크
////////////////////////////////////////////////////////
if (!this.isValid(this.pivot)) {
// No Data 이벤트 발생
this.noData.emit();
return;
}
////////////////////////////////////////////////////////
// Basic (Type, Title, etc..)
////////////////////////////////////////////////////////
// 차트 기본설정 정보를 변환
this.chartOption = this.convertBasic();
////////////////////////////////////////////////////////
// series
////////////////////////////////////////////////////////
// 차트 시리즈 정보를 변환
this.chartOption = this.convertSeries();
////////////////////////////////////////////////////////
// apply
////////////////////////////////////////////////////////
// 차트 반영
this.apply();
////////////////////////////////////////////////////////
// Draw Finish
// - 차트 표현 완료후 resize등 후속처리
////////////////////////////////////////////////////////
this.drawFinish();
}
/**
* 선반정보를 기반으로 차트를 그릴수 있는지 여부를 체크
* - 반드시 각 차트에서 Override
*/
public isValid(pivotInfo: Pivot): boolean {
return ((this.getFieldTypeCount(pivotInfo, ShelveType.COLUMNS, ShelveFieldType.DIMENSION) > 0 || this.getFieldTypeCount(pivotInfo, ShelveType.COLUMNS, ShelveFieldType.TIMESTAMP) > 0)
|| (this.getFieldTypeCount(pivotInfo, ShelveType.ROWS, ShelveFieldType.DIMENSION) > 0 || this.getFieldTypeCount(pivotInfo, ShelveType.ROWS, ShelveFieldType.TIMESTAMP) > 0))
&& (this.getFieldTypeCount(pivotInfo, ShelveType.AGGREGATIONS, ShelveFieldType.MEASURE) > 0 || this.getFieldTypeCount(pivotInfo, ShelveType.AGGREGATIONS, ShelveFieldType.CALCULATED) > 0);
// return ((this.getFieldTypeCount(pivot, ShelveType.COLUMNS, ShelveFieldType.DIMENSION) + this.getFieldTypeCount(pivot, ShelveType.COLUMNS, ShelveFieldType.TIMESTAMP)) > 0)
// && (this.getFieldTypeCount(pivot, ShelveType.AGGREGATIONS, ShelveFieldType.MEASURE) > 0 || this.getFieldTypeCount(pivot, ShelveType.AGGREGATIONS, ShelveFieldType.CALCULATED) > 0)
// && (this.getFieldTypeCount(pivot, ShelveType.COLUMNS, ShelveFieldType.MEASURE) == 0 && this.getFieldTypeCount(pivot, ShelveType.COLUMNS, ShelveFieldType.CALCULATED) == 0)
// && (this.getFieldTypeCount(pivot, ShelveType.ROWS, ShelveFieldType.MEASURE) == 0 && this.getFieldTypeCount(pivot, ShelveType.ROWS, ShelveFieldType.CALCULATED) == 0);
}
/**
* Grid Select(Click) Event Listener
*
*/
public addGridSelectEventListener(params): void {
const selectMode = params.isSelect ? ChartSelectMode.ADD : ChartSelectMode.SUBTRACT;
const selectDataList = [];
const shelve = $(this)[0]['shelve'];
// pivot값이 없는경우 return
if (!shelve || !shelve.columns) return;
// 행, 열 선반 리스트
const shelveList = _.cloneDeep(shelve.columns.concat(shelve.rows));
// 부모데이터가 있는경우 (축을 클릭했을때)
if (!_.isUndefined(params.parentData)) {
// 헤더 클릭
const data = _.cloneDeep(_.find(shelveList, {alias: params.key}));
// 찾은 데이터가 없는경우 return
if (!data) return;
data['data'] = [params.data];
// dataList에 추가
selectDataList.push(data);
// 부모 헤더가 존재 할 경우
if (!_.isNull(params.parentData)) {
// 부모 헤터의 선택정보 맵핑
_.forEach(params.parentData, (value, key) => {
// selectData[key] = [value];
const shelveData = _.cloneDeep(_.find(shelveList, {alias: key}));
// 찾은 데이터가 없는경우 return
if (!shelveData) return;
shelveData['data'] = [value];
// dataList에 추가
selectDataList.push(shelveData);
});
}
// 부모데이터가 없는경우 (셀을 클릭했을때)
} else {
let dimensionList = _.concat(this['xProperties'], this['yProperties']);
dimensionList = dimensionList.map((dimension) => {
return dimension.name;
});
_.map(params, (item: string) => {
const splitItem = _.split(item, CHART_STRING_DELIMITER);
if (-1 !== _.indexOf(dimensionList, splitItem[0])) {
const data = _.cloneDeep(_.find(shelveList, {alias: splitItem[0]}));
data['data'] = [splitItem[1]];
selectDataList.push(data);
}
});
}
// 이벤트 데이터 전송
this['gridSelectInfo'].emit(new ChartSelectInfo(selectMode, selectDataList, this['customParams']));
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 차트 기본설정 정보를 변환한다.
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected convertBasic(): BaseOption {
if (!this.uiOption) return;
this.uiOption.maxValue = this.data.info.maxValue;
this.uiOption.minValue = this.data.info.minValue;
// header, body 데이터가 없는경우 설정
this.uiOption = this.setGridData();
// if (this.uiOption.label) {
// // minValue가 0보다 작은경우 scaleDisabled true
// if (this.data.info.minValue < 0) {
// this.uiOption.label.scaleDisabled = true;
//
// // 0이거나 0보다 큰경우
// } else {
//
// this.uiOption.label.scaleDisabled = false;
// }
// }
// chartOption을 쓰지 않지만 override를 위해 반환
return this.chartOption;
}
/**
* 시리즈 정보를 변환한다.
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected convertSeries(): BaseOption {
// min, max값 설정
const minValue = this.data.info.minValue;
const maxValue = this.data.info.maxValue;
// X, Y, X
let cols: any = this.fieldInfo.cols.map((name) => {
return {name};
});
let rows: any = this.fieldInfo.rows.map((name) => {
return {name};
});
let aggregations: any;
if (this.pivot && this.pivot.aggregations && 0 < this.pivot.aggregations.length) {
aggregations = this.pivot.aggregations.map((aggr) => {
const aggrInfo = {
name: _.isUndefined(aggr.alias) ? aggr.name : aggr.alias,
digits: 2
};
if (aggr.field && aggr.field.logicalType) {
aggrInfo['type'] = aggr.field.logicalType;
}
aggrInfo['fieldFormat'] = this.setFieldFormat(aggr);
return aggrInfo;
});
} else {
aggregations = this.fieldInfo.aggs.map((name) => {
return {name, digits: 2};
});
}
// 원본보기데이터 초기화
this.originData = [];
// 원본 보기일경우 데이터 재가공
if ((this.uiOption as UIGridChart).dataType === GridViewType.MASTER) {
// for setting aggregations original name
let originAggregations: any = this.fieldOriginInfo.aggs.map((name) => {
return {name, digits: 2};
});
const columns = this.data.columns;
const removeAggregationType = (field) => {
const regExp = /\((.*)\)/gi;
const match = regExp.exec(field.name);
if (match != null && match.length > 1) {
field.name = match[1];
} else field.name;
};
// aggregation 함수 제거
for (let i = 0, nMax = originAggregations.length; i < nMax; i++) {
removeAggregationType(originAggregations[i]);
}
originAggregations = cols.concat(rows, originAggregations);
// 같은 이름을 가진 measure값 제거
originAggregations = _.uniqBy(originAggregations, 'name');
const newData = [];
for (let i = 0; i < columns[0].value.length; i++) {
for (let j = 0; j < originAggregations.length; j++) {
const key = originAggregations[j].name;
const json = {};
json[' '] = i + 1;
json['COLUMNS'] = key;
json['VALUE'] = columns[j].value[i];
newData.push(json);
}
}
cols = [{name: 'COLUMNS'}];
rows = [{name: ' '}];
originAggregations = [{name: 'VALUE'}];
this.pivot.aggregations.map((aggr) => {
if (aggr.field && aggr.field.logicalType) {
(originAggregations[0].type) || (originAggregations[0].type = {});
originAggregations[0].type[aggr.name] = aggr.field.logicalType;
(originAggregations[0]['fieldFormat']) || (originAggregations[0]['fieldFormat'] = []);
if (-1 === originAggregations[0]['fieldFormat'].findIndex(item => aggr.field.name === item['aggrColumn'])) {
const fieldFormat = this.setFieldFormat( aggr );
fieldFormat['aggrColumn'] = aggr.field.name;
originAggregations[0]['fieldFormat'].push(fieldFormat);
}
}
});
aggregations = originAggregations;
// 원본보기 데이터에 설정
this.originData = newData;
}
// 차트 속성 설정
this.gridModel = {
xProperties: cols,
yProperties: rows,
zProperties: aggregations,
axisSelectMode: 'MULTI',
onAxisXClick: !this.isPage ? this.addGridSelectEventListener : null,
onAxisYClick: !this.isPage ? this.addGridSelectEventListener : null,
onBodyCellClick: !this.isPage && this.pivot.columns.length > 1 && this.pivot.rows.length > 1 ? this.addGridSelectEventListener : null, // 한쪽에만 헤더가 있는경우 cellClick이 안되게 막음
cellWidth: 120,
cellHeight: 30,
showAxisZ: false,
customParams: this.params,
gridSelectInfo: this.chartSelectInfo,
shelve: this.pivot,
min: minValue,
max: maxValue,
header: {
font: {},
align: {},
},
body: {
font: {},
color: {
stepColors: [],
stepTextColors: []
},
align: {},
showAxisZ: false
}
};
// Grid Width 설정
if ((this.uiOption as UIGridChart).gridColumnWidth) {
this.gridModel.columnWidth = (this.uiOption as UIGridChart).gridColumnWidth;
}
// view 모드일 경우에는 클릭이벤트 삭제
if (this.viewMode === true) {
delete this.gridModel.onAxisXClick;
delete this.gridModel.onAxisYClick;
delete this.gridModel.onBodyCellClick;
}
// UI 옵션 적용
if (this.uiOption && this.uiOption.color) {
this.gridModel.useSelectStyle = this.uiOption && _.eq((this.uiOption as UIGridChart).dataType, GridViewType.PIVOT);
this.gridModel.leftAxisWidth = this.uiOption && _.eq((this.uiOption as UIGridChart).dataType, GridViewType.PIVOT) ? 120 : 65;
const schema = this.uiOption.color.schema;
this.gridModel.showColorStep = !_.isEmpty(schema);
const cellColor = this.uiOption.color;
// 원본타입일때 zProperties의 VALUE값 hide
if (_.eq((this.uiOption as UIGridChart).dataType, GridViewType.MASTER)) this.gridModel.showDataColumn = false;
// 색상 설정여부
this.gridModel.body.color.showColorStep = true;
// 색상 타입 설정
this.gridModel.body.color.colorTarget = cellColor.colorTarget ? cellColor.colorTarget : CellColorTarget.TEXT;
// ranges 색상값이있을때 설정
this.setRangeColor(cellColor, this.gridModel);
// 폰트컬러가 있는겨웅 폰트컬러로 설정
if (this.uiOption.contentStyle.fontColor && '' !== this.uiOption.contentStyle.fontColor) {
// visualGradations이 있는경우 stepTextColor를 visualGradations개수만큼 설정
if (this.uiOption.color['visualGradations'] && this.uiOption.color['visualGradations'].length > 0) {
this.gridModel.body.color.stepTextColors = this.uiOption.color['visualGradations'].map(() => {
return this.uiOption.contentStyle.fontColor
});
} else {
this.gridModel.body.color.stepTextColors = [this.uiOption.contentStyle.fontColor];
}
}
// 본문스타일 show head column
this.gridModel.body.showAxisZ = this.uiOption.contentStyle
? this.uiOption.contentStyle.showHeader
? this.uiOption.contentStyle.showHeader
: false
: false;
this.gridModel.dataColumnMode = _.eq(this.uiOption.measureLayout, UIOrient.HORIZONTAL)
? this.chart.DATA_COL_MODE.TOP
: this.chart.DATA_COL_MODE.LEFT;
// 정렬 설정
// 헤더에서는 문자값만 있으므로 기본설정 선택시 왼쪽정렬로 설정
if (UIPosition.AUTO === this.uiOption.headerStyle.hAlign) {
this.gridModel.header.align.hAlign = UIPosition.LEFT.toString().toLowerCase();
} else {
// 가로정렬
this.gridModel.header.align.hAlign = this.uiOption.headerStyle.hAlign.toString().toLowerCase();
}
// 본문에서는 auto시 숫자값은 오른쪽, 문자값은 왼쪽으로 정렬됨
this.gridModel.body.align.hAlign = this.uiOption.contentStyle.hAlign.toString().toLowerCase();
// 세로정렬
this.gridModel.header.align.vAlign = this.uiOption.headerStyle.vAlign.toString().toLowerCase();
this.gridModel.body.align.vAlign = this.uiOption.contentStyle.vAlign.toString().toLowerCase();
// 폰트사이즈 설정
this.gridModel.header.font.size = this.setFontSize(this.uiOption.headerStyle.fontSize);
this.gridModel.body.font.size = this.setFontSize(this.uiOption.contentStyle.fontSize);
// 폰트스타일 설정
this.gridModel.header.font.styles = this.uiOption.headerStyle.fontStyles;
this.gridModel.body.font.styles = this.uiOption.contentStyle.fontStyles;
// 헤더 보이기
this.gridModel.header.showHeader = this.uiOption.headerStyle.showHeader;
// 설명 설정
this.gridModel.remark = this.uiOption.annotation;
// 헤더 색상설정
this.gridModel.header.font.color = this.uiOption.headerStyle.fontColor;
this.gridModel.header.backgroundColor = this.uiOption.headerStyle.backgroundColor;
// 연산행 설정
if (this.uiOption.totalValueStyle) {
this.gridModel.totalValueStyle = this._getGridTotalStyle(this.uiOption.totalValueStyle);
}
// 연산열 설정
if (this.uiOption.showCalculatedColumnStyle) {
this.gridModel.showCalculatedColumnStyle = this._getGridTotalStyle(this.uiOption.showCalculatedColumnStyle);
}
// 부분 연산행 설정
if(this.uiOption.subTotalValueStyle) {
const gridStyle = this._getGridTotalStyle(this.uiOption.subTotalValueStyle);
this.gridModel.subCalcCellStyle
= rows.reduce((acc, item) => {
acc[item.name.toLowerCase()] = JSON.parse(JSON.stringify(gridStyle));
return acc;
}, {});
}
// 부분 연산열 설정
if(this.uiOption.subTotalColumnStyle) {
const gridStyle = this._getGridTotalStyle(this.uiOption.subTotalColumnStyle);
this.gridModel.subCalcCellStyle
= cols.reduce((acc, item) => {
acc[item.name.toLowerCase()] = JSON.parse(JSON.stringify(gridStyle));
return acc;
}, this.gridModel.subCalcCellStyle ? this.gridModel.subCalcCellStyle : {});
}
// 숫자 포멧 설정
this.gridModel.format = this.uiOption.valueFormat;
}
// chartOption을 쓰지 않지만 override를 위해 반환
return this.chartOption;
}
/**
* 차트에 옵션 반영
* - Echart기반 차트가 아닐경우 Override 필요
* @param _initFl 차트 초기화 여부
*/
protected apply(_initFl: boolean = true): void {
// 원본보기일때 원본보기 데이터로 정제된 데이터를 설정
const data = this.uiOption.dataType === GridViewType.MASTER ? this.originData : this.data;
if (this.userCustomFunction && '' !== this.userCustomFunction && -1 < this.userCustomFunction.indexOf('main')) {
const strScript = '(' + this.userCustomFunction + ')';
// ( new Function( 'return ' + strScript ) )();
try {
this.gridModel = eval(strScript)({name: 'InitWidgetEvent', data: this.gridModel});
} catch (e) {
console.error(e);
}
}
// 차트 데이터 주입
try {
this.chart.initialize(data, this.gridModel);
} catch (e) {
console.log(e);
// No Data 이벤트 발생
this.noData.emit();
return;
}
}
/**
* 차트 표현후 리사이즈
* - 필요시 각 차트에서 Override
* @returns {BaseOption}
*/
protected drawFinish(): void {
// 차트 생성 완료 이벤트 발생
this.drawFinished.emit();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 그리드 합계 스타일 생성
* @param valueStyle - 차트 합께 스타일
* @private 그리드 합계 스타일
*/
private _getGridTotalStyle(valueStyle: TotalValueStyle) {
const gridStyle = JSON.parse(JSON.stringify(valueStyle));
gridStyle.font = {};
gridStyle.font.size = this.setFontSize(valueStyle.fontSize);
gridStyle.font.color = valueStyle.fontColor;
gridStyle.font.styles = valueStyle.fontStyles;
gridStyle.align = {};
gridStyle.align.hAlign = valueStyle.hAlign;
gridStyle.align.vAlign = valueStyle.vAlign;
return gridStyle;
} // func - _getGridTotalStyle
/**
* grid 사용자 색상설정
* @param cellColor 색상값
* @param gridModel grid에 설정하는값
*/
private setRangeColor(cellColor: UIChartColorByCell, gridModel: any) {
let rangeList = [];
// ranges값이 있는경우 stepRangeColors에 값설정
if (cellColor.ranges && cellColor.ranges.length > 0) {
// gradation일때
if (this.uiOption.color['customMode'] && ColorCustomMode.GRADIENT === this.uiOption.color['customMode']) {
this.setGradationRangeColor(cellColor as UIChartColorGradationByCell, gridModel);
} else {
rangeList = _.cloneDeep(cellColor.ranges);
const rangeColors = [];
// gt, lte값을 min / max 값으로 치환
rangeList.forEach((item) => {
rangeColors.push({min: item.gt, max: item.lte, fixMin: item.fixMin, fixMax: item.fixMax, color: item.color});
});
rangeColors[0].max = 999999999999999999999;
rangeColors[rangeColors.length - 1].min = -999999999999999999999;
// pieces값 설정
gridModel.body.color.stepRangeColors = rangeColors;
}
}
}
/**
* gradation 색상설정
* @param cellColor
* @param gridModel
*/
private setGradationRangeColor(cellColor: UIChartColorGradationByCell, gridModel: any) {
const codes = cellColor.visualGradations.map((item) => {
return item['color']
});
if (CellColorTarget.BACKGROUND === this.uiOption.color.colorTarget) {
gridModel.body.color.stepColors = codes;
} else {
gridModel.body.color.stepTextColors = codes;
}
}
/**
* 폰트사이즈에 따라 사이즈 number 리턴
* @param fontSize
* @returns {number}
*/
private setFontSize(fontSize: FontSize): number {
// 폰트사이즈 설정
let size: number;
switch (fontSize) {
case FontSize.NORMAL:
size = 13;
break;
case FontSize.SMALL:
size = 11;
break;
case FontSize.LARGE:
size = 15;
break;
}
return size;
}
/**
* uiOption headerStyle, contentStyle 기본설정
* @returns {UIGridChart}
*/
private setGridData(): UIGridChart {
const uiOption = this.uiOption;
if (!uiOption.headerStyle) uiOption.headerStyle = {};
if (!uiOption.headerStyle.fontSize) uiOption.headerStyle.fontSize = FontSize.NORMAL;
if (_.isUndefined(uiOption.headerStyle.showHeader)) uiOption.headerStyle.showHeader = true;
if (!uiOption.headerStyle.fontStyles) uiOption.headerStyle.fontStyles = [];
if (!uiOption.headerStyle.hAlign) uiOption.headerStyle.hAlign = UIPosition.LEFT;
if (!uiOption.headerStyle.vAlign) uiOption.headerStyle.vAlign = UIPosition.MIDDLE;
if (!uiOption.headerStyle.backgroundColor) uiOption.headerStyle.backgroundColor = '#ffffff';
if (!uiOption.headerStyle.fontColor) uiOption.headerStyle.fontColor = '#959595';
if (!uiOption.contentStyle) uiOption.contentStyle = {};
if (!uiOption.contentStyle.hAlign) uiOption.contentStyle.hAlign = UIPosition.LEFT;
if (!uiOption.contentStyle.vAlign) uiOption.contentStyle.vAlign = UIPosition.MIDDLE;
if (!uiOption.contentStyle.fontSize) uiOption.contentStyle.fontSize = FontSize.NORMAL;
if (!uiOption.contentStyle.fontStyles) uiOption.contentStyle.fontStyles = [];
if (!uiOption.contentStyle.fontColor) uiOption.contentStyle.fontColor = '';
if (_.isUndefined(uiOption.headerStyle.showHeader)) uiOption.headerStyle.showHeader = false;
if (ChartColorType.SINGLE === uiOption.color.type && !uiOption.color['code']) uiOption.color['code'] = '';
return this.uiOption
}
/**
* 필드 형식 설정
* @param aggr - 필드 정보 ( Aggregation )
* @private
*/
private setFieldFormat(aggr:Field): Format {
let fieldFormat:Format = {};
if (aggr.fieldFormat) {
fieldFormat = JSON.parse(JSON.stringify(aggr.fieldFormat));
}
if( aggr.color ) {
const colorTarget = this.uiOption.color.colorTarget ? this.uiOption.color.colorTarget : CellColorTarget.TEXT;
if( aggr.color.rgb ) {
// 단색 설정
if( colorTarget === CellColorTarget.TEXT ) {
( fieldFormat['font'] ) || ( fieldFormat['font'] = {} );
fieldFormat['font']['color'] = aggr.color.rgb;
} else {
fieldFormat['backgroundColor'] = aggr.color.rgb;
}
} else {
// 그라데이션 설정
const colorList = ChartColorList[aggr.color.schema.key] as any;
const ranges = ColorOptionConverter.setMeasureColorRange(this.uiOption, this.data, colorList);
ranges[0].lte = 999999999999999999999;
ranges[ranges.length - 1].gt = -999999999999999999999;
if( colorTarget === CellColorTarget.TEXT ) {
( fieldFormat['font'] ) || ( fieldFormat['font'] = {} );
fieldFormat['font']['rangeColor'] = ranges;
} else {
fieldFormat['rangeBackgroundColor'] = ranges;
}
}
}
return fieldFormat;
} // func - setFieldFormat
} | the_stack |
import 'chrome://resources/cr_elements/cr_expand_button/cr_expand_button.m.js';
import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-collapse/iron-collapse.js';
import '../settings_shared_css.js';
import './recent_site_permissions.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {loadTimeData} from '../i18n_setup.js';
import {routes} from '../route.js';
import {Route, Router} from '../router.js';
import {ContentSettingsTypes} from '../site_settings/constants.js';
import {CategoryListItem} from './site_settings_list.js';
const Id = ContentSettingsTypes;
let categoryItemMap: Map<ContentSettingsTypes, CategoryListItem>|null = null;
type FocusConfig = Map<string, (string|(() => void))>;
function getCategoryItemMap(): Map<ContentSettingsTypes, CategoryListItem> {
if (categoryItemMap !== null) {
return categoryItemMap;
}
// The following list is ordered alphabetically by |id|. The order in which
// these appear in the UI is determined elsewhere in this file.
const categoryList = [
{
route: routes.SITE_SETTINGS_ADS,
id: Id.ADS,
label: 'siteSettingsAds',
icon: 'settings:ads',
enabledLabel: 'siteSettingsAdsAllowed',
disabledLabel: 'siteSettingsAdsBlocked',
shouldShow: () =>
loadTimeData.getBoolean('enableSafeBrowsingSubresourceFilter'),
},
{
route: routes.SITE_SETTINGS_AR,
id: Id.AR,
label: 'siteSettingsAr',
icon: 'settings:vr-headset',
// TODO(crbug.com/1196900): Fix redesign string when available.
enabledLabel: 'siteSettingsArAsk',
disabledLabel: 'siteSettingsArBlock',
},
{
route: routes.SITE_SETTINGS_AUTOMATIC_DOWNLOADS,
id: Id.AUTOMATIC_DOWNLOADS,
label: 'siteSettingsAutomaticDownloads',
icon: 'cr:file-download',
enabledLabel: 'siteSettingsAutomaticDownloadsAllowed',
disabledLabel: 'siteSettingsAutomaticDownloadsBlocked',
},
{
route: routes.SITE_SETTINGS_BACKGROUND_SYNC,
id: Id.BACKGROUND_SYNC,
label: 'siteSettingsBackgroundSync',
icon: 'cr:sync',
enabledLabel: 'siteSettingsBackgroundSyncAllowed',
disabledLabel: 'siteSettingsBackgroundSyncBlocked',
},
{
route: routes.SITE_SETTINGS_BLUETOOTH_DEVICES,
id: Id.BLUETOOTH_DEVICES,
label: 'siteSettingsBluetoothDevices',
icon: 'settings:bluetooth',
enabledLabel: 'siteSettingsBluetoothDevicesAllowed',
disabledLabel: 'siteSettingsBluetoothDevicesBlocked',
shouldShow: () =>
loadTimeData.getBoolean('enableWebBluetoothNewPermissionsBackend'),
},
{
route: routes.SITE_SETTINGS_BLUETOOTH_SCANNING,
id: Id.BLUETOOTH_SCANNING,
label: 'siteSettingsBluetoothScanning',
icon: 'settings:bluetooth-scanning',
enabledLabel: 'siteSettingsBluetoothScanningAsk',
disabledLabel: 'siteSettingsBluetoothScanningBlock',
shouldShow: () =>
loadTimeData.getBoolean('enableExperimentalWebPlatformFeatures'),
},
{
route: routes.SITE_SETTINGS_CAMERA,
id: Id.CAMERA,
label: 'siteSettingsCamera',
icon: 'cr:videocam',
enabledLabel: 'siteSettingsCameraAllowed',
disabledLabel: 'siteSettingsCameraBlocked',
},
{
route: routes.SITE_SETTINGS_CLIPBOARD,
id: Id.CLIPBOARD,
label: 'siteSettingsClipboard',
icon: 'settings:clipboard',
enabledLabel: 'siteSettingsClipboardAllowed',
disabledLabel: 'siteSettingsClipboardBlocked',
},
{
route: routes.COOKIES,
id: Id.COOKIES,
label: 'siteSettingsCookies',
icon: 'settings:cookie',
enabledLabel: 'siteSettingsCookiesAllowed',
disabledLabel: 'siteSettingsBlocked',
otherLabel: 'cookiePageClearOnExit',
},
{
route: routes.SITE_SETTINGS_LOCATION,
id: Id.GEOLOCATION,
label: 'siteSettingsLocation',
icon: 'settings:location-on',
enabledLabel: 'siteSettingsLocationAllowed',
disabledLabel: 'siteSettingsLocationBlocked',
},
{
route: routes.SITE_SETTINGS_HID_DEVICES,
id: Id.HID_DEVICES,
label: 'siteSettingsHidDevices',
icon: 'settings:hid-device',
enabledLabel: 'siteSettingsHidDevicesAsk',
disabledLabel: 'siteSettingsHidDevicesBlock',
},
{
route: routes.SITE_SETTINGS_IDLE_DETECTION,
id: Id.IDLE_DETECTION,
label: 'siteSettingsIdleDetection',
icon: 'settings:devices',
enabledLabel: 'siteSettingsDeviceUseAllowed',
disabledLabel: 'siteSettingsDeviceUseBlocked',
},
{
route: routes.SITE_SETTINGS_IMAGES,
id: Id.IMAGES,
label: 'siteSettingsImages',
icon: 'settings:photo',
enabledLabel: 'siteSettingsImagesAllowed',
disabledLabel: 'siteSettingsImagesBlocked',
},
{
route: routes.SITE_SETTINGS_JAVASCRIPT,
id: Id.JAVASCRIPT,
label: 'siteSettingsJavascript',
icon: 'settings:code',
enabledLabel: 'siteSettingsJavascriptAllowed',
disabledLabel: 'siteSettingsJavascriptBlocked',
},
{
route: routes.SITE_SETTINGS_MICROPHONE,
id: Id.MIC,
label: 'siteSettingsMic',
icon: 'cr:mic',
enabledLabel: 'siteSettingsMicAllowed',
disabledLabel: 'siteSettingsMicBlocked',
},
{
route: routes.SITE_SETTINGS_MIDI_DEVICES,
id: Id.MIDI_DEVICES,
label: 'siteSettingsMidiDevices',
icon: 'settings:midi',
enabledLabel: 'siteSettingsMidiAllowed',
disabledLabel: 'siteSettingsMidiBlocked',
},
{
route: routes.SITE_SETTINGS_MIXEDSCRIPT,
id: Id.MIXEDSCRIPT,
label: 'siteSettingsInsecureContent',
icon: 'settings:insecure-content',
disabledLabel: 'siteSettingsInsecureContentBlock',
},
{
route: routes.SITE_SETTINGS_FILE_HANDLING,
id: Id.FILE_HANDLING,
label: 'siteSettingsFileHandling',
icon: 'settings:file-handling',
enabledLabel: 'siteSettingsFileHandlingAsk',
disabledLabel: 'siteSettingsFileHandlingBlock',
},
{
route: routes.SITE_SETTINGS_FILE_SYSTEM_WRITE,
id: Id.FILE_SYSTEM_WRITE,
label: 'siteSettingsFileSystemWrite',
icon: 'settings:save-original',
enabledLabel: 'siteSettingsFileSystemWriteAllowed',
disabledLabel: 'siteSettingsFileSystemWriteBlocked',
},
{
route: routes.SITE_SETTINGS_FONT_ACCESS,
id: Id.FONT_ACCESS,
label: 'fonts',
icon: 'settings:font-access',
enabledLabel: 'siteSettingsFontsAllowed',
disabledLabel: 'siteSettingsFontsBlocked',
},
{
route: routes.SITE_SETTINGS_NOTIFICATIONS,
id: Id.NOTIFICATIONS,
label: 'siteSettingsNotifications',
icon: 'settings:notifications',
enabledLabel: 'siteSettingsAskBeforeSending',
disabledLabel: 'siteSettingsBlocked',
},
{
route: routes.SITE_SETTINGS_PAYMENT_HANDLER,
id: Id.PAYMENT_HANDLER,
label: 'siteSettingsPaymentHandler',
icon: 'settings:payment-handler',
enabledLabel: 'siteSettingsPaymentHandlersAllowed',
disabledLabel: 'siteSettingsPaymentHandlersBlocked',
shouldShow: () =>
loadTimeData.getBoolean('enablePaymentHandlerContentSetting'),
},
{
route: routes.SITE_SETTINGS_PDF_DOCUMENTS,
id: Id.PDF_DOCUMENTS,
label: 'siteSettingsPdfDocuments',
icon: 'settings:pdf',
enabledLabel: 'siteSettingsPdfsAllowed',
disabledLabel: 'siteSettingsPdfsBlocked',
},
{
route: routes.SITE_SETTINGS_POPUPS,
id: Id.POPUPS,
label: 'siteSettingsPopups',
icon: 'cr:open-in-new',
enabledLabel: 'siteSettingsPopupsAllowed',
disabledLabel: 'siteSettingsPopupsBlocked',
},
{
route: routes.SITE_SETTINGS_PROTECTED_CONTENT,
id: Id.PROTECTED_CONTENT,
label: 'siteSettingsProtectedContent',
icon: 'settings:protected-content',
enabledLabel: 'siteSettingsProtectedContentAllowed',
disabledLabel: 'siteSettingsProtectedContentBlocked',
},
{
route: routes.SITE_SETTINGS_HANDLERS,
id: Id.PROTOCOL_HANDLERS,
label: 'siteSettingsHandlers',
icon: 'settings:protocol-handler',
enabledLabel: 'siteSettingsProtocolHandlersAllowed',
disabledLabel: 'siteSettingsProtocolHandlersBlocked',
shouldShow: () => !loadTimeData.getBoolean('isGuest'),
},
{
route: routes.SITE_SETTINGS_SENSORS,
id: Id.SENSORS,
label: 'siteSettingsSensors',
icon: 'settings:sensors',
enabledLabel: 'siteSettingsMotionSensorsAllowed',
disabledLabel: 'siteSettingsMotionSensorsBlocked',
},
{
route: routes.SITE_SETTINGS_SERIAL_PORTS,
id: Id.SERIAL_PORTS,
label: 'siteSettingsSerialPorts',
icon: 'settings:serial-port',
enabledLabel: 'siteSettingsSerialPortsAllowed',
disabledLabel: 'siteSettingsSerialPortsBlocked',
},
{
route: routes.SITE_SETTINGS_SOUND,
id: Id.SOUND,
label: 'siteSettingsSound',
icon: 'settings:volume-up',
enabledLabel: 'siteSettingsSoundAllowed',
disabledLabel: 'siteSettingsSoundBlocked',
},
{
route: routes.SITE_SETTINGS_USB_DEVICES,
id: Id.USB_DEVICES,
label: 'siteSettingsUsbDevices',
icon: 'settings:usb',
enabledLabel: 'siteSettingsUsbAllowed',
disabledLabel: 'siteSettingsUsbBlocked',
},
{
route: routes.SITE_SETTINGS_VR,
id: Id.VR,
label: 'siteSettingsVr',
icon: 'settings:vr-headset',
enabledLabel: 'siteSettingsVrAllowed',
disabledLabel: 'siteSettingsVrBlocked',
},
{
route: routes.SITE_SETTINGS_WINDOW_PLACEMENT,
id: Id.WINDOW_PLACEMENT,
label: 'siteSettingsWindowPlacement',
icon: 'settings:window-placement',
enabledLabel: 'siteSettingsWindowPlacementAsk',
disabledLabel: 'siteSettingsWindowPlacementBlock',
},
{
route: routes.SITE_SETTINGS_ZOOM_LEVELS,
id: Id.ZOOM_LEVELS,
label: 'siteSettingsZoomLevels',
icon: 'settings:zoom-in',
},
];
categoryItemMap = new Map(categoryList.map(item => [item.id, item]));
return categoryItemMap;
}
function buildItemListFromIds(orderedIdList: Array<ContentSettingsTypes>):
Array<CategoryListItem> {
const map = getCategoryItemMap();
const orderedList = [];
for (const id of orderedIdList) {
const item = map.get(id)!;
if (item.shouldShow === undefined || item.shouldShow()) {
orderedList.push(item);
}
}
return orderedList;
}
export class SettingsSiteSettingsPageElement extends PolymerElement {
static get is() {
return 'settings-site-settings-page';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
lists_: {
type: Object,
value: function() {
return {
permissionsBasic: buildItemListFromIds([
Id.GEOLOCATION,
Id.CAMERA,
Id.MIC,
Id.NOTIFICATIONS,
Id.BACKGROUND_SYNC,
]),
permissionsAdvanced: buildItemListFromIds([
Id.SENSORS,
Id.AUTOMATIC_DOWNLOADS,
Id.PROTOCOL_HANDLERS,
Id.MIDI_DEVICES,
Id.USB_DEVICES,
Id.SERIAL_PORTS,
Id.BLUETOOTH_DEVICES,
Id.FILE_SYSTEM_WRITE,
Id.HID_DEVICES,
Id.CLIPBOARD,
Id.PAYMENT_HANDLER,
Id.BLUETOOTH_SCANNING,
Id.AR,
Id.VR,
Id.IDLE_DETECTION,
Id.WINDOW_PLACEMENT,
Id.FONT_ACCESS,
Id.FILE_HANDLING,
]),
contentBasic: buildItemListFromIds([
Id.COOKIES,
Id.JAVASCRIPT,
Id.IMAGES,
Id.POPUPS,
]),
contentAdvanced: buildItemListFromIds([
Id.SOUND,
Id.ADS,
Id.ZOOM_LEVELS,
Id.PDF_DOCUMENTS,
Id.PROTECTED_CONTENT,
Id.MIXEDSCRIPT,
]),
};
}
},
focusConfig: {
type: Object,
observer: 'focusConfigChanged_',
},
permissionsExpanded_: Boolean,
contentExpanded_: Boolean,
noRecentSitePermissions_: Boolean,
};
}
focusConfig: FocusConfig;
private permissionsExpanded_: boolean;
private contentExpanded_: boolean;
private noRecentSitePermissions_: boolean;
private lists_: {
all: Array<CategoryListItem>,
permissionsBasic: Array<CategoryListItem>,
permissionsAdvanced: Array<CategoryListItem>,
contentBasic: Array<CategoryListItem>,
contentAdvanced: Array<CategoryListItem>,
};
private focusConfigChanged_(_newConfig: FocusConfig, oldConfig: FocusConfig) {
// focusConfig is set only once on the parent, so this observer should
// only fire once.
assert(!oldConfig);
this.focusConfig.set(routes.SITE_SETTINGS_ALL.path, () => {
focusWithoutInk(assert(this.shadowRoot!.querySelector('#allSites')!));
});
}
private onSiteSettingsAllClick_() {
Router.getInstance().navigateTo(routes.SITE_SETTINGS_ALL);
}
/** @return Class for the all site settings link */
private getClassForSiteSettingsAllLink_(): string {
return this.noRecentSitePermissions_ ? '' : 'hr';
}
}
customElements.define(
SettingsSiteSettingsPageElement.is, SettingsSiteSettingsPageElement); | the_stack |
import TestSuiteWorker from "worker-loader?inline=no-fallback!test_suite/test_suite_worker";
import { assertNotNull, Rpc } from "common";
import { TestSuiteTests } from "test_suite/test_suite_worker";
import { PostMessageTypedArray, ZapArray } from "types";
import { zapBufferTests } from "test_suite/zap_buffer_test";
import * as zaplib from "zaplib_runtime";
import {
expect,
expectDeallocationOrUnregister as _expectDeallocationOrUnregister,
expectThrow,
expectThrowAsync,
setInTest,
} from "test_suite/test_helpers";
import { inWorker } from "type_of_runtime";
declare global {
interface Window {
// Exposed for zaplib_ci.
runAllTests3x: () => Promise<void>;
}
}
const expectDeallocationOrUnregister = (buffer: ZapArray) =>
_expectDeallocationOrUnregister(zaplib.callRustAsync, buffer);
export type TestSuiteWorkerSpec = {
send: {
runTest: [TestSuiteTests, void];
initWasm: [MessagePort, void];
sendWorker: [PostMessageTypedArray, void];
testSendZapArrayToMainThread: [
void,
{
array: PostMessageTypedArray;
subarray: PostMessageTypedArray;
}
];
testCallRustAsyncSyncWithZapbuffer: [void, PostMessageTypedArray];
};
receive: Record<string, never>;
};
const rpc = new Rpc<TestSuiteWorkerSpec>(new TestSuiteWorker());
const runWorkerTest = (testName: TestSuiteTests) => () =>
rpc.send("runTest", testName);
const env = new URL(window.document.location.toString()).searchParams.has(
"release"
)
? "release"
: "debug";
let onPanicCalled = false;
expect(zaplib.isInitialized(), false);
zaplib
.initialize({
wasmModule: `target/wasm32-unknown-unknown/${env}/test_suite.wasm`,
defaultStyles: true,
onPanic: () => {
onPanicCalled = true;
},
})
.then(async () => {
expect(zaplib.isInitialized(), true);
// Initialize the worker by sending a "zap worker port" to it in the first message.
if (zaplib.jsRuntime === "wasm") {
const zapWorkerPort = zaplib.newWorkerPort();
await rpc.send("initWasm", zapWorkerPort, [zapWorkerPort]);
}
zaplib.registerCallJsCallbacks({
log(params) {
console.log("log fn called", params[0]);
const div = document.createElement("div");
div.innerText = "log fn called: " + params[0];
assertNotNull(document.getElementById("root")).append(div);
},
sendWorker(params) {
const toSend = params[0] as Uint8Array;
console.log("sending data", toSend);
// Note: uncomment to see the error about sending typed arrays
// worker.postMessage(buffers[0]);
rpc.send("sendWorker", zaplib.serializeZapArrayForPostMessage(toSend));
},
});
const runtimeSpecificTests =
zaplib.jsRuntime === "wasm"
? {
"Call rust from worker": runWorkerTest(
"testCallRustAsyncFromWorker"
),
"Call rust (no return) from worker": runWorkerTest(
"testCallRustAsyncNoReturnFromWorker"
),
"Call rust with Float32Array from worker": runWorkerTest(
"testCallRustAsyncFloat32ArrayFromWorker"
),
"Call rust in same thread sync with Float32Array from worker":
runWorkerTest("testCallRustAsyncSyncFloat32ArrayFromWorker"),
"Test that for a worker 'inWorker' returns true":
runWorkerTest("testInWorker"),
"Send zap array to main thread": async () => {
const result = await rpc.send("testSendZapArrayToMainThread");
const array = zaplib.deserializeZapArrayFromPostMessage(
result.array
);
const subarray = zaplib.deserializeZapArrayFromPostMessage(
result.subarray
);
expect(array.length, 4);
expect(array[0], 30);
expect(array[1], 40);
expect(array[2], 50);
expect(array[3], 60);
expect(subarray.length, 2);
expect(subarray[0], 40);
expect(subarray[1], 50);
},
"Call Rust in same thread with zapbuffer from worker": async () => {
const result = await rpc.send(
"testCallRustAsyncSyncWithZapbuffer"
);
const array = zaplib.deserializeZapArrayFromPostMessage(result);
expect(array.length, 8);
expect(array[0], 10);
expect(array[1], 20);
expect(array[2], 30);
expect(array[3], 40);
expect(array[4], 50);
expect(array[5], 60);
expect(array[6], 70);
expect(array[7], 80);
},
"Send signal from worker": runWorkerTest(
"testCallRustAsyncSyncWithSignal"
),
}
: {
// CEF
};
const tests = {
"Call Rust": async () => {
const buffer = new SharedArrayBuffer(8);
new Uint8Array(buffer).set([1, 2, 3, 4, 5, 6, 7, 8]);
const uint8Part = new Uint8Array(buffer, 2, 4);
const [result] = await zaplib.callRustAsync("array_multiply_u8", [
JSON.stringify(10),
uint8Part,
]);
expect(result.length, 4);
expect(result[0], 30);
expect(result[1], 40);
expect(result[2], 50);
expect(result[3], 60);
},
"Call Rust (no return)": async () => {
const result = await zaplib.callRustAsync("call_rust_no_return");
expect(result.length, 0);
},
"Call Rust (string return)": async () => {
const buffer = new SharedArrayBuffer(8);
const data = new Uint8Array(buffer);
data.set([1, 2, 3, 4, 5, 6, 7, 8]);
const [result] = await zaplib.callRustAsync("total_sum", [data]);
expect(result, "36");
},
"Call Rust (with ZapBuffer)": async () => {
const buffer = zaplib.createReadOnlyBuffer(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])
);
const [result] = await zaplib.callRustAsync<[Uint8Array]>(
"array_multiply_u8_readonly",
[JSON.stringify(10), buffer]
);
expect(result.length, 8);
expect(result[0], 10);
expect(result[1], 20);
expect(result[2], 30);
expect(result[3], 40);
expect(result[4], 50);
expect(result[5], 60);
expect(result[6], 70);
expect(result[7], 80);
return Promise.all([
expectDeallocationOrUnregister(buffer),
expectDeallocationOrUnregister(result),
]);
},
"Call Rust (with Mutable ZapBuffer)": async () => {
// TODO(Paras): Add enforcement of readonly ZapArrays and test it.
// const [buffer] = await zaplib.callRustAsync("make_zapbuffer");
// let err;
// try {
// buffer[0] = 0;
// } catch (e) {
// err = e;
// } finally {
// expect(err?.message, "Cannot mutate a read-only array");
// }
const mutableBuffer = await zaplib.createMutableBuffer(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])
);
expect(mutableBuffer.length, 8);
expect(mutableBuffer[0], 1);
expect(mutableBuffer[1], 2);
expect(mutableBuffer[2], 3);
expect(mutableBuffer[3], 4);
expect(mutableBuffer[4], 5);
expect(mutableBuffer[5], 6);
expect(mutableBuffer[6], 7);
expect(mutableBuffer[7], 8);
// Mutate the buffer to ensure the changes are detected in Rust code
mutableBuffer[0] = 0;
mutableBuffer[1] = 0;
mutableBuffer[2] = 0;
mutableBuffer[3] = 0;
const [result] = await zaplib.callRustAsync<[Uint8Array]>(
"array_multiply_u8",
[JSON.stringify(10), mutableBuffer]
);
expect(result.length, 8);
expect(result[0], 0);
expect(result[1], 0);
expect(result[2], 0);
expect(result[3], 0);
expect(result[4], 50);
expect(result[5], 60);
expect(result[6], 70);
expect(result[7], 80);
return Promise.all([
expectDeallocationOrUnregister(mutableBuffer),
expectDeallocationOrUnregister(result),
]);
},
"Call Rust with Float32Array": () => {
// Using a normal array
const input = new Float32Array([0.1, 0.9, 0.3]);
const [result] = zaplib.callRustSync<[Float32Array]>(
"array_multiply_f32",
[JSON.stringify(10), input]
);
expect(result.length, 3);
expect(result[0], 1);
expect(result[1], 9);
expect(result[2], 3);
// Using a ZapArray
const input2 = zaplib.createMutableBuffer(
new Float32Array([0.1, 0.9, 0.3])
);
const [result2] = zaplib.callRustSync<[Float32Array]>(
"array_multiply_f32",
[JSON.stringify(10), input2]
);
expect(result2.length, 3);
expect(result2[0], 1);
expect(result2[1], 9);
expect(result2[2], 3);
// Using a readonly ZapArray
const input3 = zaplib.createReadOnlyBuffer(
new Float32Array([0.1, 0.9, 0.3])
);
const [result3] = zaplib.callRustSync<[Float32Array]>(
"array_multiply_f32_readonly",
[JSON.stringify(10), input3]
);
expect(result3.length, 3);
expect(result3[0], 1);
expect(result3[1], 9);
expect(result3[2], 3);
return Promise.all([
expectDeallocationOrUnregister(result),
expectDeallocationOrUnregister(input2),
expectDeallocationOrUnregister(result2),
expectDeallocationOrUnregister(input3),
expectDeallocationOrUnregister(result3),
]);
},
"Call Rust (in same thread)": () => {
const buffer = new SharedArrayBuffer(8);
new Uint8Array(buffer).set([1, 2, 3, 4, 5, 6, 7, 8]);
const uint8Part = new Uint8Array(buffer, 2, 4);
const [result] = zaplib.callRustSync("array_multiply_u8", [
JSON.stringify(10),
uint8Part,
]);
expect(result.length, 4);
expect(result[0], 30);
expect(result[1], 40);
expect(result[2], 50);
expect(result[3], 60);
},
"Call Rust with Float32Array (in same thread)": () => {
// Using a normal array
const input = new Float32Array([0.1, 0.9, 0.3]);
const [result] = zaplib.callRustSync("array_multiply_f32", [
JSON.stringify(10),
input,
]);
expect(result.length, 3);
expect(result[0], 1);
expect(result[1], 9);
expect(result[2], 3);
// Using a ZapArray
const input2 = zaplib.createMutableBuffer(
new Float32Array([0.1, 0.9, 0.3])
);
const [result2] = zaplib.callRustSync("array_multiply_f32", [
JSON.stringify(10),
input2,
]);
expect(result2.length, 3);
expect(result2[0], 1);
expect(result2[1], 9);
expect(result2[2], 3);
// Using a readonly ZapArray
const input3 = zaplib.createReadOnlyBuffer(
new Float32Array([0.1, 0.9, 0.3])
);
const [result3] = zaplib.callRustSync("array_multiply_f32_readonly", [
JSON.stringify(10),
input3,
]);
expect(result3.length, 3);
expect(result3[0], 1);
expect(result3[1], 9);
expect(result3[2], 3);
},
"Cast WrBuffers": () => {
const input = zaplib.createMutableBuffer(new Float32Array([0.1]));
const castArray = new Uint8Array(input.buffer);
expect(castArray.length, 4);
expect(castArray[0], 205);
expect(castArray[1], 204);
expect(castArray[2], 204);
expect(castArray[3], 61);
expectThrow(
() => zaplib.callRustSync("verify_cast_array", [castArray]),
"Cannot call Rust with a buffer which has been cast to a different type. Expected F32Buffer but got U8Buffer"
);
const input2 = zaplib.createReadOnlyBuffer(new Float32Array([0.1]));
const castArray2 = new Uint8Array(input2.buffer);
expect(castArray2.length, 4);
expect(castArray2[0], 205);
expect(castArray2[1], 204);
expect(castArray2[2], 204);
expect(castArray2[3], 61);
expectThrow(
() => zaplib.callRustSync("verify_cast_array", [castArray2]),
"Cannot call Rust with a buffer which has been cast to a different type. Expected ReadOnlyF32Buffer but got ReadOnlyU8Buffer"
);
},
"On the main thread inWorker returns false": () => {
expect(inWorker, false);
},
...runtimeSpecificTests,
...zapBufferTests,
};
const checkWasmOffline = async () => {
const asyncFuncs = [() => zaplib.callRustAsync("call_rust_no_return")];
for (const f of asyncFuncs) {
await expectThrowAsync(f, "Zaplib WebAssembly instance crashed");
}
const syncFuncs = [
() => zaplib.createMutableBuffer(new Uint8Array()),
() => zaplib.createReadOnlyBuffer(new Uint8Array()),
() => {
zaplib.callRustSync("call_rust_no_return");
},
];
for (const f of syncFuncs) {
expectThrow(f, "Zaplib WebAssembly instance crashed");
}
await rpc.send("runTest", "testErrorAfterPanic");
};
const otherTests =
zaplib.jsRuntime === "wasm"
? {
"Disable RPC after panic": async () => {
await expectThrowAsync(
async () => {
await zaplib.callRustAsync("panic");
},
// TODO(Paras): An exact line number here is kind of annoying. Later we can have some sort of partial matcher.
"panicked at 'I am panicking!', zaplib/web/test_suite/src/main.rs:109:17"
);
await checkWasmOffline();
},
"Throw error from event handling to user provided callback":
async () => {
await zaplib.callRustAsync("panic_signal");
// TODO(Paras): Since event handling happens in a setTimeout, we have
// to do this check some time after `callRustAsync`. For now, use a 10ms delay.
setTimeout(async () => {
expect(onPanicCalled, true);
await checkWasmOffline();
}, 10);
},
"Throw error from draw to user provided callback": async () => {
await zaplib.callRustAsync("panic_draw");
// TODO(Paras): Since event handling happens in a setTimeout, we have
// to do this check some time after `callRustAsync`. For now, use a 10ms delay.
setTimeout(async () => {
expect(onPanicCalled, true);
await checkWasmOffline();
}, 10);
},
}
: {};
const makeButtons = () => {
const jsRoot = assertNotNull(document.getElementById("root"));
window.runAllTests3x = async () => {
setInTest(true);
for (let i = 0; i < 3; i++) {
for (const [testName, test] of Object.entries(tests)) {
console.log(`Running test: ${testName}`);
await test();
console.log(`✅ Success`);
const button = document.getElementById(testName);
if (button) {
button.innerText += "✅";
}
}
}
console.log(
`✅ All tests completed (3x to ensure no memory corruption!)`
);
setInTest(false);
};
const runAllButton = document.createElement("button");
runAllButton.innerText = "Run All Tests 3x";
runAllButton.onclick = window.runAllTests3x;
const buttonDiv = document.createElement("div");
buttonDiv.append(runAllButton);
jsRoot.append(buttonDiv);
for (const [name, test] of Object.entries(tests)) {
const button = document.createElement("button");
button.innerText = name;
button.id = name;
button.onclick = async () => {
setInTest(true);
console.log(`Running test: ${name}`);
await test();
console.log(`✅ Success`);
button.innerText += "✅";
setInTest(false);
};
const buttonDiv = document.createElement("div");
buttonDiv.append(button);
jsRoot.append(buttonDiv);
}
const otherTestsRoot = assertNotNull(
document.getElementById("other-tests")
);
for (const [name, test] of Object.entries(otherTests)) {
const button = document.createElement("button");
button.innerText = name;
button.onclick = async () => {
setInTest(true);
console.log(`Running test: ${name}`);
await test();
console.log(`✅ Success`);
button.innerText += "✅";
setInTest(false);
};
const buttonDiv = document.createElement("div");
buttonDiv.append(button);
otherTestsRoot.append(buttonDiv);
}
};
if (document.readyState !== "loading") {
makeButtons();
} else {
document.addEventListener("DOMContentLoaded", makeButtons);
}
}); | the_stack |
import "reflect-metadata"
import { createClass, reflection } from "./helpers"
import { getMetadata, setMetadata } from "./storage"
import {
Class,
CustomPropertyDecorator,
DecoratorId,
DecoratorOption,
DecoratorOptionId,
DecoratorTargetType,
GenericTypeParameterDecorator,
GenericTypeArgumentDecorator,
NativeParameterDecorator,
NoopDecorator,
ParameterPropertiesDecorator,
PrivateDecorator,
TypeDecorator,
TypeOverride,
} from "./types"
/**
* Add metadata information on parameter specified
*/
export function decorateParameter(callback: ((target: Class, name: string, index: number) => any), option?: DecoratorOption): ParameterDecorator
export function decorateParameter(data: any, option?: DecoratorOption): ParameterDecorator
export function decorateParameter(data: any, option?: DecoratorOption): ParameterDecorator {
return (target: any, name: string | symbol, index: number) => {
const isCtorParam = reflection.isConstructor(target)
const targetClass = isCtorParam ? target : target.constructor
const methodName = isCtorParam ? "constructor" : name
const meta = typeof data === "function" ? data(targetClass, methodName, index) : data
setMetadata({ ...meta, [DecoratorOptionId]: { ...meta[DecoratorOptionId], ...option } }, targetClass, methodName, index)
}
}
/**
* Add metadata information on method specified
*/
export function decorateMethod(callback: ((target: Class, name: string) => any), option?: DecoratorOption): MethodDecorator
export function decorateMethod(data: any, option?: DecoratorOption): MethodDecorator
export function decorateMethod(data: any, option?: DecoratorOption) {
return (target: any, name: string | symbol) => {
const targetClass = target.constructor
const meta = typeof data === "function" ? data(targetClass, name) : data
setMetadata({ ...meta, [DecoratorOptionId]: { ...meta[DecoratorOptionId], ...option } }, targetClass, name)
}
}
/**
* Add metadata information on property specified
*/
export function decorateProperty(callback: ((target: Class, name: string, index?: any) => any), option?: DecoratorOption): CustomPropertyDecorator
export function decorateProperty(data: any, option?: DecoratorOption): CustomPropertyDecorator
export function decorateProperty(data: any, option?: DecoratorOption) {
return (target: any, name: string | symbol, index?: any) => {
if (typeof index === "number")
decorateParameter(data, option)(target, name, index)
else
decorateMethod(data, option)(target, name, index)
}
}
/**
* Add metadata information on class specified
*/
export function decorateClass(callback: ((target: Class) => any), option?: DecoratorOption): ClassDecorator
export function decorateClass(data: any, option?: DecoratorOption): ClassDecorator
export function decorateClass(data: any, option?: DecoratorOption) {
return (target: any) => {
const meta = typeof data === "function" ? data(target) : data
setMetadata({ ...meta, [DecoratorOptionId]: { ...meta[DecoratorOptionId], ...option } }, target)
}
}
/**
* Add metadata information on specified declaration, can be applied to class, property, method, or parameter
*/
export function decorate(data: any | ((...args: any[]) => any), targetTypes: DecoratorTargetType[] = [], option?: Partial<DecoratorOption>) {
const throwIfNotOfType = (target: DecoratorTargetType) => {
if (targetTypes.length > 0 && !targetTypes.some(x => x === target))
throw new Error(`Reflect Error: Decorator of type ${targetTypes.join(", ")} applied into ${target}`)
}
return (...args: any[]) => {
//class decorator
if (args.length === 1) {
throwIfNotOfType("Class")
return decorateClass(data, option)(args[0])
}
//parameter decorator
if (args.length === 3 && typeof args[2] === "number") {
throwIfNotOfType("Parameter")
return decorateParameter(data, option)(args[0], args[1], args[2])
}
//property
if (args[2] === undefined || args[2].get || args[2].set) {
throwIfNotOfType("Property")
return decorateProperty(data, option)(args[0], args[1], args[2])
}
throwIfNotOfType("Method")
return decorateMethod(data, option)(args[0], args[1], args[2])
}
}
/**
* Compose multiple metadata decorators into single decorator.
*
* ```
* function merged() {
* return mergeDecorator(decoratorOne(), decoratorTwo(), decoratorThree())
* }
*
* @merged()
* class TargetClass {
* }
* ```
*/
export function mergeDecorator(...fn: (ClassDecorator | PropertyDecorator | CustomPropertyDecorator | ParameterDecorator | MethodDecorator)[]) {
return (...args: any[]) => {
fn.forEach(x => (x as Function)(...args))
}
}
const symIgnore = Symbol("ignore")
const symOverride = Symbol("override")
const symParamProp = Symbol("paramProp")
const symNoop = Symbol("noop")
export function ignore() {
return decorate(<PrivateDecorator>{ [DecoratorId]: symIgnore, kind: "Ignore" }, ["Parameter", "Method", "Property"], { allowMultiple: false })
}
/**
* Add metadata information about data type information
* @param type Data type specified, A class or a callback function returned class for defer evaluation
* @param genericArguments List of generic type arguments
*/
export function type(type: TypeOverride | ((x: any) => TypeOverride), ...genericArguments: (string | string[] | Class | Class[])[]) {
return decorate((target: any) => <TypeDecorator>{ [DecoratorId]: symOverride, kind: "Override", type, genericArguments: genericArguments, target }, ["Parameter", "Method", "Property"], { inherit: true, allowMultiple: false })
}
/**
* No operation decorator, this decorator does nothing except it use to force the TypeScript emit type information
*/
export function noop() {
// type is not inheritable because derived class can define their own type override
return decorate((target: any) => <NoopDecorator>{ [DecoratorId]: symNoop, kind: "Noop", target }, undefined, { inherit: false, allowMultiple: false })
}
/**
* Add metadata information that all parameters of specified class is a parameter properties
*/
export function parameterProperties() {
return decorateClass(<ParameterPropertiesDecorator>{ [DecoratorId]: symParamProp, type: "ParameterProperties" }, { allowMultiple: false })
}
export namespace generic {
const symGenericType = Symbol("genericType")
const symGenericTemplate = Symbol("genericTemplate")
/**
* Add metadata information of generic type parameters
* @param parameters list of generic type parameters
*/
export function parameter(...parameters: string[]) {
return decorateClass(target => <GenericTypeParameterDecorator>{ [DecoratorId]: symGenericTemplate, kind: "GenericTemplate", templates: parameters, target }, { inherit: false, allowMultiple: false })
}
/**
* Add metadata information of generic type arguments
* @param types list of generic type arguments
*/
export function argument(...types: TypeOverride[]) {
return decorateClass(target => <GenericTypeArgumentDecorator>{ [DecoratorId]: symGenericType, kind: "GenericType", types, target }, { inherit: false, allowMultiple: false })
}
/**
* Create generic class dynamically
* @param parent Super class that the class inherited from
* @param params List of generic type parameters
*/
export function create<T extends Class>(parent: T | { extends: T, name: string }, ...params: TypeOverride[]) {
const opt = (typeof parent === "object") ? parent : { extends: parent, name: "DynamicType" }
const Type = createClass({}, { ...opt, genericParams: params })
return Type
}
/**
* Get data type of declaration in specific class based on its type specified by type("T")
* @param decorator type() decorator contains generic type information
* @param typeTarget The current type where the type will be calculated
* @returns
*/
export function getType(decorator: { type: TypeOverride | ((x: any) => TypeOverride), target: Class }, typeTarget: Class): Class | Class[] | undefined {
const getParent = (type: Class): Class[] => {
const parent: Class = Object.getPrototypeOf(type)
if (type === decorator.target) return []
return [...getParent(parent), type]
}
const getTemplate = (target: Class): GenericTypeParameterDecorator | undefined => {
const meta = getMetadata(target)
.find((x: GenericTypeParameterDecorator): x is GenericTypeParameterDecorator => x.kind === "GenericTemplate")
if (meta) return meta
// if not found walk through the parent to get the parameter decorator
const parent: Class = Object.getPrototypeOf(target)
return parent.prototype ? getTemplate(parent) : undefined
}
if (typeTarget === decorator.target) return
if (!(typeTarget.prototype instanceof decorator.target))
throw new Error(`Unable to get type information because ${typeTarget.name} is not inherited from ${decorator.target.name}`)
const [type, isArray] = reflection.getTypeFromDecorator(decorator)
if (typeof type !== "string")
throw new Error("Provided decorator is not a generic type")
let templateDec = getTemplate(decorator.target)
if (!templateDec)
throw new Error(`${decorator.target.name} doesn't have @generic.parameter() decorator required by generic parameter ${type}`)
/*
get list of parents, for example
A <-- B <-- C <-- D (A is super super)
const result = getParent(D)
result = [B, C, D]
*/
const types = getParent(typeTarget)
let tmpType = decorator.target
let result = type
for (const type of types) {
// get the index of type in @generic.parameter() list
const index = templateDec.templates.indexOf(result)
const typeDec = getMetadata(type)
.find((x: GenericTypeArgumentDecorator): x is GenericTypeArgumentDecorator => x.kind === "GenericType")
if (typeDec) {
if (typeDec.types.length !== templateDec.templates.length)
throw new Error(`Number of parameters @generic.parameter() and @generic.argument() mismatch between ${tmpType.name} and ${type.name}`)
// get the actual type in @generic.argument() list
result = typeDec.types[index] as any
// check if the result is a "function" (Class) then return immediately
const finalResult = isArray ? [result] : result
const singleResult = Array.isArray(result) ? result[0] : result
if (typeof singleResult === "function") return finalResult as any as (Class | Class[])
}
// continue searching other template
const templates = getTemplate(type)
tmpType = type
templateDec = templates!
}
}
/**
* Get list of generic arguments used in class
* @param type the class
* @returns List of generic type parameters
*/
export function getArguments(type: Class): Class[] {
const genericDecorator = getMetadata(type)
.find((x: GenericTypeArgumentDecorator): x is GenericTypeArgumentDecorator => x.kind == "GenericType" && x.target === type)
if (!genericDecorator) {
const parent: Class = Object.getPrototypeOf(type)
if (!parent.prototype) throw new Error(`${type.name} is not a generic type`)
return getArguments(parent)
}
return genericDecorator.types.map(x => x as Class)
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [sqlworkbench](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssqlworkbench.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Sqlworkbench extends PolicyStatement {
public servicePrefix = 'sqlworkbench';
/**
* Statement provider for service [sqlworkbench](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssqlworkbench.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
*
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toAssociateConnectionWithChart() {
return this.to('AssociateConnectionWithChart');
}
/**
*
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toAssociateConnectionWithTab() {
return this.to('AssociateConnectionWithTab');
}
/**
*
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toAssociateQueryWithTab() {
return this.to('AssociateQueryWithTab');
}
/**
* Grants permission to delete folders on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toBatchDeleteFolder() {
return this.to('BatchDeleteFolder');
}
/**
* Grants permission to create SQLWorkbench account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toCreateAccount() {
return this.to('CreateAccount');
}
/**
* Grants permission to create new saved chart on your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toCreateChart() {
return this.to('CreateChart');
}
/**
* Grants permission to create a new connection on your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toCreateConnection() {
return this.to('CreateConnection');
}
/**
* Grants permission to create folder on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toCreateFolder() {
return this.to('CreateFolder');
}
/**
* Grants permission to create a new saved query on your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toCreateSavedQuery() {
return this.to('CreateSavedQuery');
}
/**
* Grants permission to remove charts on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toDeleteChart() {
return this.to('DeleteChart');
}
/**
* Grants permission to remove connections on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toDeleteConnection() {
return this.to('DeleteConnection');
}
/**
* Grants permission to remove saved queries on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toDeleteSavedQuery() {
return this.to('DeleteSavedQuery');
}
/**
* Grants permission to remove a tab on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toDeleteTab() {
return this.to('DeleteTab');
}
/**
* Grants permission to execute a query in your redshift cluster
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toDriverExecute() {
return this.to('DriverExecute');
}
/**
* Grants permission to generate a new session on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGenerateSession() {
return this.to('GenerateSession');
}
/**
* Grants permission to get account info
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGetAccountInfo() {
return this.to('GetAccountInfo');
}
/**
* Grants permission to get charts on your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGetChart() {
return this.to('GetChart');
}
/**
* Grants permission to get connections on your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGetConnection() {
return this.to('GetConnection');
}
/**
* Grants permission to describe KMS Keys
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGetKMSKey() {
return this.to('GetKMSKey');
}
/**
* Grants permission to get saved query on your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGetSavedQuery() {
return this.to('GetSavedQuery');
}
/**
* Grants permission to get user info
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGetUserInfo() {
return this.to('GetUserInfo');
}
/**
* Grants permission to get workspace settings on your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toGetUserWorkspaceSettings() {
return this.to('GetUserWorkspaceSettings');
}
/**
* Grants permission to list buckets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListBuckets() {
return this.to('ListBuckets');
}
/**
* Grants permission to list the connections on your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListConnections() {
return this.to('ListConnections');
}
/**
* Grants permission to list databases of your redshift cluster
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListDatabases() {
return this.to('ListDatabases');
}
/**
* Grants permission to list files and folders
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListFiles() {
return this.to('ListFiles');
}
/**
* Grants permission to list KMS Key Aliases
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListKMSKeyAliases() {
return this.to('ListKMSKeyAliases');
}
/**
* Grants permission to list KMS Keys
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListKMSKeys() {
return this.to('ListKMSKeys');
}
/**
* Grants permission to list redshift clusters on your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListRedshiftClusters() {
return this.to('ListRedshiftClusters');
}
/**
* Grants permission to list sample databases
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListSampleDatabases() {
return this.to('ListSampleDatabases');
}
/**
* Grants permission to list versions of saved query on your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListSavedQueryVersions() {
return this.to('ListSavedQueryVersions');
}
/**
* Grants permission to list tabs on your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListTabs() {
return this.to('ListTabs');
}
/**
* Grants permission to list the tags of an sqlworkbench resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to create or update a tab on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toPutTab() {
return this.to('PutTab');
}
/**
* Grants permission to update workspace settings on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toPutUserWorkspaceSettings() {
return this.to('PutUserWorkspaceSettings');
}
/**
* Grants permission to tag an sqlworkbench resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to untag an sqlworkbench resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a chart on your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toUpdateChart() {
return this.to('UpdateChart');
}
/**
* Grants permission to update a connection on your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toUpdateConnection() {
return this.to('UpdateConnection');
}
/**
* Grants permission to move files on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toUpdateFileFolder() {
return this.to('UpdateFileFolder');
}
/**
* Grants permission to update a folder's name and details on your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toUpdateFolder() {
return this.to('UpdateFolder');
}
/**
* Grants permission to update a saved query on your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html
*/
public toUpdateSavedQuery() {
return this.to('UpdateSavedQuery');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateConnectionWithChart",
"AssociateConnectionWithTab",
"AssociateQueryWithTab",
"BatchDeleteFolder",
"CreateAccount",
"CreateChart",
"CreateConnection",
"CreateFolder",
"CreateSavedQuery",
"DeleteChart",
"DeleteConnection",
"DeleteSavedQuery",
"DeleteTab",
"DriverExecute",
"GenerateSession",
"PutTab",
"PutUserWorkspaceSettings",
"UpdateChart",
"UpdateConnection",
"UpdateFileFolder",
"UpdateFolder",
"UpdateSavedQuery"
],
"Read": [
"GetAccountInfo",
"GetChart",
"GetConnection",
"GetKMSKey",
"GetSavedQuery",
"GetUserInfo",
"GetUserWorkspaceSettings",
"ListBuckets",
"ListSampleDatabases",
"ListTagsForResource"
],
"List": [
"ListConnections",
"ListDatabases",
"ListFiles",
"ListKMSKeyAliases",
"ListKMSKeys",
"ListRedshiftClusters",
"ListSavedQueryVersions",
"ListTabs"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type connection to the statement
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/query-editor-v2.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onConnection(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:sqlworkbench:${Region}:${Account}:connection/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type query to the statement
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/query-editor-v2.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onQuery(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:sqlworkbench:${Region}:${Account}:query/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type chart to the statement
*
* https://docs.aws.amazon.com/redshift/latest/mgmt/query-editor-v2.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onChart(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:sqlworkbench:${Region}:${Account}:chart/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { settingsController, translations, cordovaFS, DocumentSelection } from "..";
/**
* Handles export / import saved games
*/
export class SavedGamesExport {
/**
* The Cordova persistent file system
*/
private fs: FileSystem = null;
/**
* Saved games file entries
*/
private fileGameEntries: Entry[] = null;
/**
* Temporal directory
*/
private tmpDir: DirectoryEntry = null;
/**
* Files to delete after the process end
*/
private filesToDeleteAtEnd: FileEntry[] = [];
/** Number of imported games */
public nImportedGames = 0;
/**
* Export saved games to Download directory
* @returns Promise with the export process
*/
public export(): JQueryPromise<void> {
const self = this;
let zipPath: string = null;
const zipFileName = "KaiChroniclesExport-" + settingsController.getDateForFileNames() + ".zip";
const process = this.setup()
.then(() => {
// Return a human readable error if there are no files to export:
if (self.fileGameEntries.length === 0) {
return jQuery.Deferred().reject(translations.text("noGamesToExport")).promise();
} else {
return jQuery.Deferred().resolve().promise();
}
})
.then(() => {
console.log("Copying file games to tmp dir (" + self.fileGameEntries.length + ")");
return cordovaFS.copySetToAsync(self.fileGameEntries, self.tmpDir);
})
.then(() => {
// Create the zip. If it's created on the tmp directory, the zip creation will fail
console.log("Creating zip file on root directory");
zipPath = self.fs.root.toURL() + zipFileName;
return cordovaFS.zipAsync(self.tmpDir.toURL(), zipPath);
})
.then(() => {
console.log("Get the zip file entry");
return cordovaFS.getFileAsync(self.fs.root, zipFileName);
})
.then((entry) => {
// This generated zip file will be removed at the end of the process
self.filesToDeleteAtEnd.push(entry);
console.log("Copying the zip to Download directory");
// Copy the zip
return cordovaFS.copyToDownloadAsync(zipPath, zipFileName, "Kai Chronicles saved games export", "application/zip");
});
// Cleant tmp files
return this.clean(process);
}
/**
* Import saved games from a file
* @param doc File with the games to import
* @returns Promise with the export process. Parameter is the number of imported games
*/
public import(doc: DocumentSelection): JQueryPromise<number> {
const self = this;
const process = this.setup()
.then(() => {
// Get the file type. It can be a zip file or a json file
// TODO: Check the mime type too?
const nameAndExtension = cordovaFS.getFileNameAndExtension(doc.fileName.toLowerCase());
if (nameAndExtension.extension === "zip") {
return self.importZip(doc);
} else if (nameAndExtension.extension === "json") {
return self.importJson(doc);
} else {
// Wrong extension
return jQuery.Deferred().reject(translations.text("importExtensionsError")).promise();
}
});
// Cleant tmp files
return this.clean(process);
}
/**
* Import saved games from a zip file
* @param doc File with the games to import
* @returns Promise with the import process. Parameter is the number of imported games
*/
private importZip(doc: DocumentSelection): JQueryPromise<number> {
const self = this;
let nNewGames = 0;
const zipContent: any = null;
let entriesToImport: any[] = null;
return this.copyFileContent(doc, this.tmpDir)
.then((zipFileEntryOnTmpDir: FileEntry) => {
console.log("Unziping file on tmp directory");
return cordovaFS.unzipAsync(zipFileEntryOnTmpDir.toURL(), self.tmpDir.toURL());
})
.then(() => {
console.log("Get unziped files");
return cordovaFS.readEntriesAsync(self.tmpDir);
})
.then((entries: Entry[]) => {
console.log("Filtering unziped files");
entriesToImport = SavedGamesExport.filterSavedGamesEntries(entries);
// Check if some file will be overwritten
const newFileNames: string[] = [];
for (const entry of entriesToImport) {
newFileNames.push(entry.name);
}
return self.checkOverwritting(newFileNames);
})
.then(() => {
console.log("Copying saved games to the root");
nNewGames = entriesToImport.length;
return cordovaFS.copySetToAsync(entriesToImport, self.fs.root);
})
.then(() => {
// Notify the number of imported games
self.nImportedGames = nNewGames;
return jQuery.Deferred<number>().resolve(nNewGames).promise();
});
}
/**
* Import a saved game file
* @param doc File with the saved game to import
* @returns Promise with the import process. Parameter is the number of imported games
*/
private importJson(doc: DocumentSelection): JQueryPromise<number> {
const self = this;
return self.checkOverwritting([doc.fileName])
.then(() => {
// Create the json file
return self.copyFileContent(doc, self.fs.root);
})
.then(() => {
// Notify the number of imported games
self.nImportedGames = 1;
return jQuery.Deferred<number>().resolve(1).promise();
});
}
/**
* Check if some file will be overwritten on import
* @param newFiles File names to import
* @returns Promise with the user confirmation to continue the process
*/
private checkOverwritting(newFiles: string[]): JQueryPromise<void> {
const duplicatedFiles: string[] = [];
for (const newFile of newFiles) {
for (const oldFile of this.fileGameEntries) {
// Case sensitive
if (oldFile.name === newFile) {
duplicatedFiles.push(newFile);
}
}
}
const dfd = jQuery.Deferred<void>();
if (duplicatedFiles.length === 0) {
// Ok, there will be no duplicates
dfd.resolve();
} else {
const msg = translations.text("confirmSavedOverwrite", [duplicatedFiles.join("\n")]);
if (confirm(msg)) {
dfd.resolve();
} else {
dfd.reject("Import cancelled");
}
}
return dfd.promise();
}
/**
* Copy a file content to other directory
* @param doc The file to copy
* @param parent Directory where to create the new file
*/
private copyFileContent(doc: DocumentSelection, parent: DirectoryEntry): JQueryPromise<FileEntry> {
// TODO: There must be something wrong with my code or with Cordova @types:
// cordovaFS.readFileAsync here should return an ArrayBuffer and FileWriter.write() call in cordovaFS.writeFileContentAsync
// expects a Blob. ArrayBuffer and Blob are not compatible between them (you cannot assign one to other)
// But it works... So I keep fileContent as "any".... ¯\_(ツ)_/¯
let fileContent: any = null;
// Well, the Entry returned by window.resolveLocalFileSystemURI( doc.uri ) is not really a FileEntry: It cannot be
// copied with "copyTo". I suspect it's because is not a "file://" URL (it's a "content://").
// So, get the file content, and create the the file on the tmp directory manually
// Well, second part, oh... If you pick a file with the "File Explorer", you get a "file://" uri, and the readFileAsync does not work...
// Who knows why. The error code is 1 (not found). Also, "copyToAsync" fails (or "resolveLocalFileSystemURIAsync") if sems to fail
// with a URL outside the app content. So, I have created a external plugin function.
if (doc.uri.toLowerCase().startsWith("file://")) {
console.log("Copy zip to the tmp directory");
return cordovaFS.copyNativePathsAsync(doc.uri, parent.toURL());
} else {
return cordovaFS.resolveLocalFileSystemURIAsync(doc.uri)
// THIS DOES NOT WORK FOR "content://" entries
// .then( function( entry /* : Entry */ ) {
// console.log( 'Copy zip to the tmp directory' );
// return cordovaFS.copyToAsync( entry , self.tmpDir , doc.fileName )
// })
.then((entry: Entry) => {
console.log("Reading file content");
return cordovaFS.readFileAsync(entry as FileEntry, true);
})
.then((content) => {
fileContent = content;
console.log("Creating empty file");
return cordovaFS.getFileAsync(parent, doc.fileName, { create: true, exclusive: false });
})
.then((newFileEntry: FileEntry) => {
console.log("Save the file content");
return cordovaFS.writeFileContentAsync(newFileEntry, fileContent);
});
}
}
/**
* Check file entries, get those that are saved games
* @param entries File entries to check
* @returns The saved games
*/
private static filterSavedGamesEntries(entries: Entry[]): Entry[] {
const result = [];
for (const entry of entries) {
let ok = true;
if (!entry.isFile) {
ok = false;
}
if (cordovaFS.getFileNameAndExtension(entry.name).extension.toLowerCase() !== "json") {
ok = false;
}
if (ok) {
result.push(entry);
}
}
return result;
}
/**
* Setup current instance members
* @returns Promise with the members setup process
*/
private setup(): JQueryPromise<void> {
const self = this;
// Retrieve a FS and the saved games
return cordovaFS.requestFileSystemAsync()
.then((fileSystem: FileSystem) => {
self.fs = fileSystem;
// Get save game files
console.log("Get save game files");
return cordovaFS.getRootFilesAsync(fileSystem);
})
.then((entries: Entry[]) => {
console.log("Storing saved games entries");
// Store saved games, and ignore others. There can be directories here (ex. downloaded books)
self.fileGameEntries = SavedGamesExport.filterSavedGamesEntries(entries);
// Re-create the tmp directory
return self.createTmpDirectory();
})
.then((tmpDirEntry) => {
// Store the tmp directory entry
self.tmpDir = tmpDirEntry;
});
}
/**
* Re-create the temporal directory
* @returns The process
*/
private createTmpDirectory(): JQueryPromise<DirectoryEntry> {
const self = this;
const dirName = "tmpKaiChronicles";
// Check if the directory exists
return cordovaFS.getDirectoryAsync(this.fs.root, dirName, { create: false })
.then(
(dirEntry) => {
// Directory exists. Remove it
console.log("Deleting previous tmp directory");
return cordovaFS.deleteDirRecursivelyAsync(dirEntry);
},
(errorDirDontExists) => {
// Directory does not exists. Do nothing
return jQuery.Deferred().resolve().promise();
}
)
.then(() => {
// Create the directory
console.log("Creating tmp directory");
return cordovaFS.getDirectoryAsync(self.fs.root, dirName, { create: true });
});
}
/**
* Add execution to clean the generated tmp files
* @param process The process to run
* @returns The "process" parameter
*/
private clean(process: JQueryPromise<any>): JQueryPromise<any> {
const self = this;
// This is horrifying. Any better way to do it???
// Delete tmp files in any case (success or error)
return process
.then(
// Ok. Clean
self.cleanTmpFiles.bind(self),
(error) => {
// Error happened. Clean and return the PREVIOUS error
return self.cleanTmpFiles()
.then(
() => jQuery.Deferred().reject(error).promise(),
() => jQuery.Deferred().reject(error).promise()
);
}
);
}
/**
* Delete the temporal directory and other generated tmp files
* @returns The deletion process
*/
private cleanTmpFiles(): JQueryPromise<void> {
// Delete tmp directory
let rootPromise;
if (!this.tmpDir) {
console.log("No tmp dir stored");
// Nothing to do
rootPromise = jQuery.Deferred().resolve().promise();
} else {
console.log("Deleting tmp directory");
rootPromise = cordovaFS.deleteDirRecursivelyAsync(this.tmpDir);
}
// Delete other tmp files
const self = this;
return rootPromise
.then(() => {
console.log("Deleting other tmp files");
const promises: Array<JQueryPromise<any>> = [];
for (const tmpFile of self.filesToDeleteAtEnd) {
promises.push(cordovaFS.deleteFileAsync(tmpFile));
}
// Wait for all deletions to finish
return $.when.apply($, promises);
});
}
} | the_stack |
import { Component, h, ComponentInterface, Prop, Event, EventEmitter, Host, State, Watch, Element } from '@stencil/core'
import classNames from 'classnames'
import {
hoursRange,
minutesRange,
compareTime,
verifyValue,
verifyTime,
verifyDate,
getYearRange,
getMonthRange,
getDayRange,
formatValue
} from './utils'
import {
TOP,
LINE_HEIGHT
} from './constant'
export type Mode = 'selector' | 'multiSelector' | 'time' | 'date'
export type Fields = 'day' | 'month' | 'year'
export type PickerValue = number | number[] | string
export interface PickerDate {
_value: Date
_start: Date
_end: Date
_updateValue: [number, number, number]
}
@Component({
tag: 'taro-picker-core',
styleUrl: './style/index.scss'
})
export class Picker implements ComponentInterface {
private index: number[] = []
private pickerDate: PickerDate
private overlay?: HTMLElement
@Element() el: HTMLElement
@Prop() mode: Mode = 'selector'
@Prop() disabled = false
@Prop() range: any[] = []
@Prop() rangeKey: string
@Prop() value: number | number[] | string
@Prop() start = ''
@Prop() end = ''
@Prop() fields: Fields = 'day'
@Prop() name = ''
@State() pickerValue: PickerValue = []
@State() height: number[] = []
@State() hidden = true
@State() fadeOut = false
@State() isWillLoadCalled = false
@Event({
eventName: 'change'
}) onChange: EventEmitter
@Event({
eventName: 'columnchange'
}) onColumnChange: EventEmitter
@Event({
eventName: 'cancel'
}) onCancel: EventEmitter
componentWillLoad () {
this.isWillLoadCalled = true
this.handleProps()
}
componentDidLoad () {
Object.defineProperty(this.el, 'value', {
get: () => this.pickerValue,
set: val => (this.value = val),
configurable: true
})
if (this.overlay) {
document.body.appendChild(this.overlay)
}
}
disconnectedCallback () {
if (this.overlay) {
this.overlay.parentNode?.removeChild(this.overlay)
}
}
@Watch('mode')
@Watch('value')
@Watch('range')
@Watch('start')
@Watch('end')
onPropsChange () {
if (!this.isWillLoadCalled) return
this.handleProps()
}
handleProps () {
const { mode, start, end } = this
if (mode === 'selector') {
const value = this.value as number
this.index = [verifyValue(value, this.range) ? Math.floor(value) : 0]
} else if (mode === 'multiSelector') {
const value = this.value as number[]
this.index = []
this.range.forEach((range, index) => {
const val = value?.[index]
const item = verifyValue(val, range as any[]) ? Math.floor(val) : 0
this.index.push(item)
})
} else if (mode === 'time') {
let value = this.value as string
// check value...
if (!verifyTime(value)) {
console.warn('time picker value illegal')
value = '0:0'
}
const time = value.split(':').map(n => +n)
this.index = time
} else if (mode === 'date') {
const value = this.value as string
const _value = verifyDate(value) || new Date(new Date().setHours(0, 0, 0, 0)) // 没传值或值的合法性错误默认今天时间
const _start = verifyDate(start) || new Date('1970/01/01')
const _end = verifyDate(end) || new Date('2999/01/01')
// 时间区间有效性
if (_value >= _start && _value <= _end) {
const currentYear = _value.getFullYear()
const currentMonth = _value.getMonth() + 1
const currentDay = _value.getDate()
const yearRange = getYearRange(_start.getFullYear(), _end.getFullYear())
const monthRange = getMonthRange(_start, _end, currentYear)
const dayRange = getDayRange(_start, _end, currentYear, currentMonth)
this.index = [
yearRange.indexOf(currentYear),
monthRange.indexOf(currentMonth),
dayRange.indexOf(currentDay)
]
if (
!this.pickerDate ||
this.pickerDate._value.getTime() !== _value.getTime() ||
this.pickerDate._start.getTime() !== _start.getTime() ||
this.pickerDate._end.getTime() !== _end.getTime()
) {
this.pickerDate = {
_value,
_start,
_end,
_updateValue: [
currentYear,
currentMonth,
currentDay
]
}
}
} else {
throw new Error('Date Interval Error')
}
}
// Prop 变化时,无论是否正在显示弹层,都更新 height 值
this.height = this.getHeightByIndex()
// 同步表单 value 值,用于 form submit
this.pickerValue = this.value
if (mode === 'date') {
const val = this.pickerValue as string
if (this.fields === 'month') {
this.pickerValue = val.split('-').slice(0, 2).join('-')
} else if (this.fields === 'year') {
this.pickerValue = val.split('-')[0]
}
}
}
// 展示 Picker
showPicker = () => {
if (this.disabled) return
this.height = this.getHeightByIndex()
this.hidden = false
}
getHeightByIndex = () => {
const height = this.index.map(i => {
let factor = 0
if (this.mode === 'time') {
factor = LINE_HEIGHT * 4
}
return TOP - LINE_HEIGHT * i - factor
})
return height
}
// 隐藏 picker
hidePicker = () => {
this.fadeOut = true
setTimeout(() => {
this.hidden = true
this.fadeOut = false
}, 350)
}
// 点击确定按钮
handleChange = () => {
this.hidePicker()
this.index = this.height.map(h => (TOP - h) / LINE_HEIGHT)
let value: PickerValue = this.index.length && this.mode !== 'selector'
? this.index
: this.index[0]
if (this.mode === 'time') {
const range = [hoursRange.slice(), minutesRange.slice()]
const timeArr = this.index.map<string>((n, i) => range[i][n])
this.index = timeArr.map(item => parseInt(item))
value = timeArr.join(':')
}
if (this.mode === 'date') {
const { _start, _end, _updateValue } = this.pickerDate
const currentYear = _updateValue[0]
const currentMonth = _updateValue[1]
const yearRange = getYearRange(_start.getFullYear(), _end.getFullYear())
const monthRange = getMonthRange(_start, _end, currentYear)
const dayRange = getDayRange(_start, _end, currentYear, currentMonth)
const year = yearRange[this.index[0]]
const month = monthRange[this.index[1]]
const day = dayRange[this.index[2]]
if (this.fields === 'year') {
value = [year]
} else if (this.fields === 'month') {
value = [year, month]
} else {
value = [year, month, day]
}
value = value
.map(item => {
return item < 10 ? `0${item}` : item
})
.join('-')
}
this.pickerValue = value
this.onChange.emit({
value
})
}
// 点击取消按钮或蒙层
handleCancel = () => {
this.hidePicker()
this.onCancel.emit()
}
updateHeight = (height: number, columnId: string, needRevise = false) => {
const temp = [...this.height]
temp[columnId] = height
this.height = temp
// time picker 必须在规定时间范围内,因此需要在 touchEnd 做修正
if (needRevise) {
let { start, end } = this
if (!verifyTime(start)) start = '00:00'
if (!verifyTime(end)) end = '23:59'
if (!compareTime(start, end)) return
const range = [hoursRange.slice(), minutesRange.slice()]
const timeList = this.height.map(h => (TOP - h) / LINE_HEIGHT)
const timeStr = timeList.map((n, i) => range[i][n]).join(':')
if (!compareTime(start, timeStr)) {
// 修正到 start
const height = start
.split(':')
.map(i => TOP - LINE_HEIGHT * (+i + 4))
requestAnimationFrame(() => (this.height = height))
} else if (!compareTime(timeStr, end)) {
// 修正到 end
const height = end
.split(':')
.map(i => TOP - LINE_HEIGHT * (+i + 4))
requestAnimationFrame(() => (this.height = height))
}
}
}
handleColumnChange = (height: number, columnId: string) => {
this.onColumnChange.emit({
column: Number(columnId),
value: (TOP - height) / LINE_HEIGHT
})
}
updateDay = (value: number, fields: number) => {
const { _start, _end, _updateValue } = this.pickerDate
_updateValue[fields] = value
const currentYear = _updateValue[0]
const currentMonth = _updateValue[1]
const currentDay = _updateValue[2]
// 滚动年份
if (fields === 0) {
const monthRange = getMonthRange(_start, _end, currentYear)
const max = monthRange[monthRange.length - 1]
const min = monthRange[0]
if (currentMonth > max) _updateValue[1] = max
if (currentMonth < min) _updateValue[1] = min
const index = monthRange.indexOf(_updateValue[1])
const height = TOP - LINE_HEIGHT * index
this.updateDay(_updateValue[1], 1)
this.updateHeight(height, '1')
} else if (fields === 1) {
const dayRange = getDayRange(_start, _end, currentYear, currentMonth)
const max = dayRange[dayRange.length - 1]
const min = dayRange[0]
if (currentDay > max) _updateValue[2] = max
if (currentDay < min) _updateValue[2] = min
const index = dayRange.indexOf(_updateValue[2])
const height = TOP - LINE_HEIGHT * index
this.updateDay(_updateValue[2], 2)
this.updateHeight(height, '2')
}
}
// 单列选择器
getSelector = () => {
return (
<taro-picker-group
range={this.range}
rangeKey={this.rangeKey}
height={this.height[0]}
updateHeight={this.updateHeight}
columnId='0'
/>
)
}
// 多列选择器
getMultiSelector = () => {
return this.range.map((range, index) => {
return (
<taro-picker-group
range={range}
rangeKey={this.rangeKey}
height={this.height[index]}
updateHeight={this.updateHeight}
onColumnChange={this.handleColumnChange}
columnId={String(index)}
/>
)
})
}
// 时间选择器
getTimeSelector = () => {
const hourRange = hoursRange.slice()
const minRange = minutesRange.slice()
return [
<taro-picker-group
mode='time'
range={hourRange}
height={this.height[0]}
updateHeight={this.updateHeight}
columnId='0'
/>,
<taro-picker-group
mode='time'
range={minRange}
height={this.height[1]}
updateHeight={this.updateHeight}
columnId='1'
/>
]
}
// 日期选择器
getDateSelector = () => {
const { fields, height } = this
const { _start, _end, _updateValue } = this.pickerDate
const currentYear = _updateValue[0]
const currentMonth = _updateValue[1]
const yearRange = getYearRange(_start.getFullYear(), _end.getFullYear())
.map(item => `${item}年`)
const monthRange = getMonthRange(_start, _end, currentYear)
.map(item => `${item < 10 ? `0${item}` : item}月`)
const dayRange = getDayRange(_start, _end, currentYear, currentMonth)
.map(item => `${item < 10 ? `0${item}` : item}日`)
const renderView = [
<taro-picker-group
mode='date'
range={yearRange}
height={height[0]}
updateDay={this.updateDay}
updateHeight={this.updateHeight}
columnId='0'
/>
]
if (fields === 'month' || fields === 'day') {
renderView.push(
<taro-picker-group
mode='date'
range={monthRange}
height={height[1]}
updateDay={this.updateDay}
updateHeight={this.updateHeight}
columnId='1'
/>
)
}
if (fields === 'day') {
renderView.push(
<taro-picker-group
mode='date'
range={dayRange}
height={height[2]}
updateDay={this.updateDay}
updateHeight={this.updateHeight}
columnId='2'
/>
)
}
return renderView
}
render () {
const {
name,
mode,
fadeOut,
hidden
} = this
// 选项条
let pickerGroup
switch (mode) {
case 'multiSelector':
pickerGroup = this.getMultiSelector()
break
case 'time':
pickerGroup = this.getTimeSelector()
break
case 'date':
pickerGroup = this.getDateSelector()
break
default:
pickerGroup = this.getSelector()
}
// 动画类名控制逻辑
const clsMask = classNames('weui-mask', 'weui-animate-fade-in', {
'weui-animate-fade-out': fadeOut
})
const clsSlider = classNames('weui-picker', 'weui-animate-slide-up', {
'weui-animate-slide-down': fadeOut
})
const shouldDivHidden = hidden ? { display: 'none' } : {}
return (
<Host>
<div onClick={this.showPicker}>
<slot />
<input type='hidden' name={name} value={formatValue(this.pickerValue)} />
</div>
<div
class='weui-picker__overlay'
style={shouldDivHidden}
ref={el => { this.overlay = el }}
>
<div class={clsMask} onClick={this.handleCancel} />
<div class={clsSlider}>
<div class='weui-picker__hd'>
<div class='weui-picker__action' onClick={this.handleCancel}>
取消
</div>
<div class='weui-picker__action' onClick={this.handleChange}>
确定
</div>
</div>
<div class='weui-picker__bd'>{pickerGroup}</div>
<input type='hidden' name={name} value={formatValue(this.pickerValue)} />
</div>
</div>
</Host>
)
}
} | the_stack |
import { EventEmitter } from "events";
import { ClientOptions } from "../ClientOptions";
import { IClient } from "../IClient";
import { Level2Point } from "../Level2Point";
import { Level2Snapshot } from "../Level2Snapshots";
import { Level2Update } from "../Level2Update";
import { Market } from "../Market";
import { NotImplementedFn } from "../NotImplementedFn";
import { SmartWss } from "../SmartWss";
import { Ticker } from "../Ticker";
import { Trade } from "../Trade";
export type GeminiSubscription = {
market: Market;
wss: SmartWss;
lastMessage: any;
reconnectIntervalHandle: number;
remoteId: string;
trades: boolean;
level2updates: boolean;
tickers: boolean;
};
export class GeminiClient extends EventEmitter implements IClient {
public wssPath: string;
public name: string;
public reconnectIntervalMs: number;
public tickersCache: Map<string, Ticker>;
public readonly hasTickers: boolean;
public readonly hasTrades: boolean;
public readonly hasCandles: boolean;
public readonly hasLevel2Snapshots: boolean;
public readonly hasLevel2Updates: boolean;
public readonly hasLevel3Snapshots: boolean;
public readonly hasLevel3Updates: boolean;
protected _subscriptions: Map<string, GeminiSubscription>;
constructor({ wssPath, watcherMs = 30000 }: ClientOptions = {}) {
super();
this.wssPath = wssPath;
this.name = "Gemini";
this._subscriptions = new Map();
this.reconnectIntervalMs = watcherMs;
this.tickersCache = new Map(); // key-value pairs of <market_id>: Ticker
this.hasTickers = true;
this.hasTrades = true;
this.hasCandles = false;
this.hasLevel2Snapshots = false;
this.hasLevel2Updates = true;
this.hasLevel3Snapshots = false;
this.hasLevel3Updates = false;
}
public reconnect() {
for (const subscription of this._subscriptions.values()) {
this._reconnect(subscription);
}
}
public subscribeTrades(market: Market) {
this._subscribe(market, "trades");
}
public unsubscribeTrades(market: Market) {
this._unsubscribe(market, "trades");
}
public subscribeLevel2Updates(market: Market) {
this._subscribe(market, "level2updates");
}
public unsubscribeLevel2Updates(market: Market): Promise<void> {
this._unsubscribe(market, "level2updates");
return;
}
public subscribeTicker(market: Market) {
this._subscribe(market, "tickers");
}
public unsubscribeTicker(market: Market): Promise<void> {
this._unsubscribe(market, "tickers");
return;
}
public subscribeCandles = NotImplementedFn;
public unsubscribeCandles = NotImplementedFn;
public subscribeLevel2Snapshots = NotImplementedFn;
public unsubscribeLevel2Snapshots = NotImplementedFn;
public subscribeLevel3Snapshots = NotImplementedFn;
public unsubscribeLevel3Snapshots = NotImplementedFn;
public subscribeLevel3Updates = NotImplementedFn;
public unsubscribeLevel3Updates = NotImplementedFn;
public close() {
this._close();
}
////////////////////////////////////////////
// PROTECTED
protected _subscribe(market: Market, mode: string) {
let remote_id = market.id.toLowerCase();
if (mode === "tickers") remote_id += "-tickers";
let subscription = this._subscriptions.get(remote_id);
if (subscription && subscription[mode]) return;
if (!subscription) {
subscription = {
market,
wss: this._connect(remote_id),
lastMessage: undefined,
reconnectIntervalHandle: undefined,
remoteId: remote_id,
trades: false,
level2updates: false,
tickers: false,
};
this._startReconnectWatcher(subscription);
this._subscriptions.set(remote_id, subscription);
}
subscription[mode] = true;
}
protected _unsubscribe(market: Market, mode: string) {
let remote_id = market.id.toLowerCase();
if (mode === "tickers") remote_id += "-tickers";
const subscription = this._subscriptions.get(remote_id);
if (!subscription) return;
subscription[mode] = false;
if (!subscription.trades && !subscription.level2updates) {
this._close(this._subscriptions.get(remote_id));
this._subscriptions.delete(remote_id);
}
if (mode === "tickers") {
this.tickersCache.delete(market.id);
}
}
/** Connect to the websocket stream by constructing a path from
* the subscribed markets.
*/
protected _connect(remote_id: string) {
const forTickers = remote_id.endsWith("-tickers");
const wssPath =
this.wssPath || forTickers
? `wss://api.gemini.com/v1/marketdata/${remote_id}?heartbeat=true&top_of_book=true`
: `wss://api.gemini.com/v1/marketdata/${remote_id}?heartbeat=true`;
const wss = new SmartWss(wssPath);
wss.on("error", err => this._onError(remote_id, err));
wss.on("connecting", () => this._onConnecting(remote_id));
wss.on("connected", () => this._onConnected(remote_id));
wss.on("disconnected", () => this._onDisconnected(remote_id));
wss.on("closing", () => this._onClosing(remote_id));
wss.on("closed", () => this._onClosed(remote_id));
wss.on("message", raw => {
try {
this._onMessage(remote_id, raw);
} catch (err) {
this._onError(remote_id, err);
}
});
wss.connect();
return wss;
}
/**
* Handles an error
*/
protected _onError(remote_id, err) {
this.emit("error", err, remote_id);
}
/**
* Fires when a socket is connecting
*/
protected _onConnecting(remote_id) {
this.emit("connecting", remote_id);
}
/**
* Fires when connected
*/
protected _onConnected(remote_id) {
const subscription = this._subscriptions.get(remote_id);
if (!subscription) {
return;
}
this._startReconnectWatcher(subscription);
this.emit("connected", remote_id);
}
/**
* Fires when there is a disconnection event
*/
protected _onDisconnected(remote_id) {
this._stopReconnectWatcher(this._subscriptions.get(remote_id));
this.emit("disconnected", remote_id);
}
/**
* Fires when the underlying socket is closing
*/
protected _onClosing(remote_id) {
this._stopReconnectWatcher(this._subscriptions.get(remote_id));
this.emit("closing", remote_id);
}
/**
* Fires when the underlying socket has closed
*/
protected _onClosed(remote_id) {
this.emit("closed", remote_id);
}
/**
* Close the underlying connction, which provides a way to reset the things
*/
protected _close(subscription?: any) {
if (subscription && subscription.wss) {
try {
subscription.wss.close();
} catch (ex) {
if (ex.message === "WebSocket was closed before the connection was established")
return;
this.emit("error", ex);
}
subscription.wss = undefined;
this._stopReconnectWatcher(subscription);
} else {
this._subscriptions.forEach(sub => this._close(sub));
this._subscriptions = new Map();
}
}
/**
* Reconnects the socket
*/
protected _reconnect(subscription) {
this.emit("reconnecting", subscription.remoteId);
subscription.wss.once("closed", () => {
subscription.wss = this._connect(subscription.remoteId);
});
this._close(subscription);
}
/**
* Starts an interval to check if a reconnction is required
*/
protected _startReconnectWatcher(subscription) {
this._stopReconnectWatcher(subscription); // always clear the prior interval
subscription.reconnectIntervalHandle = setInterval(
() => this._onReconnectCheck(subscription),
this.reconnectIntervalMs,
);
}
/**
* Stops an interval to check if a reconnection is required
*/
protected _stopReconnectWatcher(subscription) {
if (subscription) {
clearInterval(subscription.reconnectIntervalHandle);
subscription.reconnectIntervalHandle = undefined;
}
}
/**
* Checks if a reconnecton is required by comparing the current
* date to the last receieved message date
*/
protected _onReconnectCheck(subscription) {
if (
!subscription.lastMessage ||
subscription.lastMessage < Date.now() - this.reconnectIntervalMs
) {
this._reconnect(subscription);
}
}
////////////////////////////////////////////
// ABSTRACT
protected _onMessage(remote_id: string, raw: string) {
const msg = JSON.parse(raw);
const subscription = this._subscriptions.get(remote_id);
const market = subscription.market;
subscription.lastMessage = Date.now();
if (!market) return;
if (msg.type === "heartbeat") {
// ex: '{"type":"heartbeat","socket_sequence":272}'
/*
A few notes on heartbeats and sequenceIds taken from the Gemini docs:
- Ongoing order events are interspersed with heartbeats every five seconds
- So you can easily ensure that you are receiving all of your WebSocket messages in the expected order without any gaps, events and heartbeats contain a special sequence number.
- Your subscription begins - you receive your first event with socket_sequence set to a value of 0
- For all further messages, each message - whether a heartbeat or an event - should increase this sequence number by one.
- Each time you reconnect, the sequence number resets to zero.
- If you have multiple WebSocket connections, each will have a separate sequence number beginning with zero - make sure to keep track of each sequence number separately!
*/
if (subscription.level2updates) {
/*
So when subbed to l2 updates using sequenceId, a heartbeat event will arrive which includes sequenceId.
You'll need to receive the heartbeat, otherwise sequence will have a gap in next l2update,
So emit an l2update w/no ask or bid changes, only including the sequenceId
*/
const sequenceId = msg.socket_sequence;
this.emit(
"l2update",
this._constructL2Update([], market, sequenceId, null, null),
market,
);
return;
}
}
if (msg.type === "update") {
const { timestampms, eventId, socket_sequence } = msg;
const sequenceId = socket_sequence;
// process trades
if (subscription.trades) {
const events = msg.events.filter(
p => p.type === "trade" && /ask|bid/.test(p.makerSide),
);
for (const event of events) {
const trade = this._constructTrade(event, market, timestampms);
this.emit("trade", trade, market);
}
return;
}
// process l2 updates
if (subscription.level2updates) {
const updates = msg.events.filter(p => p.type === "change");
if (socket_sequence === 0) {
const snapshot = this._constructL2Snapshot(
updates,
market,
sequenceId,
eventId,
);
this.emit("l2snapshot", snapshot, market);
} else {
const update = this._constructL2Update(
updates,
market,
sequenceId,
timestampms,
eventId,
);
this.emit("l2update", update, market);
}
return;
}
// process ticker
// tickers are processed from a seperate websocket
if (subscription.tickers) {
const ticker = this._constructTicker(msg, market);
if (ticker.last && ticker.bid && ticker.ask) {
this.emit("ticker", ticker, market);
}
return;
}
}
}
protected _constructTrade(event, market, timestamp) {
const side = event.makerSide === "ask" ? "sell" : "buy";
const price = event.price;
const amount = event.amount;
return new Trade({
exchange: this.name,
base: market.base,
quote: market.quote,
tradeId: event.tid.toFixed(),
side,
unix: timestamp,
price,
amount,
});
}
protected _constructL2Snapshot(events, market, sequenceId, eventId) {
const asks = [];
const bids = [];
for (const { side, price, remaining, reason, delta } of events) {
const update = new Level2Point(price, remaining, undefined, { reason, delta });
if (side === "ask") asks.push(update);
else bids.push(update);
}
return new Level2Snapshot({
exchange: this.name,
base: market.base,
quote: market.quote,
sequenceId,
eventId,
asks,
bids,
});
}
protected _constructL2Update(events, market, sequenceId, timestampMs, eventId) {
const asks = [];
const bids = [];
for (const { side, price, remaining, reason, delta } of events) {
const update = new Level2Point(price, remaining, undefined, { reason, delta });
if (side === "ask") asks.push(update);
else bids.push(update);
}
return new Level2Update({
exchange: this.name,
base: market.base,
quote: market.quote,
sequenceId,
eventId,
timestampMs,
asks,
bids,
});
}
protected _constructTicker(msg, market): Ticker {
const ticker = this._getTicker(market);
for (let i = 0; i < msg.events.length; i++) {
const event = msg.events[i];
// asks - top_of_book in use
if (event.type === "change" && event.side === "ask") {
ticker.ask = event.price;
ticker.timestamp = msg.timestampms;
}
// bids - top_of_book in use
if (event.type === "change" && event.side === "bid") {
ticker.bid = event.price;
ticker.timestamp = msg.timestampms;
}
// attach latest trade information
if (event.type === "trade") {
ticker.last = event.price;
ticker.timestamp = msg.timestampms;
}
}
return ticker;
}
/**
* Ensures that a ticker for the market exists
* @param {*} market
*/
protected _getTicker(market) {
if (!this.tickersCache.has(market.id)) {
this.tickersCache.set(
market.id,
new Ticker({
exchange: this.name,
base: market.base,
quote: market.quote,
}),
);
}
return this.tickersCache.get(market.id);
}
} | the_stack |
import {Injectable} from "@angular/core";
import {BehaviorSubject} from "rxjs/BehaviorSubject";
import {Subject} from "rxjs/Subject";
import {of} from "rxjs/observable/of";
import {combineLatest} from "rxjs/observable/combineLatest";
import {switchMap, take, map, filter, distinctUntilChanged, skip} from "rxjs/operators";
import {RecentAppTab} from "../../../../electron/src/storage/types/recent-app-tab";
import {TabData} from "../../../../electron/src/storage/types/tab-data-interface";
import {AuthService} from "../../auth/auth.service";
import {FileRepositoryService} from "../../file-repository/file-repository.service";
import {LocalRepositoryService} from "../../repository/local-repository.service";
import {PlatformRepositoryService} from "../../repository/platform-repository.service";
import {DataGatewayService} from "../data-gateway/data-gateway.service";
import {AppHelper} from "../helpers/AppHelper";
import {Store} from "@ngrx/store";
import {TabCloseAction} from "../actions/core.actions";
import {AuthCredentials} from "../../auth/model/auth-credentials";
@Injectable()
export class WorkboxService {
tabs = new BehaviorSubject<TabData<any>[]>([]);
activeTab = new BehaviorSubject(undefined);
tabCreation = new Subject<TabData<any>>();
closeTabStream = new Subject<TabData<any>>();
closeAllTabsStream = new Subject<TabData<any> []>();
homeTabData = {id: "?newFile", label: "Home", type: "NewFile"};
private priorityTabUpdate = new Subject();
constructor(private auth: AuthService,
private dataGateway: DataGatewayService,
private fileRepository: FileRepositoryService,
private localRepository: LocalRepositoryService,
private store: Store<any>,
private platformRepository: PlatformRepositoryService) {
// Whenever a user gets changed, we should restore their tabs
this.auth.getActive().pipe(
switchMap(() => this.getStoredTabs().pipe(
take(1)
)),
// If we have no active tabs, add a "new file"
map(tabDataList => tabDataList.length ? tabDataList : [this.homeTabData]),
map(tabDataList => tabDataList.map(tabData => {
return this.isUtilityTab(tabData) ? tabData : this.getOrCreateAppTab(tabData, true);
}))
).subscribe(tabList => {
this.tabs.next(tabList);
this.ensureActiveTab();
});
// Close Welcome Tab when you connect to the platform
this.auth.getCredentials().pipe(
filter(() => {
const tabs = this.tabs.getValue();
return !!tabs.find((tab) => tab.id === "?welcome");
}),
distinctUntilChanged((a: AuthCredentials[], b: AuthCredentials[]) => !(a.length === 0 && b.length === 1)),
skip(1))
.subscribe(() => {
const welcomeTab = this.tabs.getValue().find((tab) => tab.id === "?welcome");
if (welcomeTab) {
this.closeTab(welcomeTab);
}
});
}
getStoredTabs() {
const local = this.localRepository.getOpenTabs();
const platform = this.auth.getActive().pipe(
switchMap(user => {
if (!user) {
return of([]);
}
return this.platformRepository.getOpenTabs();
}),
filter(v => v !== null)
);
return combineLatest(local, platform,
(local, platform) => [...local, ...platform].sort((a, b) => a.position - b.position)
);
}
syncTabs(): Promise<any> {
// First emit is an empty array (default), second emit is restoring tabs that were previously open
// after that, start listening for newly added tabs
const tabs = this.tabs.getValue();
const localTabs = [];
const platformTabs = [];
tabs.forEach((tab, position) => {
const {id, label, type, isWritable, language} = tab;
const entry = {id, label, type, isWritable, language, position};
if (AppHelper.isLocal(entry.id)) {
localTabs.push(entry);
} else {
platformTabs.push(entry);
}
});
return Promise.all([
this.localRepository.setOpenTabs(localTabs),
this.platformRepository.setOpenTabs(platformTabs)
]);
}
isUtilityTab(tabData: TabData<any>): boolean {
return tabData.id.startsWith("?");
}
forceReloadTabs() {
this.priorityTabUpdate.next(1);
}
openTab(tab: TabData<any>, persistToRecentApps: boolean = true, syncState = true, replaceExistingIfExists = false) {
const {tabs} = this.extractValues();
// When opening an app, we use id with revision number because we can have cases when we can open the same app
// different revisions (when we push a local file with existing id, new tab is open ...)
const foundTabIndex = tabs.findIndex(existingTab => existingTab.id === tab.id);
const foundTab = tabs[foundTabIndex];
if (foundTab) {
if (replaceExistingIfExists) {
this.dataGateway.updateSwap(foundTab.data.id, null);
tabs.splice(foundTabIndex, 1, tab);
this.tabs.next(tabs);
} else {
this.activateTab(foundTab);
return;
}
} else {
this.tabs.next(tabs.concat(tab));
}
this.tabCreation.next(tab);
this.activateTab(tab);
if (syncState) {
this.syncTabs();
}
const isUtilityTab = tab.id.startsWith("?");
if (persistToRecentApps && !isUtilityTab) {
const recentTabData = {
id: tab.id,
label: tab.label,
type: tab.type,
isWritable: tab.isWritable,
language: tab.language,
description: tab.id,
time: Date.now()
} as RecentAppTab;
if (AppHelper.isLocal(tab.id)) {
this.localRepository.pushRecentApp(recentTabData);
} else {
this.platformRepository.pushRecentApp(recentTabData);
}
}
}
openSettingsTab() {
this.openTab({
id: "?settings",
label: "Settings",
type: "Settings"
}, false);
}
/**
* Closes a tab
*/
closeTab(tab?: TabData<any>, force: boolean = false) {
if (!tab) {
tab = this.extractValues().activeTab;
}
if (!force) {
this.closeTabStream.next(tab);
return;
}
if (tab && tab.data && tab.data.id) {
this.dataGateway.updateSwap(tab.data.id, null);
this.store.dispatch(new TabCloseAction(tab.data.id));
}
const currentlyOpenTabs = this.tabs.getValue();
const tabToRemove = currentlyOpenTabs.find(t => t.id === tab.id);
const newTabList = currentlyOpenTabs.filter(t => t !== tabToRemove);
this.tabs.next(newTabList);
this.ensureActiveTab();
this.syncTabs();
}
/**
* Closes all tabs except one that should be preserved
*/
closeAllTabs(preserve: TabData<any>[] = [], force: boolean = false) {
if (!force) {
this.closeAllTabsStream.next(preserve);
return;
}
this.tabs.getValue().forEach((item) => {
if (!preserve.includes(item)) {
this.closeTab(item, true);
}
});
}
activateNext() {
const {tabs, activeTab} = this.extractValues();
const index = tabs.indexOf(activeTab);
const newActiveTab = index === (tabs.length - 1) ? tabs[0] : tabs[index + 1];
this.activateTab(newActiveTab);
}
activatePrevious() {
const {tabs, activeTab} = this.extractValues();
const index = tabs.indexOf(activeTab);
const newActiveTab = index ? tabs[index - 1] : tabs[tabs.length - 1];
this.activateTab(newActiveTab);
}
private ensureActiveTab() {
const {tabs, activeTab} = this.extractValues();
if (!tabs.find(t => t === activeTab)) {
this.activateTab(tabs[tabs.length - 1]);
}
}
private extractValues() {
return {
activeTab: this.activeTab.getValue(),
tabs: this.tabs.getValue()
};
}
private activateTab(tab) {
if (this.activeTab.getValue() === tab) {
return;
}
this.activeTab.next(tab);
}
getOrCreateAppTab<T>(data: TabData<any>, forceCreate = false, forceFetch = false): TabData<T> {
if (!forceCreate) {
const currentTab = this.tabs.getValue().find(existingTab => existingTab.id === data.id);
if (currentTab) {
return currentTab;
}
}
const dataSource = DataGatewayService.getFileSource(data.id);
const id = data.id;
const label = AppHelper.getBasename(data.id);
const isWritable = data.isWritable;
const fileContent = of(1).pipe(
switchMap(() => {
if (dataSource === "local") {
return this.fileRepository.fetchFile(id, forceFetch);
}
return this.platformRepository.getAppContent(id, forceFetch);
})
);
const resolve = (fcontent: string) => this.dataGateway.resolveContent(fcontent, id);
const tab = Object.assign({
label,
isWritable,
data: {
id,
isWritable,
dataSource,
language: data.language || "yaml",
fileContent,
resolve
}
}, data) as TabData<any>;
if (id.endsWith(".json") && !data.language) {
tab.data.language = "json";
}
this.tabCreation.next(tab);
return tab;
}
} | the_stack |
import * as Popper from '@popperjs/core';
import cx from 'classnames';
import React, { useContext } from 'react';
import { OverlayBehaviorContext, OverlayBehaviorContextType } from '../../providers';
import { composeHandlers, pick } from '../../utils';
import {
IOverlayAnimationProps,
IOverlayBackdropProps,
IOverlayCloseActions,
IOverlayLifecycles,
IOverlayPortalProps,
Overlay,
OverlayProps,
} from './overlay';
import { animations } from './overlay-utils/animations';
import { batchedUpdates } from './overlay-utils/batchUpdate';
import { PopupInteractionManager } from './overlay-utils/PopupInteractionManager';
export type PopupPlacement = Popper.Placement;
const ARROW_PADDING = 10;
const ARROW_OFFSET = 12;
const defaultRenderTarget: PopupProps['renderTarget'] = (htmlProps, { target, targetStyle, targetTagName }) => {
return React.createElement(
targetTagName,
{
...htmlProps,
style: targetStyle,
// rex-popup-target will set display=inline-block
className: 'rex-popup-target',
},
target,
);
};
const defaultRenderChildren: PopupProps['renderChildren'] = ({ children, ref, arrow }) => (
<div ref={ref as React.RefObject<HTMLDivElement>}>
{arrow}
{children}
</div>
);
const popperAutoSizeModifier = ({
autoWidth,
autoHeight,
}: {
autoWidth: boolean;
autoHeight: boolean;
}): Popper.Modifier<'popperAutoSizeModifier', {}> => ({
name: 'popperAutoSizeModifier',
enabled: true,
phase: 'beforeWrite' as Popper.ModifierPhases,
requires: ['computeStyles'],
fn: ({ state }: Popper.ModifierArguments<{}>) => {
if (autoWidth) {
state.styles.popper.minWidth = `${state.rects.reference.width}px`;
}
if (autoHeight) {
state.styles.popper.minHeight = `${state.rects.reference.height}px`;
}
},
});
const arrowModifier: Partial<Popper.Modifier<'arrow', { padding: number }>> = {
name: 'arrow',
// arrow modifier 总是开启的,但最终是否渲染箭头由「是否存在 DOM 中的对应节点」决定
enabled: true,
options: { padding: ARROW_PADDING },
};
const adjustArrowStyleModifier: Popper.Modifier<'adjustArrowStyle', {}> = {
name: 'adjustArrowStyle',
enabled: true,
phase: 'beforeWrite',
requires: ['arrow'],
fn({ state }) {
const { arrow } = state.elements;
if (!arrow) {
return;
}
if (state.attributes.arrow == null) {
state.attributes.arrow = {};
}
state.attributes.arrow['data-popper-placement'] = state.placement;
if (state.placement.startsWith('top')) {
state.styles.arrow.bottom = '0';
state.elements.popper.style.setProperty('--rex-popup-arrow-position', `${state.modifiersData.arrow.x}px bottom`);
}
if (state.placement.startsWith('right')) {
state.styles.arrow.left = '0';
state.elements.popper.style.setProperty('--rex-popup-arrow-position', `left ${state.modifiersData.arrow.y}px`);
}
if (state.placement.startsWith('bottom')) {
state.styles.arrow.top = '0';
state.elements.popper.style.setProperty('--rex-popup-arrow-position', `${state.modifiersData.arrow.x}px top`);
}
if (state.placement.startsWith('left')) {
state.styles.arrow.right = '0';
state.elements.popper.style.setProperty('--rex-popup-arrow-position', `right ${state.modifiersData.arrow.y}px`);
}
},
};
export interface PopupChildrenRenderArg {
ref: React.RefObject<Element>;
children: React.ReactNode;
arrow?: React.ReactNode;
}
export type PopupTargetRenderArgs = [
{
ref: React.RefObject<any>;
onClick(e: React.MouseEvent): void;
onMouseEnter(e: React.MouseEvent): void;
onMouseLeave(e: React.MouseEvent): void;
onFocus(e: React.FocusEvent): void;
onBlur(e: React.FocusEvent): void;
},
Pick<PopupProps, 'target' | 'targetStyle' | 'targetTagName'>,
];
export type PopupInteractionKind = 'hover' | 'click' | 'hover-target';
export interface PopupProps
extends IOverlayCloseActions,
IOverlayLifecycles,
IOverlayBackdropProps,
IOverlayAnimationProps,
IOverlayPortalProps {
/** 是否显示弹层 */
visible?: boolean;
/** 弹层是否默认显示 */
defaultVisible?: boolean;
/** 弹层请求关闭时触发事件的回调函数 */
onRequestClose?(reason: any): void;
/** 弹层请求打开时触发事件的回调函数 */
onRequestOpen?(reason: any): void;
/** 弹层方向 */
placement?: PopupPlacement;
/** 弹层目标元素中的内容 */
target?: React.ReactNode;
/** 弹层目标元素的标签名称。默认为 span,适用于内联文本。设置为 div 用于块级元素。 */
targetTagName?: 'div' | 'span';
/** 弹层目标元素的样式 */
targetStyle?: React.CSSProperties;
/**
* 目标元素获取焦点时,是否自动打开弹层
* @category 浮层交互
* */
canOpenByFocus?: boolean;
/**
* 目标元素失去焦点时,是否自动关闭弹层
* @category 浮层交互
* */
canCloseByBlur?: boolean;
attachOverlayManager?: boolean;
/**
* 渲染目标元素的自定义方法。 该属性将覆盖 target/targetTagName/targetStyle
* @displayType (htmlProps, partialPopupProps) => React.ReactNode
* */
renderTarget?(...params: PopupTargetRenderArgs): React.ReactNode;
/**
* 触发弹层显示或隐藏的操作类型,可以是 click', 'hover', 'hover-target'
* @category 浮层交互
*/
interactionKind?: PopupInteractionKind;
/** 鼠标悬停触发弹层显示或隐藏的超时时间 */
hoverDelay?: number;
/** 弹层的根节点的样式类 */
wrapperClassName?: string;
/** 弹层的根节点的内联样式 */
wrapperStyle?: React.CSSProperties;
style?: React.CSSProperties;
className?: string;
hasArrow?: boolean;
/** 弹层内容 */
children?: React.ReactNode;
/** 使用 render prop 的形式指定弹层内容,用于精确控制 DOM 结构 */
renderChildren?(arg: PopupChildrenRenderArg): React.ReactNode;
/** 弹层翻转 是否允许弹层翻转 */
flip?: boolean;
/** 弹层相对于 target 位置的偏移量 */
offset?: [skidding: number, distance: number];
/** 将弹层的最小宽度设置为 target 的宽度 */
autoWidth?: boolean;
/** 将弹层的最小高度设置为 target 的高度 */
autoHeight?: boolean;
/**
* 为不同的方向设置不同的弹层打开动画
* @category 浮层动画
* @displayType Partial<{ [placement in PopupPlacement]: OverlayProps['animation'] }>
* */
animationDict?: Partial<{ [placement in PopupPlacement]: OverlayProps['animation'] }>;
/**
* 弹层的打开方向(如果 animationDict 中缺少当前方向的打开方向的话,则会使用该 prop 指定的动画)
* @category 浮层动画
* */
animation?: OverlayProps['animation'];
}
interface PopupState {
visible: boolean;
}
/**
* 弹层组件,根据 placement/strategy/flip/offset 等配置,将 content 放置在 target 的旁边。
*
* ```
* <Popup target={target} placement="bottom" offset={[0, 16]}>{content}</Popup>:
*
* ┌─────────────────────┐
* │ │ <┄┄┄ target
* └─────────────────────┘
* ╔═════════════════════════════╗
* ║ ║
* ║ ║ <┄┄┄ content/children
* ║ ║
* ╚═════════════════════════════╝
* ```
*/
export class Popup extends React.Component<PopupProps, PopupState> {
static readonly contextType = OverlayBehaviorContext;
context: OverlayBehaviorContextType;
// 通过 context 将 popup 实例传递给子节点,允许子节点通过该 context 直接关闭 popup
static readonly NearestPopupContext = React.createContext<Popup>(null);
// eslint-disable-next-line react-hooks/rules-of-hooks
static useNearestPopup = () => useContext(Popup.NearestPopupContext);
static defaultRenderTarget = defaultRenderTarget;
static defaultRenderChildren = defaultRenderChildren;
static getDefaultAnimation(placement: PopupPlacement) {
if (placement.includes('top')) {
return { in: animations.expandInUp, out: animations.expandOutDown };
} else {
return { in: animations.expandInDown, out: animations.expandOutUp };
}
}
static defaultProps = {
placement: 'bottom-start',
strategy: 'absolute',
flip: true,
autoWidth: false,
autoHeight: false,
usePortal: true,
canCloseByEsc: true,
canCloseByOutSideClick: true,
canOpenByFocus: false,
canCloseByBlur: false,
offset: [0, 0],
interactionKind: 'click',
hoverDelay: 120,
renderTarget: Popup.defaultRenderTarget,
renderChildren: Popup.defaultRenderChildren,
targetTagName: 'span',
// 为了区分用户是否真的传递了 animation 与 animationDict,这里不设置默认值
// animation: Popup.defaultAnimation,
// animationDict: Popup.defaultAnimationDict,
};
private popper: Popper.Instance | null = null;
private contentRef = React.createRef<HTMLElement>();
private targetRef = React.createRef<Element>();
private overlayRef = React.createRef<Overlay>();
/** 上次使用的定位参考元素,用于判断参照元素是否发生了变化,发生变化时需要重新创建 popper 实例 */
private lastTarget: Element = null;
constructor(props: PopupProps) {
super(props);
this.state = {
visible: props.visible ?? props.defaultVisible,
};
this.interactionManager.action$.subscribe((action) => {
if (action.type === 'open') {
this.onRequestOpen(action.reason);
} else {
this.onRequestClose(action.reason);
}
});
}
static getDerivedStateFromProps(props: PopupProps, state: PopupState) {
if (props.visible != null) {
return { visible: props.visible };
}
return null;
}
private onRequestClose = (reason: any) => {
batchedUpdates(() => {
this.setState({ visible: false });
this.props.onRequestClose?.(reason);
});
};
private onRequestOpen = (reason: any) => {
batchedUpdates(() => {
this.setState({ visible: true });
this.props.onRequestOpen?.(reason);
});
};
/** 关闭当前弹层以及该弹层之后的所有弹层(这里的「之后」指的是在 OverlayManager.stack 中的先后顺序 */
dismissAfterwards() {
const portalContainer = this.props.portalContainer ?? this.context.portalContainer;
const manager = Overlay.getManager(portalContainer);
const selfIndex = manager.stack.indexOf(this.overlayRef.current);
if (selfIndex !== -1) {
for (const overlay of manager.stack.slice(selfIndex)) {
overlay.props.onRequestClose?.('dismiss');
}
}
}
componentDidUpdate(prevProps: Readonly<PopupProps>, prevState: Readonly<PopupState>) {
if (
prevProps.placement !== this.props.placement ||
prevProps.autoWidth !== this.props.autoWidth ||
prevProps.autoHeight !== this.props.autoHeight ||
prevProps.flip !== this.props.flip ||
(this.lastTarget != null && this.lastTarget != this.targetRef.current)
) {
if (this.state.visible) {
this.reopenPopper();
}
}
}
private reopenPopper() {
const { placement, flip, offset, autoWidth, autoHeight } = this.props;
this.closePopper();
const target = this.targetRef.current as HTMLElement;
this.lastTarget = target;
if (target == null) {
return;
}
target.dataset.rexPopupOpen = 'true';
this.popper = Popper.createPopper(target, this.contentRef.current, {
placement,
modifiers: [
{ name: 'flip', enabled: flip },
{
name: 'offset',
enabled: true,
options: {
offset: () => {
const [skidding, distance] = offset;
const { hasArrow } = this.props;
return [skidding, distance + (hasArrow ? ARROW_OFFSET : 0)];
},
},
},
popperAutoSizeModifier({ autoWidth, autoHeight }),
arrowModifier,
adjustArrowStyleModifier,
],
});
return this.popper.update();
}
private clearTargetDataset = () => {
const target = this.targetRef.current as HTMLElement;
delete target?.dataset.rexPopupOpen;
};
private closePopper = () => {
if (this.popper) {
this.popper.destroy();
this.popper = null;
}
};
componentWillUnmount() {
this.clearTargetDataset();
this.closePopper();
this.interactionManager.complete();
}
private interactionManager = new PopupInteractionManager(
{
hoverDelay: this.props.hoverDelay,
interactionKind: this.props.interactionKind,
canOpenByFocus: this.props.canOpenByFocus,
canCloseByBlur: this.props.canCloseByBlur,
},
() => this.state.visible,
);
private beforeOverlayOpen = () => {
const { beforeOpen, animationDict, animation } = this.props;
return this.reopenPopper().then((state) => {
beforeOpen?.();
const animationFromProps = animationDict?.[state.placement] ?? animation;
return {
animation: animationFromProps ?? Popup.getDefaultAnimation(state.placement),
};
});
};
private beforeOverlayClose = () => {
const { beforeClose, animationDict, animation } = this.props;
beforeClose?.();
if (this.popper == null) {
return;
}
const placement = this.popper.state.placement;
const animationFromProps = animationDict?.[placement] ?? animation;
return {
animation: animationFromProps ?? Popup.getDefaultAnimation(placement),
};
};
render() {
const {
usePortal,
portalContainer,
renderTarget,
target,
targetStyle,
targetTagName,
wrapperClassName,
wrapperStyle,
hasBackdrop,
style,
className,
backdropClassName,
backdropStyle,
children,
renderChildren,
animation,
animationDuration,
hasArrow,
canCloseByEsc,
attachOverlayManager,
canCloseByOutSideClick,
disableScroll,
} = this.props;
const overlayLifecycles = pick(this.props, [
'beforeOpen',
'onOpen',
'afterOpen',
'beforeClose',
'onClose',
'afterClose',
]);
const { visible } = this.state;
const renderedTarget = renderTarget(
{
ref: this.targetRef,
onClick: this.interactionManager.onTargetClick,
onMouseEnter: this.interactionManager.onTargetMouseEnter,
onMouseLeave: this.interactionManager.onTargetMouseLeave,
onFocus: this.interactionManager.onTargetFocus,
onBlur: this.interactionManager.onTargetBlur,
},
{ target, targetStyle, targetTagName },
);
const arrow = hasArrow && <div className="rex-popup-arrow" data-popper-arrow="true" />;
return (
<>
{renderedTarget}
<Overlay
ref={this.overlayRef}
className={wrapperClassName}
style={wrapperStyle}
usePortal={usePortal}
portalContainer={portalContainer}
visible={visible}
safeNodes={[() => this.targetRef.current]}
hasBackdrop={hasBackdrop}
backdropStyle={backdropStyle}
backdropClassName={backdropClassName}
onRequestClose={this.onRequestClose}
canCloseByOutSideClick={canCloseByOutSideClick}
canCloseByEsc={canCloseByEsc}
attachOverlayManager={attachOverlayManager}
disableScroll={disableScroll}
animation={animation}
animationDuration={animationDuration}
beforeOpen={this.beforeOverlayOpen}
onOpen={overlayLifecycles.onOpen}
afterOpen={overlayLifecycles.afterOpen}
beforeClose={this.beforeOverlayClose}
onClose={composeHandlers(this.clearTargetDataset, overlayLifecycles.onClose)}
afterClose={composeHandlers(this.closePopper, overlayLifecycles.afterClose)}
renderChildren={({ ref }) => (
<div
// todo autoFocus 浮层打开时 自动获取焦点
// todo enforceFocus 浮层打开状态下,焦点始终在浮层内
className={cx('rex-popup-content', className)}
style={style}
ref={this.contentRef as React.RefObject<HTMLDivElement>}
// 注意这里注册的是 React 管理的回调,mouseEnter/mouseLeave 事件在冒泡时会按照 react portal 来进行
onMouseEnter={this.interactionManager.onContentMouseEnter}
onMouseLeave={this.interactionManager.onContentMouseLeave}
>
<Popup.NearestPopupContext.Provider value={this}>
{renderChildren({ ref, children, arrow })}
</Popup.NearestPopupContext.Provider>
</div>
)}
/>
</>
);
}
} | the_stack |
module android.text{
import System = java.lang.System;
import StringBuilder = java.lang.StringBuilder;
import MeasuredText = android.text.MeasuredText;
import Spanned = android.text.Spanned;
import TextDirectionHeuristic = android.text.TextDirectionHeuristic;
import TextDirectionHeuristics = android.text.TextDirectionHeuristics;
import TextPaint = android.text.TextPaint;
export class TextUtils{
/**
* Returns true if the string is null or 0-length.
* @param str the string to be examined
* @return true if str is null or zero length
*/
static isEmpty(str:string|String):boolean {
if (str == null || str.length == 0)
return true;
else
return false;
}
/** @hide */
static ALIGNMENT_SPAN:number = 1;
/** @hide */
static FIRST_SPAN:number = TextUtils.ALIGNMENT_SPAN;
/** @hide */
static FOREGROUND_COLOR_SPAN:number = 2;
/** @hide */
static RELATIVE_SIZE_SPAN:number = 3;
/** @hide */
static SCALE_X_SPAN:number = 4;
/** @hide */
static STRIKETHROUGH_SPAN:number = 5;
/** @hide */
static UNDERLINE_SPAN:number = 6;
/** @hide */
static STYLE_SPAN:number = 7;
/** @hide */
static BULLET_SPAN:number = 8;
/** @hide */
static QUOTE_SPAN:number = 9;
/** @hide */
static LEADING_MARGIN_SPAN:number = 10;
/** @hide */
static URL_SPAN:number = 11;
/** @hide */
static BACKGROUND_COLOR_SPAN:number = 12;
/** @hide */
static TYPEFACE_SPAN:number = 13;
/** @hide */
static SUPERSCRIPT_SPAN:number = 14;
/** @hide */
static SUBSCRIPT_SPAN:number = 15;
/** @hide */
static ABSOLUTE_SIZE_SPAN:number = 16;
/** @hide */
static TEXT_APPEARANCE_SPAN:number = 17;
/** @hide */
static ANNOTATION:number = 18;
/** @hide */
static SUGGESTION_SPAN:number = 19;
/** @hide */
static SPELL_CHECK_SPAN:number = 20;
/** @hide */
static SUGGESTION_RANGE_SPAN:number = 21;
/** @hide */
static EASY_EDIT_SPAN:number = 22;
/** @hide */
static LOCALE_SPAN:number = 23;
/** @hide */
static LAST_SPAN:number = TextUtils.LOCALE_SPAN;
private static EMPTY_STRING_ARRAY:string[] = [];
private static ZWNBS_CHAR = String.fromCodePoint(20);
private static ARAB_SCRIPT_SUBTAG:string = "Arab";
private static HEBR_SCRIPT_SUBTAG:string = "Hebr";
static getOffsetBefore(text:String, offset:number):number {
if (offset == 0)
return 0;
if (offset == 1)
return 0;
let c = text.codePointAt(offset - 1);
if (c >= '?'.codePointAt(0) && c <= '?'.codePointAt(0)) {
let c1 = text.codePointAt(offset - 2);
if (c1 >= '?'.codePointAt(0) && c1 <= '?'.codePointAt(0))
offset -= 2;
else
offset -= 1;
} else {
offset -= 1;
}
if (Spanned.isImplements(text)) {
let spans:android.text.style.ReplacementSpan[] = (<Spanned> text).getSpans<android.text.style.ReplacementSpan>(offset, offset, android.text.style.ReplacementSpan.type);
for (let i:number = 0; i < spans.length; i++) {
let start:number = (<Spanned> text).getSpanStart(spans[i]);
let end:number = (<Spanned> text).getSpanEnd(spans[i]);
if (start < offset && end > offset)
offset = start;
}
}
return offset;
}
static getOffsetAfter(text:String, offset:number):number {
let len:number = text.length;
if (offset == len)
return len;
if (offset == len - 1)
return len;
let c = text.codePointAt(offset);
if (c >= '?'.codePointAt(0) && c <= '?'.codePointAt(0)) {
let c1 = text.codePointAt(offset + 1);
if (c1 >= '?'.codePointAt(0) && c1 <= '?'.codePointAt(0))
offset += 2;
else
offset += 1;
} else {
offset += 1;
}
if (Spanned.isImplements(text)) {
let spans:android.text.style.ReplacementSpan[] = (<Spanned> text).getSpans<android.text.style.ReplacementSpan>(offset, offset, android.text.style.ReplacementSpan.type);
for (let i:number = 0; i < spans.length; i++) {
let start:number = (<Spanned> text).getSpanStart(spans[i]);
let end:number = (<Spanned> text).getSpanEnd(spans[i]);
if (start < offset && end > offset)
offset = end;
}
}
return offset;
}
/**
* Returns the original text if it fits in the specified width
* given the properties of the specified Paint,
* or, if it does not fit, a copy with ellipsis character added
* at the specified edge or center.
* If <code>preserveLength</code> is specified, the returned copy
* will be padded with zero-width spaces to preserve the original
* length and offsets instead of truncating.
* If <code>callback</code> is non-null, it will be called to
* report the start and end of the ellipsized range.
*
* @hide
*/
static ellipsize(text:String, paint:TextPaint, avail:number, where:TextUtils.TruncateAt, preserveLength=false,
callback:TextUtils.EllipsizeCallback=null, textDir=TextDirectionHeuristics.FIRSTSTRONG_LTR,
ellipsis = undefined):String {
ellipsis = ellipsis || (where == TextUtils.TruncateAt.END_SMALL? android.text.Layout.ELLIPSIS_TWO_DOTS[0] : android.text.Layout.ELLIPSIS_NORMAL[0]);
let len:number = text.length;
let mt:MeasuredText = MeasuredText.obtain();
try {
let width:number = TextUtils.setPara(mt, paint, text, 0, text.length, textDir);
if (width <= avail) {
if (callback != null) {
callback.ellipsized(0, 0);
}
return text;
}
// XXX assumes ellipsis string does not require shaping and
// is unaffected by style
let ellipsiswid:number = paint.measureText(ellipsis);
avail -= ellipsiswid;
let left:number = 0;
let right:number = len;
if (avail < 0) {
// it all goes
} else if (where == TextUtils.TruncateAt.START) {
right = len - mt.breakText(len, false, avail);
} else if (where == TextUtils.TruncateAt.END || where == TextUtils.TruncateAt.END_SMALL) {
left = mt.breakText(len, true, avail);
} else {
right = len - mt.breakText(len, false, avail / 2);
avail -= mt.measure(right, len);
left = mt.breakText(right, true, avail);
}
if (callback != null) {
callback.ellipsized(left, right);
}
let buf:string[] = mt.mChars.split('');
let sp:Spanned = Spanned.isImplements(text) ? <Spanned> text : null;
let remaining:number = len - (right - left);
if (preserveLength) {
if (remaining > 0) {
// else eliminate the ellipsis too
buf[left++] = ellipsis.charAt(0);
}
for (let i:number = left; i < right; i++) {
buf[i] = TextUtils.ZWNBS_CHAR;
}
let s:string = buf.join('');
//if (sp == null) {//TODO when span impl
return s;
//}
//let ss:SpannableString = new SpannableString(s);
//TextUtils.copySpansFrom(sp, 0, len, any.class, ss, 0);
//return ss;
}
if (remaining == 0) {
return "";
}
//if (sp == null) {//TODO when span impl
let sb:StringBuilder = new StringBuilder(remaining + ellipsis.length());
sb.append(buf.join('').substr(0, left));
sb.append(ellipsis);
sb.append(buf.join('').substr(right, len - right));
return sb.toString();
//}
//let ssb:SpannableStringBuilder = new SpannableStringBuilder();
//ssb.append(text, 0, left);
//ssb.append(ellipsis);
//ssb.append(text, right, len);
//return ssb;
} finally {
MeasuredText.recycle(mt);
}
}
private static setPara(mt:MeasuredText, paint:TextPaint, text:String, start:number, end:number, textDir:TextDirectionHeuristic):number {
mt.setPara(text, start, end, textDir);
let width:number;
let sp:Spanned = Spanned.isImplements(text) ? <Spanned> text : null;
let len:number = end - start;
if (sp == null) {
width = mt.addStyleRun(paint, len, null);
} else {
width = 0;
let spanEnd:number;
for (let spanStart:number = 0; spanStart < len; spanStart = spanEnd) {
spanEnd = sp.nextSpanTransition(spanStart, len, android.text.style.MetricAffectingSpan.type);
let spans:android.text.style.MetricAffectingSpan[] = sp.getSpans<android.text.style.MetricAffectingSpan>(spanStart, spanEnd, android.text.style.MetricAffectingSpan.type);
spans = TextUtils.removeEmptySpans(spans, sp, android.text.style.MetricAffectingSpan.type);
width += mt.addStyleRun(paint, spans, spanEnd - spanStart, null);
}
}
return width;
}
/**
* Removes empty spans from the <code>spans</code> array.
*
* When parsing a Spanned using {@link Spanned#nextSpanTransition(int, int, Class)}, empty spans
* will (correctly) create span transitions, and calling getSpans on a slice of text bounded by
* one of these transitions will (correctly) include the empty overlapping span.
*
* However, these empty spans should not be taken into account when layouting or rendering the
* string and this method provides a way to filter getSpans' results accordingly.
*
* @param spans A list of spans retrieved using {@link Spanned#getSpans(int, int, Class)} from
* the <code>spanned</code>
* @param spanned The Spanned from which spans were extracted
* @return A subset of spans where empty spans ({@link Spanned#getSpanStart(Object)} ==
* {@link Spanned#getSpanEnd(Object)} have been removed. The initial order is preserved
* @hide
*/
static removeEmptySpans<T> (spans:T[], spanned:Spanned, klass:any):T[] {
let copy:T[] = null;
let count:number = 0;
for (let i:number = 0; i < spans.length; i++) {
const span:T = spans[i];
const start:number = spanned.getSpanStart(span);
const end:number = spanned.getSpanEnd(span);
if (start == end) {
if (copy == null) {
copy = new Array<T>(spans.length - 1);
System.arraycopy(spans, 0, copy, 0, i);
count = i;
}
} else {
if (copy != null) {
copy[count] = span;
count++;
}
}
}
if (copy != null) {
let result:T[] = new Array<T>(count);
System.arraycopy(copy, 0, result, 0, count);
return result;
} else {
return spans;
}
}
/**
* pack to a array, because javascript will do '<<' as int range
* (Pack 2 int values into a long, useful as a return value for a range)
* @see #unpackRangeStartFromLong(long)
* @see #unpackRangeEndFromLong(long)
* @hide
*/
static packRangeInLong(start:number, end:number):number[] {
return [start, end];
}
/**
* Get the start value from a range packed in a long by {@link #packRangeInLong(int, int)}
* @see #unpackRangeEndFromLong(long)
* @see #packRangeInLong(int, int)
* @hide
*/
static unpackRangeStartFromLong(range:number[]):number {
return range[0] || 0;
}
/**
* Get the end value from a range packed in a long by {@link #packRangeInLong(int, int)}
* @see #unpackRangeStartFromLong(long)
* @see #packRangeInLong(int, int)
* @hide
*/
static unpackRangeEndFromLong(range:number[]):number {
return range[1] || 0;
}
}
export module TextUtils{
export enum TruncateAt {
START /*() {
}
*/, MIDDLE /*() {
}
*/, END /*() {
}
*/, MARQUEE /*() {
}
*/, /**
* @hide
*/
END_SMALL /*() {
}
*/ /*;
*/}
export interface EllipsizeCallback {
/**
* This method is called to report that the specified region of
* text was ellipsized away by a call to {@link #ellipsize}.
*/
ellipsized(start:number, end:number):void ;
}
}
} | the_stack |
import { Appservice, AppserviceJoinRoomStrategy, IJoinRoomStrategy } from "../../src";
import * as expect from "expect";
import * as simple from "simple-mock";
describe('AppserviceJoinRoomStrategy', () => {
it('should be able to join the room normally', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
const roomId = "!somewhere:example.org";
const userId = "@someone:example.org";
const underlyingSpy = simple.stub().callFn((rid, uid, apiCall) => {
expect(rid).toEqual(roomId);
expect(uid).toEqual(userId);
expect(apiCall).toBeDefined();
return Promise.resolve();
});
const underlyingStrategy = <IJoinRoomStrategy>{joinRoom: underlyingSpy};
const strategy = new AppserviceJoinRoomStrategy(underlyingStrategy, appservice);
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
return Promise.resolve();
});
await strategy.joinRoom(roomId, userId, apiCallSpy);
expect(apiCallSpy.callCount).toBe(1);
expect(underlyingSpy.callCount).toBe(0);
});
it('should call the underlying strategy after the first failure', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
appservice.botIntent.underlyingClient.resolveRoom = async (rid) => {
return roomId;
};
const inviteSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
return Promise.resolve();
});
appservice.botIntent.underlyingClient.inviteUser = inviteSpy;
const roomId = "!somewhere:example.org";
const userId = "@someone:example.org";
const underlyingSpy = simple.stub().callFn((rid, uid, apiCall) => {
expect(rid).toEqual(roomId);
expect(uid).toEqual(userId);
expect(apiCall).toBeDefined();
return Promise.resolve();
});
const underlyingStrategy = <IJoinRoomStrategy>{joinRoom: underlyingSpy};
const strategy = new AppserviceJoinRoomStrategy(underlyingStrategy, appservice);
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
throw new Error("Simulated failure");
});
await strategy.joinRoom(roomId, userId, apiCallSpy);
expect(apiCallSpy.callCount).toBe(1);
expect(underlyingSpy.callCount).toBe(1);
expect(inviteSpy.callCount).toBe(1);
});
it('should not invite the bot user if the bot user is joining', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
appservice.botIntent.underlyingClient.resolveRoom = async (rid) => {
return roomId;
};
const inviteSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
return Promise.resolve();
});
appservice.botIntent.underlyingClient.inviteUser = inviteSpy;
const roomId = "!somewhere:example.org";
const userId = "@_bot_:example.org";
const underlyingSpy = simple.stub().callFn((rid, uid, apiCall) => {
expect(rid).toEqual(roomId);
expect(uid).toEqual(userId);
expect(apiCall).toBeDefined();
return Promise.resolve();
});
const underlyingStrategy = <IJoinRoomStrategy>{joinRoom: underlyingSpy};
const strategy = new AppserviceJoinRoomStrategy(underlyingStrategy, appservice);
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
throw new Error("Simulated failure");
});
await strategy.joinRoom(roomId, userId, apiCallSpy);
expect(apiCallSpy.callCount).toBe(1);
expect(underlyingSpy.callCount).toBe(1);
expect(inviteSpy.callCount).toBe(0);
});
it('should call the API twice when there is no strategy', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
appservice.botIntent.underlyingClient.resolveRoom = async (rid) => {
return roomId;
};
const inviteSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
return Promise.resolve();
});
appservice.botIntent.underlyingClient.inviteUser = inviteSpy;
const roomId = "!somewhere:example.org";
const userId = "@someone:example.org";
const strategy = new AppserviceJoinRoomStrategy(null, appservice);
let attempt = 0;
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
if (attempt++ === 0) {
throw new Error("Simulated failure");
} else return Promise.resolve();
});
await strategy.joinRoom(roomId, userId, apiCallSpy);
expect(apiCallSpy.callCount).toBe(2);
expect(inviteSpy.callCount).toBe(1);
});
it('should call the API once when there is no strategy for the bot user', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
appservice.botIntent.underlyingClient.resolveRoom = async (rid) => {
return roomId;
};
const inviteSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
return Promise.resolve();
});
appservice.botIntent.underlyingClient.inviteUser = inviteSpy;
const roomId = "!somewhere:example.org";
const userId = "@_bot_:example.org";
const strategy = new AppserviceJoinRoomStrategy(null, appservice);
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
throw new Error("Simulated failure");
});
try {
await strategy.joinRoom(roomId, userId, apiCallSpy);
// noinspection ExceptionCaughtLocallyJS
throw new Error("Join succeeded when it should have failed");
} catch (e) {
expect(e.message).toEqual("Simulated failure");
}
expect(apiCallSpy.callCount).toBe(1);
expect(inviteSpy.callCount).toBe(0);
});
it('should fail if the underlying strategy fails', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
appservice.botIntent.underlyingClient.resolveRoom = async (rid) => {
return roomId;
};
const inviteSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
return Promise.resolve();
});
appservice.botIntent.underlyingClient.inviteUser = inviteSpy;
const roomId = "!somewhere:example.org";
const userId = "@someone:example.org";
const underlyingSpy = simple.stub().callFn((rid, uid, apiCall) => {
expect(rid).toEqual(roomId);
expect(uid).toEqual(userId);
expect(apiCall).toBeDefined();
throw new Error("Simulated failure 2");
});
const underlyingStrategy = <IJoinRoomStrategy>{joinRoom: underlyingSpy};
const strategy = new AppserviceJoinRoomStrategy(underlyingStrategy, appservice);
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
throw new Error("Simulated failure");
});
try {
await strategy.joinRoom(roomId, userId, apiCallSpy);
// noinspection ExceptionCaughtLocallyJS
throw new Error("Join succeeded when it should have failed");
} catch (e) {
expect(e.message).toEqual("Simulated failure 2");
}
expect(apiCallSpy.callCount).toBe(1);
expect(underlyingSpy.callCount).toBe(1);
expect(inviteSpy.callCount).toBe(1);
});
it('should handle invite failures', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
appservice.botIntent.underlyingClient.resolveRoom = async (rid) => {
return roomId;
};
const inviteSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
throw new Error("Simulated invite error");
});
appservice.botIntent.underlyingClient.inviteUser = inviteSpy;
const roomId = "!somewhere:example.org";
const userId = "@someone:example.org";
const strategy = new AppserviceJoinRoomStrategy(null, appservice);
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
throw new Error("Simulated failure");
});
try {
await strategy.joinRoom(roomId, userId, apiCallSpy);
// noinspection ExceptionCaughtLocallyJS
throw new Error("Join succeeded when it should have failed");
} catch (e) {
expect(e.message).toEqual("Simulated invite error");
}
expect(apiCallSpy.callCount).toBe(1);
expect(inviteSpy.callCount).toBe(1);
});
it('should pass to the underlying strategy on invite failures', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'example.org',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "_bot_",
namespaces: {
users: [{exclusive: true, regex: "@_prefix_.*:.+"}],
rooms: [],
aliases: [],
},
},
});
appservice.botIntent.ensureRegistered = () => {
return null;
};
appservice.botIntent.underlyingClient.resolveRoom = async (rid) => {
return roomId;
};
const inviteSpy = simple.stub().callFn((uid, rid) => {
expect(uid).toEqual(userId);
expect(rid).toEqual(roomId);
throw new Error("Simulated invite error");
});
appservice.botIntent.underlyingClient.inviteUser = inviteSpy;
const roomId = "!somewhere:example.org";
const userId = "@someone:example.org";
const underlyingSpy = simple.stub().callFn((rid, uid, apiCall) => {
expect(rid).toEqual(roomId);
expect(uid).toEqual(userId);
expect(apiCall).toBeDefined();
throw new Error("Simulated failure 2");
});
const underlyingStrategy = <IJoinRoomStrategy>{joinRoom: underlyingSpy};
const strategy = new AppserviceJoinRoomStrategy(underlyingStrategy, appservice);
const apiCallSpy = simple.stub().callFn((rid) => {
expect(rid).toEqual(roomId);
throw new Error("Simulated failure");
});
try {
await strategy.joinRoom(roomId, userId, apiCallSpy);
// noinspection ExceptionCaughtLocallyJS
throw new Error("Join succeeded when it should have failed");
} catch (e) {
expect(e.message).toEqual("Simulated failure 2");
}
expect(apiCallSpy.callCount).toBe(1);
expect(underlyingSpy.callCount).toBe(1);
expect(inviteSpy.callCount).toBe(1);
});
}); | the_stack |
import {MAGIC_ADDRESS_INDICATING_ETH} from '../src/transactions';
import {
waitForChallengesToTimeOut,
challengeChannelAndExpectGas,
Y,
X,
LforX,
LforJ,
J,
assertEthBalancesAndHoldings,
amountForAlice,
amountForBob,
amountForAliceAndBob,
} from './fixtures';
import {gasRequiredTo} from './gas';
import {nitroAdjudicator, token} from './vanillaSetup';
/**
* Ensures the asset holding contract always has a nonzero token balance.
*/
async function addResidualTokenBalance(asset: string) {
/**
* Funding someOtherChannel with tokens, as well as the channel in question
* makes the benchmark more realistic. In practice many other
* channels are funded by the nitro adjudicator. If we didn't reflect
* that, our benchmark might reflect a gas refund for clearing storage
* in the token contract (setting the token balance of the asset holder to 0)
* which we would only expect in rare cases.
*/
await (await nitroAdjudicator.deposit(asset, Y.channelId, 0, 1)).wait();
}
describe('Consumes the expected gas for deployments', () => {
it(`when deploying the NitroAdjudicator`, async () => {
await expect(await nitroAdjudicator.deployTransaction).toConsumeGas(
gasRequiredTo.deployInfrastructureContracts.vanillaNitro.NitroAdjudicator
);
});
});
describe('Consumes the expected gas for deposits', () => {
it(`when directly funding a channel with ETH (first deposit)`, async () => {
await expect(
await nitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, X.channelId, 0, 5, {value: 5})
).toConsumeGas(gasRequiredTo.directlyFundAChannelWithETHFirst.vanillaNitro);
});
it(`when directly funding a channel with ETH (second deposit)`, async () => {
// begin setup
const setupTX = nitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, X.channelId, 0, 5, {
value: 5,
});
await (await setupTX).wait();
// end setup
await expect(
await nitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, X.channelId, 5, 5, {value: 5})
).toConsumeGas(gasRequiredTo.directlyFundAChannelWithETHSecond.vanillaNitro);
});
it(`when directly funding a channel with an ERC20 (first deposit)`, async () => {
// begin setup
await (await token.transfer(nitroAdjudicator.address, 1)).wait(); // The asset holder already has some tokens (for other channels)
// end setup
await expect(await token.increaseAllowance(nitroAdjudicator.address, 100)).toConsumeGas(
gasRequiredTo.directlyFundAChannelWithERC20First.vanillaNitro.approve
);
await expect(await nitroAdjudicator.deposit(token.address, X.channelId, 0, 5)).toConsumeGas(
gasRequiredTo.directlyFundAChannelWithERC20First.vanillaNitro.deposit
);
});
it(`when directly funding a channel with an ERC20 (second deposit)`, async () => {
// begin setup
await (await token.increaseAllowance(nitroAdjudicator.address, 100)).wait();
await (await nitroAdjudicator.deposit(token.address, X.channelId, 0, 5)).wait(); // The asset holder already has some tokens *for this channel*
await (await token.decreaseAllowance(nitroAdjudicator.address, 95)).wait(); // reset allowance to zero
// end setup
await expect(await token.increaseAllowance(nitroAdjudicator.address, 100)).toConsumeGas(
gasRequiredTo.directlyFundAChannelWithERC20Second.vanillaNitro.approve
);
await expect(await nitroAdjudicator.deposit(token.address, X.channelId, 5, 5)).toConsumeGas(
gasRequiredTo.directlyFundAChannelWithERC20Second.vanillaNitro.deposit
);
});
});
describe('Consumes the expected gas for happy-path exits', () => {
it(`when exiting a directly funded (with ETH) channel`, async () => {
// begin setup
await (
await nitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, X.channelId, 0, 10, {value: 10})
).wait();
// end setup
await expect(await X.concludeAndTransferAllAssetsTx(MAGIC_ADDRESS_INDICATING_ETH)).toConsumeGas(
gasRequiredTo.ETHexit.vanillaNitro
);
});
it(`when exiting a directly funded (with ERC20s) channel`, async () => {
// begin setup
await (await token.increaseAllowance(nitroAdjudicator.address, 100)).wait();
await (await nitroAdjudicator.deposit(token.address, X.channelId, 0, 10)).wait();
await addResidualTokenBalance(token.address);
// end setup
await expect(await X.concludeAndTransferAllAssetsTx(token.address)).toConsumeGas(
gasRequiredTo.ERC20exit.vanillaNitro
);
});
});
describe('Consumes the expected gas for sad-path exits', () => {
it(`when exiting a directly funded (with ETH) channel`, async () => {
// begin setup
await (
await nitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, X.channelId, 0, 10, {value: 10})
).wait();
// end setup
// initially ⬛ -> X -> 👩
const {proof, finalizesAt} = await challengeChannelAndExpectGas(
X,
MAGIC_ADDRESS_INDICATING_ETH,
gasRequiredTo.ETHexitSad.vanillaNitro.challenge
);
// begin wait
await waitForChallengesToTimeOut([finalizesAt]);
// end wait
// challenge + timeout ⬛ -> (X) -> 👩
await expect(
await nitroAdjudicator.transferAllAssets(
X.channelId,
proof.outcomeBytes, // outcomeBytes,
proof.stateHash // stateHash
)
).toConsumeGas(gasRequiredTo.ETHexitSad.vanillaNitro.transferAllAssets);
// transferAllAssets ⬛ --------> 👩
expect(
gasRequiredTo.ETHexitSad.vanillaNitro.challenge +
gasRequiredTo.ETHexitSad.vanillaNitro.transferAllAssets
).toEqual(gasRequiredTo.ETHexitSad.vanillaNitro.total);
});
it(`when exiting a ledger funded (with ETH) channel`, async () => {
// begin setup
await (
await nitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, LforX.channelId, 0, 10, {
value: 10,
})
).wait();
// end setup
// initially ⬛ -> L -> X -> 👩
const {proof: ledgerProof, finalizesAt: ledgerFinalizesAt} = await challengeChannelAndExpectGas(
LforX,
MAGIC_ADDRESS_INDICATING_ETH,
gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.challengeL
);
const {proof, finalizesAt} = await challengeChannelAndExpectGas(
X,
MAGIC_ADDRESS_INDICATING_ETH,
gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.challengeX
);
// begin wait
await waitForChallengesToTimeOut([ledgerFinalizesAt, finalizesAt]); // just go to the max one
// end wait
// challenge X, L and timeout ⬛ -> (L) -> (X) -> 👩
await expect(
await nitroAdjudicator.transferAllAssets(
LforX.channelId,
ledgerProof.outcomeBytes, // outcomeBytes
ledgerProof.stateHash // stateHash
)
).toConsumeGas(gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.transferAllAssetsL);
// transferAllAssetsL ⬛ --------> (X) -> 👩
await expect(
await nitroAdjudicator.transferAllAssets(
X.channelId,
proof.outcomeBytes, // outcomeBytes
proof.stateHash // stateHash
)
).toConsumeGas(gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.transferAllAssetsX);
// transferAllAssetsX ⬛ ---------------> 👩
// meta-test here to confirm the total recorded in gas.ts is up to date
// with the recorded costs of each step
expect(
gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.challengeL +
gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.transferAllAssetsL +
gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.challengeX +
gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.transferAllAssetsX
).toEqual(gasRequiredTo.ETHexitSadLedgerFunded.vanillaNitro.total);
});
it(`when exiting a virtual funded (with ETH) channel`, async () => {
// begin setup
await (
await nitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, LforJ.channelId, 0, 10, {
value: 10,
})
).wait();
// end setup
// initially ⬛ -> L -> J -> X -> 👩
// challenge L
const {proof: ledgerProof, finalizesAt: ledgerFinalizesAt} = await challengeChannelAndExpectGas(
LforJ,
MAGIC_ADDRESS_INDICATING_ETH,
gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro.challengeL
);
// challenge J
const {
proof: jointProof,
finalizesAt: jointChannelFinalizesAt,
} = await challengeChannelAndExpectGas(
J,
MAGIC_ADDRESS_INDICATING_ETH,
gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro.challengeJ
);
// challenge X
const {proof, finalizesAt} = await challengeChannelAndExpectGas(
X,
MAGIC_ADDRESS_INDICATING_ETH,
gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro.challengeX
);
// begin wait
await waitForChallengesToTimeOut([ledgerFinalizesAt, jointChannelFinalizesAt, finalizesAt]);
// end wait
// challenge L,J,X + timeout ⬛ -> (L) -> (J) -> (X) -> 👩
await assertEthBalancesAndHoldings(
{Alice: 0, Bob: 0, Ingrid: 0},
{LforJ: amountForAliceAndBob, J: 0, X: 0}
);
await expect(
await nitroAdjudicator.claim({
sourceChannelId: LforJ.channelId,
sourceStateHash: ledgerProof.stateHash,
sourceOutcomeBytes: ledgerProof.outcomeBytes,
sourceAssetIndex: 0,
indexOfTargetInSource: 0,
targetStateHash: jointProof.stateHash,
targetOutcomeBytes: jointProof.outcomeBytes,
targetAssetIndex: 0,
targetAllocationIndicesToPayout: [], // meaning "all"
})
).toConsumeGas(gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro.claimL);
// claimL ⬛ ---------------> (X) -> 👩
await assertEthBalancesAndHoldings(
{Alice: 0, Bob: 0, Ingrid: 0},
{LforJ: 0, J: 0, X: amountForAliceAndBob}
);
await expect(
await nitroAdjudicator.transferAllAssets(
X.channelId,
proof.outcomeBytes, // outcomeBytes
proof.stateHash // stateHash
)
).toConsumeGas(gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro.transferAllAssetsX);
// transferAllAssetsX ⬛ ----------------------> 👩
await assertEthBalancesAndHoldings(
{Alice: amountForAlice, Bob: amountForBob, Ingrid: 0},
{LforJ: 0, J: 0, X: 0}
);
// meta-test here to confirm the total recorded in gas.ts is up to date
// with the recorded costs of each step
expect(
(Object.values(gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro) as number[]).reduce(
(a, b) => a + b
) - gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro.total
).toEqual(gasRequiredTo.ETHexitSadVirtualFunded.vanillaNitro.total);
});
}); | the_stack |
module VORLON {
declare var BABYLON;
/**
* Represents a node in a tree.
* Composed of a div wrapper that can have classes :
* tree-node : always, represents the type TreeNodeHTMLElement
* tree-node-with-children : if element has children
* tree-node-folded : if the node is folded, ie its children are hidden
* tree-node-hidden : if the node is hidden, ie its parent is folded
* In the wrapper div, we have :
* dropDownButton : if the node has children, allows to fold and unfold children
* when user clicks on it
* content : the content to be displayed
* features : optionnal features
*/
class TreeNodeHTMLElement {
//ATTRIBUTES
dashboard : BabylonInspectorDashboard;
wrapper : HTMLElement;
dropDownButton : HTMLElement;
icon : HTMLElement;
content : HTMLElement;
features : HTMLElement;
parent : TreeNodeHTMLElement;
children : Array<TreeNodeHTMLElement>;
hasChildren : boolean;
isFolded : boolean;
isHidden : boolean;
//CONSTRUCTOR
constructor(dashboard : BabylonInspectorDashboard, contentValue : any) {
this.dashboard = dashboard;
this.children = [];
this.wrapper = document.createElement('div');
this.wrapper.className = 'tree-node tree-node-hidden tree-node-folded';
this.content = document.createElement('div');
this.content.className = 'tree-node-content';
this.content.innerHTML = contentValue;
this.wrapper.appendChild(this.content);
this.features = document.createElement('div');
this.features.className = 'tree-node-features';
this.wrapper.appendChild(this.features);
this.hasChildren = false;
this.isFolded = true;
this.isHidden = true;
}
//REQUESTS
/**
* Add a child to the node.
* @param child
*/
public addChild(child : TreeNodeHTMLElement) {
if (!this.hasChildren) {
this.hasChildren = true;
this.createDropdownIcon();
this._prepend(this.wrapper, this.dropDownButton);
this.wrapper.className += ' tree-node-with-children';
}
this.wrapper.appendChild(child.wrapper);
this.children.push(child);
child.parent = this;
}
/**
* Add a feature (a button, image or whatever)
* @param feature
*/
public addFeature(feature : HTMLElement) {
this.features.appendChild(feature);
}
/**
* Create a dropdown icon with event listener on click.
* @returns {any}
* @private
*/
createDropdownIcon () {
var dropDown = document.createElement('div');
dropDown.innerHTML = '+';
dropDown.className = 'tree-node-button folded-button';
dropDown.addEventListener('click', () => {
if (this.isFolded) {
dropDown.innerHTML = '-';
this.unfold();
} else {
dropDown.innerHTML = '+';
this.fold();
}
});
this.dropDownButton = dropDown;
}
/**
* Fold node
*/
public fold () {
if (this.isFolded) {
return;
}
this.wrapper.className += " tree-node-folded";
this.isFolded = true;
for (var i = 0; i < this.children.length; ++i) {
var child : TreeNodeHTMLElement = this.children[i];
child.hide();
}
}
/**
* Hide node
*/
public hide () {
if (this.isHidden) {
return;
}
this.isHidden = true;
this.wrapper.className += ' tree-node-hidden';
}
/**
* Unhide node
*/
public unhide() {
if (!this.isHidden) {
return;
}
this.isHidden = false;
this.wrapper.classList.remove('tree-node-hidden');
}
/**
* Unfold node
*/
public unfold () {
if (!this.isFolded) {
return;
}
this.wrapper.classList.remove('tree-node-folded');
this.isFolded = false;
for (var i = 0; i < this.children.length; ++i) {
var child : TreeNodeHTMLElement = this.children[i];
child.unhide();
}
}
//TOOLS
_prepend = (parent : HTMLElement, child : HTMLElement) => {
parent.insertBefore(child, parent.firstChild);
}
}
/**
* Tree node elements with a type represented by an small icon
*/
class TypeTreeNodeHTMLElement extends TreeNodeHTMLElement {
icon : HTMLElement;
type : string;
constructor(dashboard, content, type) {
super(dashboard, content);
this.type = type;
this.createAndAddTypeIcon(this.type);
}
/**
* Create a type icon, its background is the image found at
* imgURL.
*/
createAndAddTypeIcon(iconType) {
var typeIcon = document.createElement('div');
typeIcon.className = 'tree-node-type-icon tree-node-type-icon-' + iconType;
this.icon = typeIcon;
this._prepend(this.wrapper, this.icon);
}
}
/**
* Node to display a property.
* Constructor must be provided with property name and value.
* Node content will be <span> property name : </span> property value
*/
class PropertyTreeNodeHTMLElement extends TreeNodeHTMLElement {
constructor(dashboard : BabylonInspectorDashboard, propertyName : string, propertyValue : string) {
super(dashboard, "<span>" + propertyName + " : " + "</span>" + propertyValue);
}
}
/**
* Node to display a color property. Property with color sample added
* in features.
*/
class ColorPropertyTreeNodeHTMLElement extends PropertyTreeNodeHTMLElement {
constructor(dashboard : BabylonInspectorDashboard, propertyName : string, propertyValue : string) {
super(dashboard, propertyName, propertyValue);
var colorSample = this._createColorSample(propertyValue);
this.addFeature(colorSample);
}
/**
* Create a color sample which background colored in colorHex.
* @param colorHex
* @returns {any}
* @private
*/
private _createColorSample(colorHex) {
var colorSample = document.createElement('div');
colorSample.className = "tree-node-color-sample";
if (colorHex) {
colorSample.style.backgroundColor = colorHex;
colorSample.style.borderColor = this._isClearColor(colorHex) ? '#000000' : '#ffffff';
}
return colorSample;
}
/**
* True if colorHex is a clear color
* @param colorHex
* @returns {boolean}
* @private
*/
private _isClearColor(colorHex) : boolean {
return (colorHex.charAt(1) == 'f' || colorHex.charAt(1) == 'F')
&& (colorHex.charAt(3) == 'f' || colorHex.charAt(3) == 'F')
&& (colorHex.charAt(5) == 'f' || colorHex.charAt(5) == 'F');
}
}
/**
* Node to display a texture.
* Texture thumbnail which displays texture on click added to features.
*/
class TextureUrlPropertyTreeNodeHTMLElement extends PropertyTreeNodeHTMLElement {
completeURL : string;
imageDisplayed : boolean;
constructor(dashboard : BabylonInspectorDashboard, textureURL, completeURL) {
super(dashboard, 'url', textureURL);
this.completeURL = completeURL;
this.imageDisplayed = false;
var imageViewer = this._createImageViewer();
this.addFeature(imageViewer);
}
/**
* Create texture thumbnail that allows to view texture on click.
* @returns {any}
* @private
*/
private _createImageViewer() : HTMLElement {
var viewerThumbnail = document.createElement('div');
viewerThumbnail.className = 'tree-node-texture-thumbnail';
viewerThumbnail.style.backgroundImage = ('url(' + this.completeURL + ')');
var imageView = document.createElement('div');
imageView.className = 'tree-node-texture-view';
imageView.style.backgroundImage = ('url(' + this.completeURL + ')');
viewerThumbnail.addEventListener('mouseover', () => {
//if image was displayed, hide it
if (this.imageDisplayed) {
return;
}
//else, display it
this.imageDisplayed = true;
this.dashboard.displayer.innerHTML = "";
this.dashboard.displayer.style.display = 'block';
this.dashboard.displayer.appendChild(imageView);
});
viewerThumbnail.addEventListener('mouseout', () => {
//if image was displayed, hide it
if (!this.imageDisplayed) {
return;
}
this.imageDisplayed = false;
this.dashboard.displayer.style.display = 'none';
this.dashboard.displayer.innerHTML = "";
});
//imageView.addEventListener('click', () => {
// this.imageDisplayed = false;
// this.dashboard.displayer.innerHTML = "";
//});
return viewerThumbnail;
}
}
class LightTreeNodeHTMLElement extends TreeNodeHTMLElement {
lightName : string;
lightIsOn : boolean;
constructor(dashboard, lightName, isEnabled) {
super(dashboard, lightName);
this.lightName = lightName;
this.lightIsOn = isEnabled;
var switchBtn = this._createSwitch();
this.addFeature(switchBtn);
}
/**
* Create the on/off switch
* @returns {any}
* @private
*/
private _createSwitch() : HTMLElement {
var switchBtn = document.createElement('div');
switchBtn.className = 'tree-node-light-switch clickable';
if (this.lightIsOn) {
switchBtn.innerHTML = 'ON';
switchBtn.className += ' tree-node-light-switch-on';
} else {
switchBtn.innerHTML = 'OFF';
switchBtn.className += ' tree-node-light-switch-off';
}
switchBtn.addEventListener('click', () => {
var data = {
lightName : this.lightName,
sceneID : (<SceneTreeNodeHTMLElement>(this.parent.parent)).sceneID
}
if (this.lightIsOn) {
this.lightIsOn = false;
switchBtn.innerHTML = 'OFF';
switchBtn.classList.remove('tree-node-light-switch-on');
switchBtn.className += ' tree-node-light-switch-off';
this.dashboard.queryToClient(QueryTypes.TURN_OFF_LIGHT, data);
} else {
this.lightIsOn = true;
switchBtn.innerHTML = 'ON';
switchBtn.classList.remove('tree-node-light-switch-off');
switchBtn.className += ' tree-node-light-switch-on';
this.dashboard.queryToClient(QueryTypes.TURN_ON_LIGHT, data);
}
});
return switchBtn;
}
}
/**
* Node to display a scene.
* Contains the scene ID as an attribute
*/
class SceneTreeNodeHTMLElement extends TreeNodeHTMLElement {
//ATTRIBUTES
sceneID : number;
//CONSTRUCTOR
constructor(dashboard : BabylonInspectorDashboard, sceneID : number) {
super(dashboard, 'Scene n° ' + sceneID);
this.sceneID = sceneID;
}
}
/**
* Node to display a mesh.
*/
class MeshTreeNodeHTMLElement extends TreeNodeHTMLElement {
//ATTRIBUTES
meshName : string;
meshIsSpotted : boolean;
meshIsVisible : boolean;
gizmosVisible : boolean;
//CONSTRUCTOR
constructor(dashboard : BabylonInspectorDashboard, meshName : string, visible : boolean) {
super(dashboard, meshName);
this.meshName = meshName;
this.meshIsSpotted = false;
this.meshIsVisible = visible;
this.gizmosVisible = false;
var spotMeshButton = this._createSpotMeshButton();
this.addFeature(spotMeshButton);
var displaySwitch = this._createSwitch();
this.addFeature(displaySwitch);
var gizmosSwitch = this._createGizmoSwitch();
this.addFeature(gizmosSwitch);
}
//REQUESTS
//TOOLS
/**
* Create a switch to spot the mesh in the scene
* @returns {any}
* @private
*/
private _createSpotMeshButton() : HTMLElement {
var spotMeshCheckbox = document.createElement('div');
spotMeshCheckbox.innerHTML = 'Spot mesh';
var cb = document.createElement('div');
cb.className = "tree-node-features-element tree-node-spot-mesh-button tree-node-spot-mesh-button-off clickable"
cb.addEventListener('click', () => {
var data = {
meshName: this.meshName,
sceneID: (<SceneTreeNodeHTMLElement>(this.parent.parent)).sceneID
}
if (this.meshIsSpotted) {
this.meshIsSpotted = false;
cb.classList.remove('tree-node-spot-mesh-button-on');
cb.className += ' tree-node-spot-mesh-button-off';
this.dashboard.queryToClient(QueryTypes.UNSPOT_MESH, data);
} else {
this.meshIsSpotted = true;
cb.classList.remove('tree-node-spot-mesh-button-off');
cb.className += ' tree-node-spot-mesh-button-on';
this.dashboard.queryToClient(QueryTypes.SPOT_MESH, data);
}
});
spotMeshCheckbox.appendChild(cb);
return spotMeshCheckbox;
}
/**
* Create a switch to hide/display the mesh
* @returns {any}
* @private
*/
private _createSwitch() : HTMLElement {
var switchBtn = document.createElement('div');
switchBtn.className = 'tree-node-mesh-switch';
if (this.meshIsVisible) {
switchBtn.innerHTML = 'ON';
switchBtn.className += 'tree-node-features-element tree-node-mesh-switch-on clickable';
} else {
switchBtn.innerHTML = 'OFF';
switchBtn.className += ' tree-node-mesh-switch-off';
}
switchBtn.addEventListener('click', () => {
var data = {
meshName : this.meshName,
sceneID : (<SceneTreeNodeHTMLElement>(this.parent.parent)).sceneID
};
if (this.meshIsVisible) {
this.meshIsVisible = false;
switchBtn.innerHTML = 'OFF';
switchBtn.classList.remove('tree-node-mesh-switch-on');
switchBtn.className += ' tree-node-mesh-switch-off';
this.dashboard.queryToClient(QueryTypes.HIDE_MESH, data);
} else {
this.meshIsVisible = true;
switchBtn.innerHTML = 'ON';
switchBtn.classList.remove('tree-node-mesh-switch-off');
switchBtn.className += ' tree-node-mesh-switch-on';
this.dashboard.queryToClient(QueryTypes.DISPLAY_MESH, data);
}
});
return switchBtn;
}
/**
* Create a switch than displays or hide the axes (gizmos) of the mesh..
* @returns {any}
* @private
*/
private _createGizmoSwitch() : HTMLElement {
var gizmosBtn = document.createElement('div');
gizmosBtn.className = 'tree-node-features-element tree-node-mesh-gizmo clickable';
gizmosBtn.innerHTML = 'gizmo off';
gizmosBtn.className += ' tree-node-mesh-gizmo-off';
gizmosBtn.addEventListener('click', () => {
var data = {
meshName : this.meshName,
sceneID : (<SceneTreeNodeHTMLElement>(this.parent.parent)).sceneID
};
if (this.gizmosVisible) {
this.gizmosVisible = false;
gizmosBtn.innerHTML = 'gizmo off';
gizmosBtn.classList.remove('tree-node-mesh-gizmo-on');
gizmosBtn.className += ' tree-node-mesh-gizmo-off';
this.dashboard.queryToClient(QueryTypes.HIDE_MESH_GIZMO, data);
} else {
this.gizmosVisible = true;
gizmosBtn.innerHTML = 'gizmo on';
gizmosBtn.classList.remove('tree-node-mesh-gizmo-off');
gizmosBtn.className += ' tree-node-mesh-gizmo-on';
this.dashboard.queryToClient(QueryTypes.DISPLAY_MESH_GIZMO, data);
}
});
return gizmosBtn;
}
}
/**
* Node to display an animation.
* Features : play/pause and stop buttons (disabled).
*/
class AnimationTreeNodeHTMLElement extends TreeNodeHTMLElement {
animationIsStarted : boolean;
animationIsStopped : boolean;
animationIsPaused : boolean;
playBtn : HTMLElement;
stopBtn : HTMLElement;
animName : string;
targetType : AnimTargetTypes;
constructor(dashboard : BabylonInspectorDashboard, animName : string, targetType : AnimTargetTypes, stopped : boolean) {
super(dashboard, animName);
this.animName = animName;
this.targetType = targetType;
this.animationIsStopped = stopped;
this.animationIsPaused = false;
this.animationIsStarted = !stopped;
//this._createPlayStopIcons();
}
private _createPlayStopIcons() {
//Create buttons and set appropriate class names
this.playBtn = document.createElement('button');
this.stopBtn = document.createElement('button');
if (this.animationIsStarted) {
this.playBtn.className = 'tree-node-features-element tree-node-animation-button tree-node-animation-button-pause';
this.stopBtn.className = 'tree-node-features-element tree-node-animation-button tree-node-animation-button-stop';
} else {
this.playBtn.className = 'tree-node-features-element tree-node-animation-button tree-node-animation-button-play';
this.stopBtn.className = 'tree-node-features-element tree-node-animation-button tree-node-animation-button-stop-pressed';
}
// Event listeners
this.playBtn.addEventListener('click', () => {
if (!this.animationIsStarted) {
this._startAnimation();
} else if (this.animationIsPaused) {
this.unpauseAnimation();
} else {
this._pauseAnimation();
}
});
this.stopBtn.addEventListener('click', () => {
if (!this.animationIsStarted) {
return;
}
this._stopAnimation();
});
// Add to features list
this.addFeature(this.playBtn);
this.addFeature(this.stopBtn);
}
private _startAnimation() {
if (!this.animationIsStopped) {
return;
}
this.animationIsStarted = true;
this.animationIsStopped = false;
//play-pause button has icon pause
this.playBtn.classList.remove('tree-node-animation-button-play');
this.playBtn.className += ' tree-node-animation-button-pause';
// stop button has icon unpressed
this.stopBtn.classList.remove('tree-node-animation-button-stop-pressed');
this.stopBtn.className += ' tree-node-animation-button-stop';
this.dashboard.queryToClient(QueryTypes.START_ANIM, {
animName : this.animName,
animTargetType : this.targetType,
animTargetName : this._getTargetName(),
sceneID : this._getSceneID()
});
}
private _pauseAnimation() {
if (this.animationIsPaused || this.animationIsStopped) {
return;
}
this.animationIsPaused = true;
//play-pause button has icon play
this.playBtn.classList.remove('tree-node-animation-button-pause');
this.playBtn.className += ' tree-node-animation-button-play';
this.dashboard.queryToClient(QueryTypes.PAUSE_ANIM, {
animName : this.animName,
animTargetType : this.targetType,
animTargetName : this._getTargetName(),
sceneID : this._getSceneID()
});
}
private unpauseAnimation() {
if (!this.animationIsPaused) {
return;
}
this.animationIsPaused = false;
//play-pause button has icon pause
this.playBtn.classList.remove('tree-node-animation-button-play');
this.playBtn.className += ' tree-node-animation-button-pause';
this.dashboard.queryToClient(QueryTypes.UNPAUSE_ANIM, {
animName : this.animName,
animTargetType : this.targetType,
animTargetName : this._getTargetName(),
sceneID : this._getSceneID()
});
}
private _stopAnimation() {
if (!this.animationIsStarted) {
return;
}
this.animationIsStarted = false;
this.animationIsStopped = true;
this.animationIsPaused = false;
//play-pause button has icon play
this.playBtn.classList.remove('tree-node-animation-button-pause');
this.playBtn.className += ' tree-node-animation-button-play';
//stop button has icon stop pressed
this.stopBtn.classList.remove('tree-node-animation-button-stop');
this.stopBtn.className += ' tree-node-animation-button-stop-pressed';
this.dashboard.queryToClient(QueryTypes.STOP_ANIM, {
animName : this.animName,
animTargetType : this.targetType,
animTargetName : this._getTargetName(),
sceneID : this._getSceneID()
});
}
/**
* Find the name of the object targeted by the animation.
* @returns {string}
* @private
*/
private _getTargetName() : string {
var targetName : string;
switch (this.targetType) {
case AnimTargetTypes.MESH :
targetName = (<MeshTreeNodeHTMLElement>(this.parent.parent)).meshName;
break;
default :
break;
}
return targetName;
}
private _getSceneID() : number {
var sceneID : number;
switch (this.targetType) {
case AnimTargetTypes.MESH :
sceneID = (<SceneTreeNodeHTMLElement>(this.parent.parent.parent.parent)).sceneID;
break;
default :
break;
}
return sceneID;
}
}
/**
* Class that generates the tree of data.
*/
class DataTreeGenerator {
//ATTRIBUTES
dashboard : BabylonInspectorDashboard;
//CONSTRCUTOR
constructor(dashboard) {
this.dashboard = dashboard;
}
/**
* Generate a material node.
* @param materialData
* @param clientURL
* @returns {VORLON.PropertyTreeNodeHTMLElement}
* @private
*/
private _generateMaterialNode(materialData, clientURL) : TreeNodeHTMLElement {
var materialNode = new PropertyTreeNodeHTMLElement(this.dashboard, "material", ""); {
var materialPropertyNode:PropertyTreeNodeHTMLElement;
materialPropertyNode = new ColorPropertyTreeNodeHTMLElement(this.dashboard, "diffuseColor", materialData.diffuseColor);
materialNode.addChild(materialPropertyNode);
materialPropertyNode = new ColorPropertyTreeNodeHTMLElement(this.dashboard, "ambientColor", materialData.ambientColor);
materialNode.addChild(materialPropertyNode);
materialPropertyNode = new ColorPropertyTreeNodeHTMLElement(this.dashboard, "emissiveColor", materialData.emissiveColor);
materialNode.addChild(materialPropertyNode);
materialPropertyNode = new ColorPropertyTreeNodeHTMLElement(this.dashboard, "specularColor", materialData.specularColor);
materialNode.addChild(materialPropertyNode);
if (materialData.diffuseTexture) {
materialPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "diffuseTexture", materialData.diffuseTexture.name);
{
var texturePropertyNode:TreeNodeHTMLElement;
texturePropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "name", materialData.diffuseTexture.name);
materialPropertyNode.addChild(texturePropertyNode);
texturePropertyNode = new TextureUrlPropertyTreeNodeHTMLElement(this.dashboard,
materialData.diffuseTexture.url,
clientURL + materialData.diffuseTexture.url);
materialPropertyNode.addChild(texturePropertyNode);
}
materialNode.addChild(materialPropertyNode);
}
}
return materialNode;
}
/**
* Generate an animation node
* @param animations
* @returns {VORLON.PropertyTreeNodeHTMLElement}
* @private
*/
private _generateAnimationsNode(animations) : TreeNodeHTMLElement {
var allAnimationsNode = new PropertyTreeNodeHTMLElement(this.dashboard, "animations", "");
animations.forEach(anim => {
var animNode = new AnimationTreeNodeHTMLElement(this.dashboard, anim.name, AnimTargetTypes.MESH, anim.stopped);
{
var animPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "name", anim.name);
animNode.addChild(animPropertyNode);
animPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "target property", anim.targetProperty);
animNode.addChild(animPropertyNode);
animPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "frame per second", anim.framePerSecond);
animNode.addChild(animPropertyNode);
animPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "running", anim.stopped);
animNode.addChild(animPropertyNode);
animPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "begin frame", anim.beginFrame);
animNode.addChild(animPropertyNode);
animPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "end frame", anim.endFrame);
animNode.addChild(animPropertyNode);
}
allAnimationsNode.addChild(animNode);
});
return allAnimationsNode;
}
/**
* Generate the tree of meshes
* @param meshesData
* @param clientURL
* @returns {VORLON.TypeTreeNodeHTMLElement}
*/
generateMeshesTree(meshesData, clientURL) : TreeNodeHTMLElement {
//Generate node containing all meshes
var allMeshesNode = new TypeTreeNodeHTMLElement(this.dashboard, "Meshes", "mesh");
// Generate one node for each mesh
meshesData.forEach(meshData => {
var meshNode = new MeshTreeNodeHTMLElement(this.dashboard, meshData.name, meshData.isVisible); {
// Generate one node for each property
var propertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "name", meshData.name);
meshNode.addChild(propertyNode);
propertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "position",
"(" + meshData.position.x + ", " + meshData.position.y + ", " + meshData.position.z + ")");
meshNode.addChild(propertyNode);
propertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "rotation",
"(" + meshData.rotation.x + ", " + meshData.rotation.y + ", " + meshData.rotation.z + ")");
meshNode.addChild(propertyNode);
propertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "scaling",
"(" + meshData.scaling.x + ", " + meshData.scaling.y + ", " + meshData.scaling.z + ")");
meshNode.addChild(propertyNode);
propertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "bounding box center",
"(" + meshData.boundingBoxCenter.x + ", " + meshData.boundingBoxCenter.y + ", " + meshData.boundingBoxCenter.z + ")");
meshNode.addChild(propertyNode);
if(meshData.animations) {
propertyNode = this._generateAnimationsNode(meshData.animations);
meshNode.addChild(propertyNode);
}
if (meshData.material) {
propertyNode = this._generateMaterialNode(meshData.material, clientURL);
meshNode.addChild(propertyNode);
}
//TODO factorise avec plus haut
if (meshData.multiMaterial) {
propertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "multi material", "");
var subMaterialNode;
meshData.multiMaterial.subMaterials.forEach((subMaterialData, index) => {
subMaterialNode = this._generateMaterialNode(subMaterialData, clientURL);
propertyNode.addChild(subMaterialNode);
});
meshNode.addChild(propertyNode);
}
}
allMeshesNode.addChild(meshNode);
});
return allMeshesNode;
}
/**
* Generate the tree of textures
* @param texturesData
* @param clientURL
* @returns {VORLON.TreeNodeHTMLElement}
*/
generateTexturesTree(texturesData, clientURL) : TreeNodeHTMLElement {
var allTexturesNode = new TreeNodeHTMLElement(this.dashboard, "Textures");
texturesData.forEach(txtrData => {
var txtrNode = new TreeNodeHTMLElement(this.dashboard, txtrData.name);
{
var texturePropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "name", txtrData.name);
txtrNode.addChild(texturePropertyNode);
texturePropertyNode = new TextureUrlPropertyTreeNodeHTMLElement(this.dashboard,
txtrData.url,
clientURL + txtrData.url);
txtrNode.addChild(texturePropertyNode);
}
allTexturesNode.addChild(txtrNode);
});
return allTexturesNode;
}
/**
* Generate the tree of the active camera.
* @param camData
* @returns {VORLON.TypeTreeNodeHTMLElement}
*/
generateActiveCameraNode(camData) : TreeNodeHTMLElement {
var camNode = new TypeTreeNodeHTMLElement(this.dashboard, "Active camera", "camera");
var camPropertyNode;
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "name", camData.name);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "type", camData.type);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "mode", camData.mode);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "layer mask", camData.layerMask);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "position",
"(" + camData.position.x + ", " + camData.position.y + ", " + camData.position.z + ")");
camNode.addChild(camPropertyNode);
if (camData.type == 'FreeCamera') {
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "speed", camData.speed);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "rotation",
"(" + camData.rotation.x + ", " + camData.rotation.y + ", " + camData.rotation.z + ")");
camNode.addChild(camPropertyNode);
}
if (camData.type == 'ArcRotateCamera') {
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "alpha", camData.alpha);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "beta", camData.beta);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "radius", camData.radius);
camNode.addChild(camPropertyNode);
}
if (camData.animations) {
camPropertyNode = this._generateAnimationsNode(camData.animations);
camNode.addChild(camPropertyNode);
}
return camNode;
}
/**
* Generate the tree of cameras.
* @param camerasData
* @returns {VORLON.TypeTreeNodeHTMLElement}
*/
generateCamerasTree(camerasData) : TreeNodeHTMLElement {
var allCamerasNode = new TypeTreeNodeHTMLElement(this.dashboard, "Cameras", "camera");
camerasData.forEach(camData => {
var camNode = new TreeNodeHTMLElement(this.dashboard, camData.name); {
var camPropertyNode;
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "name", camData.name);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "type", camData.type);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "mode", camData.mode);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "layer mask", camData.layerMask);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "position",
"(" + camData.position.x + ", " + camData.position.y + ", " + camData.position.z + ")");
camNode.addChild(camPropertyNode);
if (camData.type == 'FreeCamera') {
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "speed", camData.speed);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "rotation",
"(" + camData.rotation.x + ", " + camData.rotation.y + ", " + camData.rotation.z + ")");
camNode.addChild(camPropertyNode);
}
if (camData.type == 'ArcRotateCamera') {
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "alpha", camData.alpha);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "beta", camData.beta);
camNode.addChild(camPropertyNode);
camPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "radius", camData.radius);
camNode.addChild(camPropertyNode);
}
if (camData.animations) {
camPropertyNode = this._generateAnimationsNode(camData.animations);
camNode.addChild(camPropertyNode);
}
}
allCamerasNode.addChild(camNode);
});
return allCamerasNode;
}
/**
* Generate the tree of lights.
* @param lightsData
* @returns {VORLON.TypeTreeNodeHTMLElement}
*/
generateLightsTree(lightsData) : TreeNodeHTMLElement {
var allLightsNode = new TypeTreeNodeHTMLElement(this.dashboard, "Lights", "light");
lightsData.forEach(lightData => {
var lightNode = new LightTreeNodeHTMLElement(this.dashboard, lightData.name, lightData.isEnabled); {
var lightPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "name", lightData.name);
lightNode.addChild(lightPropertyNode);
lightPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "type", lightData.type);
lightNode.addChild(lightPropertyNode);
if (lightData.type != "HemisphericLight") {
lightPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "position",
"(" + lightData.position.x + ", " + lightData.position.y + ", " + lightData.position.z + ")");
lightNode.addChild(lightPropertyNode);
}
lightPropertyNode = new ColorPropertyTreeNodeHTMLElement(this.dashboard, "diffuse", lightData.diffuse);
lightNode.addChild(lightPropertyNode);
lightPropertyNode = new ColorPropertyTreeNodeHTMLElement(this.dashboard, "specular", lightData.specular);
lightNode.addChild(lightPropertyNode);
lightPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "intensity", lightData.intensity);
lightNode.addChild(lightPropertyNode);
if (lightData.type == "HemisphericLight") {
lightPropertyNode = new PropertyTreeNodeHTMLElement(this.dashboard, "direction",
"(" + lightData.direction.x + ", " + lightData.direction.y + ", " + lightData.direction.z + ")");
lightNode.addChild(lightPropertyNode);
lightPropertyNode = new ColorPropertyTreeNodeHTMLElement(this.dashboard, "groundColor", lightData.groundColor);
lightNode.addChild(lightPropertyNode);
}
}
allLightsNode.addChild(lightNode);
});
return allLightsNode;
}
/**
* Generate the tree of functions before render.
* @param beforeRenderCallbacksData
* @returns {VORLON.TreeNodeHTMLElement}
*/
generateBeforeRenderCallbacksTree(beforeRenderCallbacksData) : TreeNodeHTMLElement {
var allBeforeRenderCallBacksNode = new TreeNodeHTMLElement(this.dashboard, 'functions registered before render');
beforeRenderCallbacksData.forEach((fct, index) => {
var functionNode = new TreeNodeHTMLElement(this.dashboard, index); {
var propertyFunctionNode = new PropertyTreeNodeHTMLElement(this.dashboard, "body", fct.body);
functionNode.addChild(propertyFunctionNode);
}
allBeforeRenderCallBacksNode.addChild(functionNode);
});
return allBeforeRenderCallBacksNode;
}
/**
* Generate the tree of functions after render.
* @param afterRenderCallbacksData
* @returns {VORLON.TreeNodeHTMLElement}
*/
generateAfterRenderCallbacksTree(afterRenderCallbacksData) : TreeNodeHTMLElement {
var allAfterRenderCallBacksNode = new TreeNodeHTMLElement(this.dashboard, 'functions registered after render');
afterRenderCallbacksData.forEach((fct, index) => {
var functionNode = new TreeNodeHTMLElement(this.dashboard, index); {
var propertyFunctionNode = new PropertyTreeNodeHTMLElement(this.dashboard, "body", fct.body);
functionNode.addChild(propertyFunctionNode);
}
allAfterRenderCallBacksNode.addChild(functionNode);
});
return allAfterRenderCallBacksNode;
}
/**
* Generate tree containging all data.
* Extra curly brackets {} are added in order to render tree view in code.
* @param scenesData
* @returns {VORLON.TreeNodeHTMLElement}
*/
public generateScenesTree(scenesData, clientURL) : TreeNodeHTMLElement {
//Tree root
var treeRoot = new TreeNodeHTMLElement(this.dashboard, "Scenes explorer");
//Generate scene nodes
scenesData.forEach((scene, index) => {
var sceneNode = new SceneTreeNodeHTMLElement(this.dashboard, index);{
if(scene.activeCameraData) {
var activeCameraNode = this.generateActiveCameraNode(scene.activeCameraData);
sceneNode.addChild(activeCameraNode);
}
if(scene.meshesData) {
var allMeshesNode = this.generateMeshesTree(scene.meshesData, clientURL);
sceneNode.addChild(allMeshesNode);
}
if(scene.texturesData) {
var allTexturesNode = this.generateTexturesTree(scene.texturesData, clientURL);
sceneNode.addChild(allTexturesNode);
}
if(scene.camerasData) {
var allCamerasNode = this.generateCamerasTree(scene.camerasData);
sceneNode.addChild(allCamerasNode);
}
if (scene.lightsData) {
var allLightsNode = this.generateLightsTree(scene.lightsData);
sceneNode.addChild(allLightsNode);
}
if (scene.beforeRenderCallbacksData) {
var allBeforeRenderCallbacksNode = this.generateBeforeRenderCallbacksTree(scene.beforeRenderCallbacksData);
sceneNode.addChild(allBeforeRenderCallbacksNode);
}
if (scene.afterRenderCallbacksData) {
var allAfterRenderCallbacksNode = this.generateAfterRenderCallbacksTree(scene.afterRenderCallbacksData);
sceneNode.addChild(allAfterRenderCallbacksNode);
}
}
treeRoot.addChild(sceneNode)
});
return treeRoot;
}
}
export class BabylonInspectorDashboard extends DashboardPlugin {
private id : string;
private _dataTreeGenerator : DataTreeGenerator;
private treeRoot : TreeNodeHTMLElement;
private _containerDiv : HTMLElement;
displayer : HTMLElement
/**
* Do any setup you need, call super to configure
* the plugin with html and css for the dashboarde
*/
constructor() {
// name , html for dash css for dash
super("babylonInspector", "control.html", "control.css");
this._ready = false;
this.id = 'BABYLONINSPECTOR';
this._dataTreeGenerator = new DataTreeGenerator(this);
this.treeRoot = null;
}
/**
* Return unique id for your plugin
*/
public getID():string {
return this.id;
}
/**
* When we get a message from the client, handle it
*/
public onRealtimeMessageReceivedFromClientSide(receivedObject:any):void {
switch (receivedObject.messageType) {
case 'SCENES_DATA' :
var scenesData = receivedObject.data;
this._refreshTree(scenesData, receivedObject.clientURL);
break;
default :
break;
}
}
/**
* Send a query to client of type queryType containing some data.
* @param queryType
* @param data
*/
public queryToClient(queryType : QueryTypes, data : any) {
var message = {
queryType: queryType,
data: data
};
this.sendToClient(message);
}
/**
* This code will run on the dashboard
* Start dashboard code
* uses _insertHtmlContentAsync to insert the control.html content
* into the dashboard
* @param div
*/
public startDashboardSide(div:HTMLDivElement = null):void {
this._insertHtmlContentAsync(div, (filledDiv) => {
this._containerDiv = filledDiv;
this.displayer = <HTMLElement> this._containerDiv.querySelector("#babylonInspector-displayer");
this._ready = true;
});
}
//TOOLS
/**
* Refresh tree.
* @param scenesData
* @private
*/
private _refreshTree(scenesData, clientURL) {
this.treeRoot = this._dataTreeGenerator.generateScenesTree(scenesData, clientURL);
this.treeRoot.unhide();
this.treeRoot.unfold();
this._containerDiv.appendChild(this.treeRoot.wrapper);
}
}
//Register the plugin with vorlon core
Core.RegisterDashboardPlugin(new BabylonInspectorDashboard());
} | the_stack |
import { DebugProtocol } from 'vscode-debugprotocol';
import { NotebookDocument, NotebookCell, DebugSession, DebugAdapterTracker, Uri } from 'vscode';
import * as path from 'path';
import { JavaScriptKernel } from '../jsKernel';
import { Compiler } from '../compiler';
import { createDeferred, noop } from '../../coreUtils';
const activeDebuggers = new WeakMap<NotebookDocument, Debugger>();
export class Debugger implements DebugAdapterTracker {
public readonly _attached = createDeferred<void>();
private configurationDoneSequence = 0;
public get ready() {
return this._attached.promise;
}
constructor(
public readonly document: NotebookDocument,
public readonly debugSession: DebugSession,
public readonly kernel: JavaScriptKernel,
public readonly cell?: NotebookCell
) {
activeDebuggers.set(document, this);
}
public onError?(error: Error): void {
console.error('Error in debug adapter tracker', error);
}
public onWillReceiveMessage(message: DebugProtocol.ProtocolMessage) {
// VS Code -> Debug Adapter
visitSources(
message,
(source) => {
if (source.path) {
const cellPath = this.dumpCell(source.path);
if (cellPath) {
source.path = cellPath;
}
}
},
(request: { source?: DebugProtocol.Source }, locations?: { line?: number; column?: number }[]) => {
if (!request.source?.path || !locations) {
return;
}
const cell = Compiler.getCellFromTemporaryPath(request.source.path);
if (!cell) {
return;
}
const codeObject = Compiler.getCodeObject(cell);
if (!codeObject) {
return;
}
const sourceMap = Compiler.getSourceMapsInfo(codeObject);
if (!sourceMap) {
return;
}
// const cache = (sourceMap.mappingCache = sourceMap.mappingCache || new Map<string, [number, number]>());
locations.forEach((location) => {
const mappedLocation = Compiler.getMappedLocation(codeObject, location, 'VSCodeToDAP');
location.line = mappedLocation.line;
location.column = mappedLocation.column;
});
},
noop,
'VSCodeToDAP'
);
}
public onDidSendMessage(message: DebugProtocol.ProtocolMessage) {
// Debug Adapter -> VS Code
visitSources(
message,
(source) => {
if (source.path) {
const cell = Compiler.getCellFromTemporaryPath(source.path);
if (cell && !cell.document.isClosed) {
source.name = path.basename(cell.document.uri.path);
if (cell.index >= 0) {
source.name += `, Cell ${cell.index + 1}`;
}
source.path = cell.document.uri.toString();
}
}
},
(request: { source?: DebugProtocol.Source }, locations?: { line?: number; column?: number }[]) => {
if (!request.source?.path || !locations) {
return;
}
const cell = Compiler.getCellFromTemporaryPath(request.source.path);
if (!cell) {
return;
}
const codeObject = Compiler.getCodeObject(cell);
if (!codeObject) {
return;
}
const sourceMap = Compiler.getSourceMapsInfo(codeObject);
if (!sourceMap) {
return;
}
// const cache = (sourceMap.mappingCache = sourceMap.mappingCache || new Map<string, [number, number]>());
locations.forEach((location) => {
const mappedLocation = Compiler.getMappedLocation(codeObject, location, 'DAPToVSCode');
location.line = mappedLocation.line;
location.column = mappedLocation.column;
});
},
(body: DebugProtocol.ExceptionInfoResponse['body']) => {
if (body.details?.stackTrace) {
const dummmyError = new Error('');
dummmyError.stack = body.details.stackTrace;
body.details.stackTrace = Compiler.fixCellPathsInStackTrace(this.document, dummmyError, true);
}
},
'DAPToVSCode'
);
if (message.type === 'response') {
// There are two debug sessions when debugging node.js
// A wrapper and the real debug session.
// Hence, remember the fact that we could have two debug trackers.
// We are only interested in `attach` having been completed after we have received configuration done.
const response = message as DebugProtocol.Response;
if (
response.command === 'attach' &&
response.success &&
response.seq > this.configurationDoneSequence &&
this.configurationDoneSequence > 0
) {
this._attached.resolve();
}
if (response.command === 'configurationDone' && response.success) {
this.configurationDoneSequence = response.seq;
}
}
}
/**
* Store cell in temporary file and return its path or undefined if uri does not denote a cell.
*/
private dumpCell(uri: string): string | undefined {
try {
const cellUri = Uri.parse(uri, true);
if (cellUri.scheme === 'vscode-notebook-cell') {
// find cell in document by matching its URI
const cell = this.document.getCells().find((c) => c.document.uri.toString() === uri);
if (cell) {
return Compiler.getOrCreateCodeObject(cell).sourceFilename;
}
}
} catch (e) {
// Oops
}
return undefined;
}
}
// this vistor could be moved into the DAP npm module (it must be kept in sync with the DAP spec)
function visitSources(
msg: DebugProtocol.ProtocolMessage,
visitor: (source: DebugProtocol.Source) => void,
remapLocation: (
request: { source?: DebugProtocol.Source },
location?: { line?: number; column?: number }[]
) => void,
fixStackTrace: (body: DebugProtocol.ExceptionInfoResponse['body']) => void,
_direction: 'DAPToVSCode' | 'VSCodeToDAP'
): void {
const sourceHook = (source: DebugProtocol.Source | undefined) => {
if (source) {
visitor(source);
}
};
switch (msg.type) {
case 'event': {
const event = <DebugProtocol.Event>msg;
switch (event.event) {
case 'output':
sourceHook((<DebugProtocol.OutputEvent>event).body.source);
break;
case 'loadedSource':
sourceHook((<DebugProtocol.LoadedSourceEvent>event).body.source);
break;
case 'breakpoint':
sourceHook((<DebugProtocol.BreakpointEvent>event).body.breakpoint.source);
break;
default:
break;
}
break;
}
case 'request': {
const request = <DebugProtocol.Request>msg;
switch (request.command) {
case 'setBreakpoints': {
const args = <DebugProtocol.SetBreakpointsArguments>request.arguments;
sourceHook(args.source);
remapLocation(args, args.breakpoints);
break;
}
case 'breakpointLocations':
sourceHook((<DebugProtocol.BreakpointLocationsArguments>request.arguments).source);
break;
case 'source':
sourceHook((<DebugProtocol.SourceArguments>request.arguments).source);
break;
case 'gotoTargets':
sourceHook((<DebugProtocol.GotoTargetsArguments>request.arguments).source);
break;
default:
break;
}
break;
}
case 'response': {
const response = <DebugProtocol.Response>msg;
if (response.success && response.body) {
switch (response.command) {
case 'stackTrace':
(<DebugProtocol.StackTraceResponse>response).body.stackFrames.forEach((frame) => {
sourceHook(frame.source);
remapLocation(frame, [frame]);
});
break;
case 'loadedSources':
(<DebugProtocol.LoadedSourcesResponse>response).body.sources.forEach((source) =>
sourceHook(source)
);
break;
case 'scopes':
(<DebugProtocol.ScopesResponse>response).body.scopes.forEach((scope) => {
sourceHook(scope.source);
remapLocation(scope, [scope]);
});
break;
case 'setFunctionBreakpoints':
(<DebugProtocol.SetFunctionBreakpointsResponse>response).body.breakpoints.forEach((bp) => {
sourceHook(bp.source);
remapLocation(bp, [bp]);
});
break;
case 'setBreakpoints':
(<DebugProtocol.SetBreakpointsResponse>response).body.breakpoints.forEach((bp) => {
sourceHook(bp.source);
remapLocation(bp, [bp]);
});
break;
case 'exceptionInfo':
fixStackTrace((<DebugProtocol.ExceptionInfoResponse>response).body);
break;
default:
break;
}
}
break;
}
}
} | the_stack |
import { MailActions, MailActionTypes } from '../actions';
import { MailBoxesState, MailboxKey } from '../datatypes';
import { Mailbox } from '../models/mail.model';
import { SafePipe } from '../../shared/pipes/safe.pipe';
export function reducer(
// eslint-disable-next-line unicorn/no-object-as-default-parameter
state: MailBoxesState = {
mailboxes: [],
currentMailbox: null,
decryptKeyInProgress: false,
encryptionInProgress: false,
mailboxKeysMap: new Map(),
},
action: MailActions,
): MailBoxesState {
switch (action.type) {
case MailActionTypes.GET_MAILBOXES: {
return {
...state,
inProgress: true,
};
}
case MailActionTypes.GET_MAILBOXES_SUCCESS: {
const mailboxes = action.payload;
// Filling up primary keys for multiple keys
const mailboxKeysMap = new Map();
mailboxes.forEach((mailbox: Mailbox) => {
const primaryKey: MailboxKey = {};
primaryKey.public_key = mailbox.public_key;
primaryKey.private_key = mailbox.private_key;
primaryKey.fingerprint = mailbox.fingerprint;
primaryKey.key_type = mailbox.key_type;
primaryKey.is_primary = true;
if (mailboxKeysMap.has(mailbox.id) && mailboxKeysMap.get(mailbox.id).length > 0) {
const temporaryKeys = mailboxKeysMap.get(mailbox.id).filter((key: MailboxKey, index: number) => index !== 0);
mailboxKeysMap.set(mailbox.id, [primaryKey, ...temporaryKeys]);
} else {
mailboxKeysMap.set(mailbox.id, [primaryKey]);
}
});
return {
...state,
mailboxes: action.payload.map((item: any, index: number) => {
item.sort_order = item.sort_order ? item.sort_order : index + 1;
item.display_name = SafePipe.processSanitization(item.display_name, false);
item.signature = SafePipe.processSanitization(item.signature, false);
return item;
}),
mailboxKeysMap,
inProgress: false,
currentMailbox: action.payload.find((item: Mailbox) => item.is_enabled),
};
}
case MailActionTypes.SET_DECRYPT_INPROGRESS: {
return {
...state,
decryptKeyInProgress: action.payload,
};
}
case MailActionTypes.SET_DECRYPTED_KEY: {
return {
...state,
decryptKeyInProgress: false,
decryptedKey: action.payload.decryptedKey,
};
}
case MailActionTypes.SET_CURRENT_MAILBOX: {
return {
...state,
currentMailbox: action.payload,
};
}
case MailActionTypes.MAILBOX_SETTINGS_UPDATE: {
return {
...state,
inProgress: true,
};
}
case MailActionTypes.MAILBOX_SETTINGS_UPDATE_SUCCESS: {
const updatedCurrentMailBox: Mailbox = action.payload;
let { currentMailbox } = state;
updatedCurrentMailBox.inProgress = false;
let { mailboxes } = state;
mailboxes = mailboxes.map(mailbox => {
if (mailbox.id === updatedCurrentMailBox.id) {
return { ...updatedCurrentMailBox };
}
return mailbox;
});
if (updatedCurrentMailBox.id === currentMailbox.id) {
currentMailbox = { ...updatedCurrentMailBox };
}
return {
...state,
currentMailbox,
mailboxes,
inProgress: false,
};
}
case MailActionTypes.MAILBOX_SETTINGS_UPDATE_FAILURE: {
return {
...state,
mailboxes: state.mailboxes.map(mailbox => {
if (mailbox.id === action.payload.id) {
mailbox.inProgress = false;
}
return mailbox;
}),
};
}
case MailActionTypes.CREATE_MAILBOX: {
return { ...state, inProgress: true };
}
case MailActionTypes.CREATE_MAILBOX_SUCCESS: {
state.mailboxes = [...state.mailboxes, action.payload];
return { ...state, inProgress: false };
}
case MailActionTypes.CREATE_MAILBOX_FAILURE: {
return { ...state, inProgress: false };
}
case MailActionTypes.SET_DEFAULT_MAILBOX_SUCCESS: {
const updatedCurrentMailBox: Mailbox = action.payload;
let { currentMailbox } = state;
const previousDefaultMailBox = state.mailboxes.find(mailbox => !!mailbox.is_default);
let { mailboxes } = state;
mailboxes = mailboxes.map(mailbox => {
if (mailbox.id === updatedCurrentMailBox.id) {
return { ...updatedCurrentMailBox };
}
if (mailbox.id === previousDefaultMailBox.id) {
return { ...mailbox, is_default: false };
}
return mailbox;
});
if (updatedCurrentMailBox.id === currentMailbox.id) {
currentMailbox = { ...updatedCurrentMailBox };
} else if (previousDefaultMailBox.id === currentMailbox.id) {
currentMailbox = { ...currentMailbox, is_default: false };
}
return {
...state,
currentMailbox,
mailboxes,
};
}
case MailActionTypes.UPDATE_MAILBOX_ORDER: {
return { ...state, isUpdatingOrder: true };
}
case MailActionTypes.UPDATE_MAILBOX_ORDER_SUCCESS: {
return {
...state,
mailboxes: action.payload.mailboxes,
currentMailbox: action.payload.mailboxes[0],
isUpdatingOrder: false,
};
}
case MailActionTypes.DELETE_MAILBOX_SUCCESS: {
return { ...state, mailboxes: state.mailboxes.filter(mailbox => mailbox.id !== action.payload.id) };
}
case MailActionTypes.FETCH_MAILBOX_KEYS: {
return {
...state,
mailboxKeyInProgress: true,
};
}
case MailActionTypes.FETCH_MAILBOX_KEYS_SUCCESS: {
const { mailboxKeysMap } = state;
if (action.payload.updateKeyMap) {
const { keyMap } = action.payload;
for (const mailboxId of [...mailboxKeysMap.keys()]) {
if (mailboxKeysMap.get(mailboxId).length > 0 && keyMap[mailboxId] && keyMap[mailboxId].length > 0) {
const updatedKeys = mailboxKeysMap.get(mailboxId).map((key, index) => {
if (keyMap[mailboxId].length > index + 1) {
return {
...key,
private_key: keyMap[mailboxId][index].private_key,
public_key: keyMap[mailboxId][index].public_key,
};
}
return key;
});
mailboxKeysMap.set(mailboxId, updatedKeys);
}
}
return {
...state,
mailboxKeysMap,
mailboxKeyInProgress: false,
};
}
const mailboxKeys = action.payload.results;
const { mailboxes } = state;
if (mailboxKeys && mailboxKeys.length > 0) {
mailboxes.forEach((mailbox: Mailbox) => {
const specificKeys = mailboxKeys.filter((key: MailboxKey) => key.mailbox === mailbox.id);
if (mailboxKeysMap.has(mailbox.id)) {
const originKeys = mailboxKeysMap.get(mailbox.id);
mailboxKeysMap.set(mailbox.id, [...originKeys, ...specificKeys]);
} else {
mailboxKeysMap.set(mailbox.id, specificKeys);
}
});
}
return {
...state,
mailboxKeysMap,
mailboxKeyInProgress: false,
};
}
case MailActionTypes.FETCH_MAILBOX_KEYS_FAILURE: {
return {
...state,
mailboxKeyInProgress: false,
};
}
case MailActionTypes.ADD_MAILBOX_KEYS: {
return {
...state,
mailboxKeyInProgress: true,
mailboxKeyFailure: false,
};
}
case MailActionTypes.ADD_MAILBOX_KEYS_SUCCESS: {
const newKey = action.payload;
const { mailboxKeysMap } = state;
if (mailboxKeysMap.has(newKey.mailbox)) {
const originKeys = mailboxKeysMap.get(newKey.mailbox);
mailboxKeysMap.set(newKey.mailbox, [...originKeys, newKey]);
} else {
mailboxKeysMap.set(newKey.mailbox, [newKey]);
}
return {
...state,
mailboxKeysMap,
mailboxKeyInProgress: false,
mailboxKeyFailure: false,
};
}
case MailActionTypes.ADD_MAILBOX_KEYS_FAILURE: {
return {
...state,
mailboxKeyInProgress: false,
mailboxKeyFailure: true,
};
}
case MailActionTypes.DELETE_MAILBOX_KEYS: {
return {
...state,
mailboxKeyInProgress: true,
mailboxKeyFailure: false,
};
}
case MailActionTypes.DELETE_MAILBOX_KEYS_SUCCESS: {
const deletedKey = action.payload;
const { mailboxKeysMap } = state;
if (mailboxKeysMap.has(deletedKey.mailbox)) {
const originKeys = mailboxKeysMap.get(deletedKey.mailbox);
mailboxKeysMap.set(
deletedKey.mailbox,
originKeys.filter(key => deletedKey.id !== key.id),
);
}
return {
...state,
mailboxKeysMap,
mailboxKeyInProgress: false,
mailboxKeyFailure: false,
};
}
case MailActionTypes.DELETE_MAILBOX_KEYS_FAILURE: {
return {
...state,
mailboxKeyFailure: true,
mailboxKeyInProgress: false,
};
}
case MailActionTypes.SET_PRIMARY_MAILBOX_KEYS: {
return {
...state,
mailboxKeyInProgress: true,
};
}
case MailActionTypes.SET_PRIMARY_MAILBOX_KEYS_SUCCESS: {
const newPrimaryKey: MailboxKey = action.payload;
// Update mailbox to set key info
const { mailboxes } = state;
let currentPrimaryMailbox: Mailbox;
for (const mailbox of mailboxes) {
if (mailbox.id === newPrimaryKey.mailbox) {
currentPrimaryMailbox = { ...mailbox };
mailbox.public_key = newPrimaryKey.public_key;
mailbox.private_key = newPrimaryKey.private_key;
mailbox.fingerprint = newPrimaryKey.fingerprint;
mailbox.key_type = newPrimaryKey.key_type;
}
}
// Update mailbox key list
const { mailboxKeysMap } = state;
if (mailboxKeysMap.has(newPrimaryKey.mailbox) && mailboxKeysMap.get(newPrimaryKey.mailbox).length > 0) {
for (const [index, key] of mailboxKeysMap.get(newPrimaryKey.mailbox).entries()) {
if (index === 0) {
key.private_key = newPrimaryKey.private_key;
key.public_key = newPrimaryKey.public_key;
key.fingerprint = newPrimaryKey.fingerprint;
key.key_type = newPrimaryKey.key_type;
}
if (key.id === newPrimaryKey.id) {
key.private_key = currentPrimaryMailbox.private_key;
key.public_key = currentPrimaryMailbox.public_key;
key.fingerprint = currentPrimaryMailbox.fingerprint;
key.key_type = currentPrimaryMailbox.key_type;
}
}
}
return {
...state,
mailboxes,
mailboxKeysMap,
mailboxKeyInProgress: false,
};
}
case MailActionTypes.SET_PRIMARY_MAILBOX_KEYS_FAILURE: {
return {
...state,
mailboxKeyInProgress: false,
};
}
case MailActionTypes.RESET_MAILBOX_KEY_OPERATION_STATE: {
return {
...state,
mailboxKeyInProgress: false,
mailboxKeyFailure: false,
};
}
default: {
return state;
}
}
} | the_stack |
import { storage } from 'uxp'
import * as consts from './consts'
import { GlobalVars } from "./globals";
import {
getChildIndex,
isFirstChild,
isLastChild,
isOnlyChild, isRootNode,
sameParentBounds
} from "./node";
import { asBool } from './tools'
import * as tools from './tools'
const CssSelectorParser = require('./node_modules/css-selector-parser/lib/index')
.CssSelectorParser
// import {CssSelectorParser} from 'css-selector-parser'
let cssSelectorParser = new CssSelectorParser()
//cssSelectorParser.registerSelectorPseudos('has')
cssSelectorParser.registerNumericPseudos('root')
cssSelectorParser.registerNumericPseudos('nth-child')
cssSelectorParser.registerSelectorPseudos('first-child')
cssSelectorParser.registerSelectorPseudos('last-child')
cssSelectorParser.registerSelectorPseudos('same-parent-bounds')
cssSelectorParser.registerNestingOperators('>', '+', '~', ' ')
cssSelectorParser.registerAttrEqualityMods('^', '$', '*', '~')
cssSelectorParser.enableSubstitutes()
class CssSelector {
private json: any
/**
* @param {string} selectorText
*/
constructor(selectorText) {
if (!selectorText) {
throw 'CssSelectorがNULLで作成された'
}
// console.log("SelectorTextをパースします",selectorText)
this.json = cssSelectorParser.parse(selectorText.trim())
/*
console.log(
'SelectorTextをパースした',
JSON.stringify(this.json, null, ' '),
)
*/
}
/**
* 擬似クラスの:rootであるか
* @return {boolean}
*/
isRoot() {
const rule = this.json['rule']
if (!rule) return false
const pseudos = rule['pseudos']
// console.log("isRoot() pseudos確認:", pseudos)
return pseudos && pseudos[0].name === 'root'
}
/**
*
* @param {{name:string, parent:*}} node
* @param {{type:string, classNames:string[], id:string, tagName:string, pseudos:*[], nestingOperator:string, rule:*, selectors:*[] }|null} rule
* @param verboseLog
* @return {null|*}
*/
matchRule(node, rule = null, verboseLog = false) {
if (verboseLog) console.log('# matchRule')
if (!rule) {
rule = this.json
}
if (!rule) {
return null
}
let checkNode = node
let ruleRule = rule.rule
switch (rule.type) {
case 'rule': {
if (verboseLog) console.log('## type:rule')
// まず奥へ入っていく
if (ruleRule) {
checkNode = this.matchRule(node, ruleRule, verboseLog)
if (!checkNode) {
return null
}
}
break
}
case 'selectors': {
if (verboseLog) console.log('## type:selectors')
// 複数あり、どれかに適合するかどうか
for (let selector of rule.selectors) {
ruleRule = selector.rule
checkNode = this.matchRule(node, ruleRule, verboseLog)
if (checkNode) break
}
if (!checkNode) {
return null
}
break
}
case 'ruleSet': {
if (verboseLog) console.log('## type:ruleSet')
return this.matchRule(node, ruleRule, verboseLog)
}
default:
return null
}
if (ruleRule && ruleRule.nestingOperator === null) {
if (verboseLog) console.log('nullオペレータ確認をする')
while (checkNode) {
let result = CssSelector.check(checkNode, rule, verboseLog)
if (result) {
if (verboseLog) console.log('nullオペレータで整合したものをみつけた')
return checkNode
}
checkNode = checkNode.parent
}
if (verboseLog)
console.log('nullオペレータで整合するものはみつからなかった')
return null
}
let result = CssSelector.check(checkNode, rule, verboseLog)
if (!result) {
if (verboseLog) console.log('このruleは適合しなかった')
return null
}
if (verboseLog) console.log('check成功')
if (rule.nestingOperator === '>' || rule.nestingOperator == null) {
if (verboseLog)
console.log(
`nestingオペレータ${rule.nestingOperator} 確認のため、checkNodeを親にすすめる`,
)
checkNode = checkNode.parent
}
return checkNode
}
/**
* @param {{name:string, parent:*}} node マスクチェックのために node.maskとすることがある
* @param {{type:string, classNames:string[], id:string, tagName:string, attrs:*[], pseudos:*[], nestingOperator:string, rule:*, selectors:*[] }|null} rule
* @return {boolean}
*/
static check(node, rule, verboseLog = false) {
if (!node) return false
const nodeName = node.name.trim()
const parsedNodeName = cssParseNodeName(nodeName)
if (verboseLog) {
console.log('# rule check')
console.log('- name:', node.name)
console.log(parsedNodeName)
console.log('## 以下のruleと照らし合わせる')
console.log(rule)
}
if (rule.tagName && rule.tagName !== '*') {
if (
rule.tagName !== parsedNodeName.tagName &&
rule.tagName !== nodeName
) {
if (verboseLog) console.log('tagNameが適合しない')
return false
}
}
if (rule.id && rule.id !== parsedNodeName.id) {
if (verboseLog) console.log('idが適合しない')
return false
}
if (rule.classNames) {
if (!parsedNodeName.classNames) {
if (verboseLog) console.log('ruleはclassを求めたがclassが無い')
return false
}
for (let className of rule.classNames) {
if (!parsedNodeName.classNames.find(c => c === className)) {
if (verboseLog) console.log('classが適合しない')
return false
}
}
}
if (rule.attrs) {
// console.log('attrチェック')
for (let attr of rule.attrs) {
if (!this.checkAttr(node, parsedNodeName, attr)) {
return false
}
}
}
if (rule.pseudos) {
if (verboseLog) console.log('## 疑似クラスチェック')
for (let pseudo of rule.pseudos) {
if (!this.checkPseudo(node, pseudo)) {
if (verboseLog) console.log(`- ${pseudo.name} が適合しません`)
return false
}
if (verboseLog) console.log(`- ${pseudo.name} が適合した`)
}
}
//console.log(nodeName)
//console.log(JSON.stringify(parsedNodeName, null, ' '))
if (verboseLog) console.log('このruleは適合した')
return true
}
static checkAttr(node, parsedNodeName, attr) {
switch (attr.name) {
case 'class': {
if (
!CssSelector.namesCheck(
attr.operator,
parsedNodeName.classNames,
attr.value,
)
)
return false
break
}
case 'id': {
if (
!CssSelector.nameCheck(attr.operator, parsedNodeName.id, attr.value)
)
return false
break
}
case 'tag-name': {
if (
!CssSelector.nameCheck(
attr.operator,
parsedNodeName.tagName,
attr.value,
)
)
return false
break
}
case 'type-of':
case 'typeof': {
if (
!CssSelector.nameCheck(
attr.operator,
node.constructor.name,
attr.value,
)
)
return false
break
}
default:
console.log('**error** 未対応の要素名です:', attr.name)
return false
}
return true
}
static checkPseudo(node, pseudo) {
let result = false
switch (pseudo.name) {
case 'nth-child':
const nthChild = parseInt(pseudo.value)
const nodeChildIndex = getChildIndex(node) + 1
result = nthChild === nodeChildIndex
break
case 'first-child':
result = isFirstChild(node)
break
case 'last-child':
result = isLastChild(node)
break
case 'only-child':
result = isOnlyChild(node)
break
case 'same-parent-bounds':
result = sameParentBounds(node)
break
case 'root':
result = isRootNode(node)
break
default:
console.log('**error** 未対応の疑似要素です', pseudo.name)
result = false
break
}
return result
}
/**
* @param {string} op
* @param {string[]} names
* @param value
*/
static namesCheck(op, names, value) {
if (!op || names == null) return false
for (let name of names) {
if (this.nameCheck(op, name, value)) return true
}
return false
}
/**
* @param {string} op
* @param {string} name
* @param value
*/
static nameCheck(op, name, value) {
if (!op || name == null || value == null) return false
switch (op) {
case '=':
return name === value
case '*=':
return name.includes(value) > 0
case '^=':
return name.startsWith(value)
case '$=':
return name.endsWith(value)
case '|=':
if (name === value) return true
return name.startsWith(value + '-')
}
return false
}
}
class CssDeclarations {
private declarations: {}
constructor(declarationBlock: string = null) {
if (declarationBlock) {
this.declarations = parseCssDeclarationBlock(declarationBlock)
} else {
this.declarations = {}
}
}
properties() {
return Object.keys(this.declarations)
}
values(property: string): string[] {
return this.declarations[property]
}
/**
* @param {string} property
* @return {*|null}
*/
first(property) {
const values = this.values(property)
if (values == null) return null
return values[0]
}
setFirst(property, value) {
let values = this.values(property)
if (!values) {
values = this.declarations[property] = []
}
values[0] = value
}
firstAsBool(property) {
return asBool(this.first(property))
}
}
function parseCss(text, errorThrow = true):any {
// コメントアウト処理 エラー時に行数を表示するため、コメント内の改行を残す
//TODO: 文字列内の /* */について正しく処理できない
text = text.replace(/\/\*[\s\S]*?\*\//g, str => {
let replace = ''
for (let c of str) {
if (c === '\n') replace += c
}
return replace
})
// declaration部がなくてもSelectorだけで取得できるようにする NodeNameのパースに使うため
// const tokenizer = /(?<at_rule>\s*@[^;]+;\s*)|((?<selector>(("([^"\\]|\\.)*")|[^{"]+)+)({(?<decl_block>(("([^"\\]|\\.)*")|[^}"]*)*)}\s*)?)/gi
// シングルクオーテーション
const tokenizer = /(?<at_rule>\s*@[^;]+;\s*)|((?<selector>(('([^'\\]|\\.)*')|[^{']+)+)({(?<decl_block>(('([^'\\]|\\.)*')|[^}']*)*)}\s*)?)/gi
const rules = []
let token
while ((token = tokenizer.exec(text))) {
try {
const tokenAtRule = token.groups.at_rule
const tokenSelector = token.groups.selector
const tokenDeclBlock = token.groups.decl_block
if (tokenAtRule) {
rules.push({ at_rule: tokenAtRule })
} else if (tokenSelector) {
const selector = new CssSelector(tokenSelector)
let declarations = null
if (tokenDeclBlock) {
declarations = new CssDeclarations(tokenDeclBlock)
}
rules.push({
selector,
declarations,
})
}
} catch (e) {
if (errorThrow) {
// エラー行の算出
const parsedText = text.substr(0, token.index) // エラーの起きた文字列までを抜き出す
const lines = parsedText.split(/\n/)
//const errorIndex = text.indexOf()
//const errorLastIndex = text.lastIndexOf("\n",token.index)
const errorLine = text.substring(token.index - 30, token.index + 30)
const errorText =
`CSSのパースに失敗した: ${lines.length}行目:${errorLine}\n` +
e.message
console.log(errorText)
// console.log(e.stack)
// console.log(text)
throw errorText
}
}
}
return rules
}
export function cssParseNodeName(nodeName) {
nodeName = nodeName.trim()
const cache = GlobalVars.cacheParseNodeName[nodeName]
if (cache) {
return cache
}
// コメントアウトチェック
let result = null
if (nodeName.startsWith('//')) {
// コメントアウトのスタイルを追加する
const declarations = new CssDeclarations()
declarations.setFirst(consts.STYLE_COMMENT_OUT, true)
result = { declarations }
} else {
// nameの作成 {} を除いた部分
let name = nodeName
const pattern = /(.*)({.*})/g
const r = pattern.exec(nodeName)
if (r && r.length > 1) {
name = r[1].trim()
}
try {
// ascii文字以外 _ に変換する
const asciiNodeName = nodeName.replace(/[^\x01-\x7E]/g, function(s) {
return '_'
})
let rules = parseCss(asciiNodeName, false) // 名前はエラーチェックしない
if (!rules || rules.length === 0 || !rules[0].selector) {
// パースできなかった場合はそのまま返す
result = { name, tagName: nodeName }
} else {
result = rules[0].selector.json['rule'] // 一番外側の{}をはずす
Object.assign(result, {
name,
declarations: rules[0].declarations,
})
}
} catch (e) {
console.log('parseNodeName: exception')
result = { name, tagName: nodeName }
}
}
GlobalVars.cacheParseNodeName[nodeName] = result
return result
}
function parseCssDeclarationBlock(declarationBlock: string): {} {
declarationBlock = declarationBlock.trim()
// const tokenizer = /(?<property>[^:";\s]+)\s*:\s*|(?<value>"(?<string>([^"\\]|\\.)*)"|var\([^\)]+\)|[^";:\s]+)/gi
const tokenizer = /(?<property>[^:';\s]+)\s*:\s*|(?<value>'(?<string>([^'\\]|\\.)*)'|var\([^\)]+\)|[^';:\s]+)/gi
/** @type {string[][]} */
let values = {}
/** @type {string[]} */
let currentValues = null
let token
while ((token = tokenizer.exec(declarationBlock))) {
const property = token.groups.property
if (property) {
currentValues = []
values[property] = currentValues
}
let value = token.groups.value
if (value) {
if (token.groups.string) {
value = token.groups.string
}
if (!currentValues) {
// Propertyが無いのに値がある場合
throw 'DeclarationBlockのパースに失敗した'
}
currentValues.push(value)
}
}
return values
}
/**
* @param currentFolder
* @param filename
*/
export async function loadCssRules(currentFolder: storage.Folder, filename):Promise<any> {
if (!currentFolder) return null
// console.log(`${filename}の読み込みを開始します`)
let file
try {
file = await currentFolder.getEntry(filename)
} catch (e) {
// console.log("cssフォルダ以下にもあるかチェック")
file = await currentFolder.getEntry('css/' + filename)
if (!file) return null
}
const contents = await file.read()
let parsed = parseCss(contents)
for (let parsedElement of parsed) {
const atRule = parsedElement.at_rule
if (atRule) {
const importTokenizer = /\s*@import\s*url\("(?<file_name>.*)"\);/
let token = importTokenizer.exec(atRule)
const importFileName = token.groups.file_name
if (importFileName) {
const p = await loadCssRules(currentFolder, importFileName)
//TODO: 接続する位置とループ対策
parsed = parsed.concat(p)
}
}
}
console.log(`- ${file.name} loaded.`)
return parsed
} | the_stack |
import * as html from '../src/ast'
import { HtmlParser, TreeError } from '../src/html_parser'
import { TokenType } from '../src/lexer'
import { ParseError } from '../src/parse_util'
import { humanizeDom, humanizeDomSourceSpans, humanizeLineColumn } from '../src/ast_spec_utils'
// AST output is humanized to an array
// [type, tagName | attrName | text, index, implicitNs]
// for mor informations look in ast_spec_util.ts
{
describe('HtmlParser', () => {
let parser: HtmlParser
beforeEach(() => {
parser = new HtmlParser()
})
describe('parse', () => {
describe('HTML5 doctype', () => {
it('should parse doctype', () => {
expect(humanizeDom(parser.parse('<!doctype html>', 'TestComp'))).toEqual([
[html.Doctype, 'doctype html', 0]
])
})
})
describe('vue', () => {
it('should support colon and @ prefixed attributes', () => {
expect(
humanizeDom(parser.parse('<div :md-date.sync="" @md-closed="toggleDialog">', 'TestComp'))
).toEqual([
[html.Element, 'div', 0],
[html.Attribute, ':md-date.sync', ''],
[html.Attribute, '@md-closed', 'toggleDialog']
])
})
})
describe('interpolation', () => {
it('should parse as text', () => {
expect(humanizeDom(parser.parse('{{ foo }}', 'TestComp'))).toEqual([[html.Text, '{{ foo }}', 0]])
})
})
describe('LF no skip', () => {
it('should not ignore LF immediately after textarea, pre and listing', () => {
parser = new HtmlParser({ ignoreFirstLf: false })
expect(
humanizeDom(
parser.parse(
'<p>\n</p><textarea>\n</textarea><pre>\n\n</pre><listing>\n\n</listing>',
'TestComp'
)
)
).toEqual([
[html.Element, 'p', 0],
[html.Text, '\n', 1],
[html.Element, 'textarea', 0],
[html.Text, '\n', 1],
[html.Element, 'pre', 0],
[html.Text, '\n\n', 1],
[html.Element, 'listing', 0],
[html.Text, '\n\n', 1]
])
})
})
describe('Case sensitivity', () => {
it('should parse attributes case sensitive', () => {
parser = new HtmlParser({ ignoreFirstLf: false })
expect(
humanizeDom(
parser.parse(
'<SCRIPT src="https://www.google-analytics.com/analytics.js" ASYNC DEFER></SCRIPT>',
'TestComp'
)
)
).toEqual([
[html.Element, 'SCRIPT', 0],
[html.Attribute, 'src', 'https://www.google-analytics.com/analytics.js'],
[html.Attribute, 'ASYNC', ''],
[html.Attribute, 'DEFER', '']
])
})
it('should parse tag case sensitive', () => {
parser = new HtmlParser({ ignoreFirstLf: false })
expect(humanizeDom(parser.parse('<SCRIPT></SCRIPT>', 'TestComp'))).toEqual([
[html.Element, 'SCRIPT', 0]
])
})
it('should parse void elements case sensitive', () => {
parser = new HtmlParser({
ignoreFirstLf: false,
selfClosingElements: true
})
expect(humanizeDom(parser.parse('<Input/>', 'TestComp'))).toEqual([[html.Element, 'Input', 0]])
})
})
describe('Custom self-closing elements', () => {
it('should be able to parse any custom element as self-closing tag', () => {
const parser = new HtmlParser({ selfClosingCustomElements: true })
expect(humanizeDom(parser.parse('<custom/>', 'TestComp'))).toEqual([[html.Element, 'custom', 0]])
})
})
describe('text nodes', () => {
it('should parse root level text nodes', () => {
expect(humanizeDom(parser.parse('a', 'TestComp'))).toEqual([[html.Text, 'a', 0]])
})
it('should parse text nodes inside regular elements', () => {
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Text, 'a', 1]
])
})
it('should parse text nodes inside <ng-template> elements', () => {
expect(humanizeDom(parser.parse('<ng-template>a</ng-template>', 'TestComp'))).toEqual([
[html.Element, 'ng-template', 0],
[html.Text, 'a', 1]
])
})
it('should parse CDATA', () => {
expect(humanizeDom(parser.parse('<![CDATA[text]]>', 'TestComp'))).toEqual([[html.Text, 'text', 0]])
})
})
describe('elements', () => {
it('should parse root level elements', () => {
expect(humanizeDom(parser.parse('<div></div>', 'TestComp'))).toEqual([[html.Element, 'div', 0]])
})
it('should parse elements inside of regular elements', () => {
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Element, 'span', 1]
])
})
it('should parse elements inside <ng-template> elements', () => {
expect(humanizeDom(parser.parse('<ng-template><span></span></ng-template>', 'TestComp'))).toEqual([
[html.Element, 'ng-template', 0],
[html.Element, 'span', 1]
])
})
it('should support void elements', () => {
expect(humanizeDom(parser.parse('<link rel="author license" href="/about">', 'TestComp'))).toEqual([
[html.Element, 'link', 0],
[html.Attribute, 'rel', 'author license'],
[html.Attribute, 'href', '/about']
])
})
it('should parse image with closed tag in svg space', () => {
expect(
humanizeDom(parser.parse('<svg><image src="http://image.de"></image></svg>', 'TestComp'))
).toEqual([
[html.Element, ':svg:svg', 0, true],
[html.Element, ':svg:image', 1, true],
[html.Attribute, 'src', 'http://image.de']
])
})
it('should parse image as void element in html space', () => {
expect(humanizeDom(parser.parse('<image src="http://image.de">', 'TestComp'))).toEqual([
[html.Element, 'image', 0],
[html.Attribute, 'src', 'http://image.de']
])
})
it('should error when image is used with closed tag in html space', () => {
const errors = parser.parse('<image src="http://image.de"></image>', 'TestComp').errors
expect(errors.length).toEqual(1)
expect(humanizeErrors(errors)).toEqual([
['image', 'Void elements do not have end tags "image"', '0:29']
])
})
it('should not error on void elements from HTML5 spec', () => {
// http://www.w3.org/TR/html-markup/syntax.html#syntax-elements without:
// <base> - it can be present in head only
// <meta> - it can be present in head only
// <command> - obsolete
// <keygen> - obsolete
;[
'<map><area></map>',
'<div><br></div>',
'<colgroup><col></colgroup>',
'<div><embed></div>',
'<div><hr></div>',
'<div><img></div>',
'<div><image></div>',
'<div><input></div>',
'<object><param>/<object>',
'<audio><source></audio>',
'<audio><track></audio>',
'<p><wbr></p>'
].forEach(html => {
expect(parser.parse(html, 'TestComp').errors).toEqual([])
})
})
it('should close void elements on text nodes', () => {
expect(humanizeDom(parser.parse('<p>before<br>after</p>', 'TestComp'))).toEqual([
[html.Element, 'p', 0],
[html.Text, 'before', 1],
[html.Element, 'br', 1],
[html.Text, 'after', 1]
])
})
it('should support optional end tags', () => {
expect(humanizeDom(parser.parse('<div><p>1<p>2</div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Element, 'p', 1],
[html.Text, '1', 2],
[html.Element, 'p', 1],
[html.Text, '2', 2]
])
})
it('should support nested elements', () => {
expect(humanizeDom(parser.parse('<ul><li><ul><li></li></ul></li></ul>', 'TestComp'))).toEqual([
[html.Element, 'ul', 0],
[html.Element, 'li', 1],
[html.Element, 'ul', 2],
[html.Element, 'li', 3]
])
})
// https://github.com/Prettyhtml/prettyhtml/issues/46
it('should not add the requiredParent by default', () => {
parser = new HtmlParser()
expect(humanizeDom(parser.parse(`<draggable><tr><td></td></tr></draggable>`, 'TestComp'))).toEqual([
[html.Element, 'draggable', 0],
[html.Element, 'tr', 1],
[html.Element, 'td', 2]
])
})
it('should add the requiredParent', () => {
parser = new HtmlParser({ insertRequiredParents: true })
expect(
humanizeDom(
parser.parse(
'<table><thead><tr head></tr></thead><tr noparent></tr><tbody><tr body></tr></tbody><tfoot><tr foot></tr></tfoot></table>',
'TestComp'
)
)
).toEqual([
[html.Element, 'table', 0],
[html.Element, 'thead', 1],
[html.Element, 'tr', 2],
[html.Attribute, 'head', ''],
[html.Element, 'tbody', 1],
[html.Element, 'tr', 2],
[html.Attribute, 'noparent', ''],
[html.Element, 'tbody', 1],
[html.Element, 'tr', 2],
[html.Attribute, 'body', ''],
[html.Element, 'tfoot', 1],
[html.Element, 'tr', 2],
[html.Attribute, 'foot', '']
])
})
it('should append the required parent considering ng-container', () => {
parser = new HtmlParser({ insertRequiredParents: true })
expect(
humanizeDom(parser.parse('<table><ng-container><tr></tr></ng-container></table>', 'TestComp'))
).toEqual([
[html.Element, 'table', 0],
[html.Element, 'tbody', 1],
[html.Element, 'ng-container', 2],
[html.Element, 'tr', 3]
])
})
it('should append the required parent considering top level ng-container', () => {
parser = new HtmlParser({ insertRequiredParents: true })
expect(
humanizeDom(parser.parse('<ng-container><tr></tr></ng-container><p></p>', 'TestComp'))
).toEqual([[html.Element, 'ng-container', 0], [html.Element, 'tr', 1], [html.Element, 'p', 0]])
})
it('should special case ng-container when adding a required parent', () => {
parser = new HtmlParser({ insertRequiredParents: true })
expect(
humanizeDom(
parser.parse('<table><thead><ng-container><tr></tr></ng-container></thead></table>', 'TestComp')
)
).toEqual([
[html.Element, 'table', 0],
[html.Element, 'thead', 1],
[html.Element, 'ng-container', 2],
[html.Element, 'tr', 3]
])
})
it('should not add the requiredParent when the parent is a <ng-template>', () => {
parser = new HtmlParser({ insertRequiredParents: true })
expect(humanizeDom(parser.parse('<ng-template><tr></tr></ng-template>', 'TestComp'))).toEqual([
[html.Element, 'ng-template', 0],
[html.Element, 'tr', 1]
])
})
// https://github.com/angular/angular/issues/5967
it('should not add the requiredParent to a template root element', () => {
parser = new HtmlParser({ insertRequiredParents: true })
expect(humanizeDom(parser.parse('<tr></tr>', 'TestComp'))).toEqual([[html.Element, 'tr', 0]])
})
it('should support explicit namespace', () => {
expect(humanizeDom(parser.parse('<myns:div></myns:div>', 'TestComp'))).toEqual([
[html.Element, ':myns:div', 0]
])
})
it('should support implicit namespace', () => {
expect(humanizeDom(parser.parse('<svg></svg>', 'TestComp'))).toEqual([
[html.Element, ':svg:svg', 0, true]
])
})
it('should support implicit namespace on nested elements', () => {
expect(humanizeDom(parser.parse('<svg><g></g></svg>', 'TestComp'))).toEqual([
[html.Element, ':svg:svg', 0, true],
[html.Element, ':svg:g', 1, true]
])
})
it('should set flag that namespace was set implicitly', () => {
expect(humanizeDom(parser.parse('<svg><g></g></svg>', 'TestComp'))).toEqual([
[html.Element, ':svg:svg', 0, true],
[html.Element, ':svg:g', 1, true]
])
})
it('should propagate the namespace', () => {
expect(humanizeDom(parser.parse('<myns:div><p></p></myns:div>', 'TestComp'))).toEqual([
[html.Element, ':myns:div', 0],
[html.Element, ':myns:p', 1, true]
])
})
it('should match closing tags case sensitive', () => {
const errors = parser.parse('<DiV><P></p></dIv>', 'TestComp').errors
expect(errors.length).toEqual(2)
expect(humanizeErrors(errors)).toEqual([
[
'p',
'Unexpected closing tag "p". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:8'
],
[
'dIv',
'Unexpected closing tag "dIv". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:12'
]
])
})
it('should support self closing void elements', () => {
expect(humanizeDom(parser.parse('<input />', 'TestComp'))).toEqual([[html.Element, 'input', 0]])
})
it('should support self closing foreign elements', () => {
expect(humanizeDom(parser.parse('<math />', 'TestComp'))).toEqual([
[html.Element, ':math:math', 0, true]
])
})
it('should ignore LF immediately after textarea, pre and listing', () => {
expect(
humanizeDom(
parser.parse(
'<p>\n</p><textarea>\n</textarea><pre>\n\n</pre><listing>\n\n</listing>',
'TestComp'
)
)
).toEqual([
[html.Element, 'p', 0],
[html.Text, '\n', 1],
[html.Element, 'textarea', 0],
[html.Element, 'pre', 0],
[html.Text, '\n', 1],
[html.Element, 'listing', 0],
[html.Text, '\n', 1]
])
})
})
describe('attributes', () => {
it('should parse attributes on regular elements case sensitive', () => {
expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'kEy', 'v'],
[html.Attribute, 'key2', 'v2']
])
})
it('should parse attributes without values', () => {
expect(humanizeDom(parser.parse('<div k></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, 'k', '']
])
})
it('should parse attributes on svg elements case sensitive', () => {
expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp'))).toEqual([
[html.Element, ':svg:svg', 0, true],
[html.Attribute, 'viewBox', '0']
])
})
it('should parse attributes on <ng-template> elements', () => {
expect(humanizeDom(parser.parse('<ng-template k="v"></ng-template>', 'TestComp'))).toEqual([
[html.Element, 'ng-template', 0],
[html.Attribute, 'k', 'v']
])
})
it('should support namespace', () => {
expect(humanizeDom(parser.parse('<svg:use xlink:href="Port" />', 'TestComp'))).toEqual([
[html.Element, ':svg:use', 0],
[html.Attribute, ':xlink:href', 'Port']
])
})
})
describe('entities', () => {
it('should not decode entities with only ampersand and #', () => {
parser = new HtmlParser({ decodeEntities: false })
expect(humanizeDom(parser.parse('<div [icon]="&#"></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, '[icon]', '&#']
])
})
it('should not decode entities', () => {
parser = new HtmlParser({ decodeEntities: false })
expect(humanizeDom(parser.parse('<div [icon]="ō"></div>', 'TestComp'))).toEqual([
[html.Element, 'div', 0],
[html.Attribute, '[icon]', 'ō']
])
})
})
describe('comments', () => {
it('should preserve comments', () => {
expect(humanizeDom(parser.parse('<!-- comment --><div></div>', 'TestComp'))).toEqual([
[html.Comment, ' comment ', 0],
[html.Element, 'div', 0]
])
})
it('should preserve whitespaces and newlines in comments', () => {
expect(humanizeDom(parser.parse('<!-- \ncomment\n --><div></div>', 'TestComp'))).toEqual([
[html.Comment, ' \ncomment\n ', 0],
[html.Element, 'div', 0]
])
})
})
describe('source spans', () => {
it('should store the location', () => {
expect(
humanizeDomSourceSpans(
parser.parse('<div [prop]="v1" (e)="do()" attr="v2" noValue>\na\n</div>', 'TestComp')
)
).toEqual([
[html.Element, 'div', 0, '<div [prop]="v1" (e)="do()" attr="v2" noValue>'],
[html.Attribute, '[prop]', 'v1', '[prop]="v1"'],
[html.Attribute, '(e)', 'do()', '(e)="do()"'],
[html.Attribute, 'attr', 'v2', 'attr="v2"'],
[html.Attribute, 'noValue', '', 'noValue'],
[html.Text, '\na\n', 1, '\na\n']
])
})
it('should set the start and end source spans', () => {
const node = <html.Element>parser.parse('<div>a</div>', 'TestComp').rootNodes[0]
expect(node.startSourceSpan!.start.offset).toEqual(0)
expect(node.startSourceSpan!.end.offset).toEqual(5)
expect(node.endSourceSpan!.start.offset).toEqual(6)
expect(node.endSourceSpan!.end.offset).toEqual(12)
})
it('should not report a value span for an attribute without a value', () => {
const ast = parser.parse('<div bar></div>', 'TestComp')
expect((ast.rootNodes[0] as html.Element).attrs[0].valueSpan).toBeUndefined()
})
it('should report a value span for an attribute with a value', () => {
const ast = parser.parse('<div bar="12"></div>', 'TestComp')
const attr = (ast.rootNodes[0] as html.Element).attrs[0]
expect(attr.valueSpan!.start.offset).toEqual(9)
expect(attr.valueSpan!.end.offset).toEqual(13)
})
})
describe('self close mode', () => {
it('should allow self closing html element', () => {
parser = new HtmlParser({ selfClosingElements: true })
const errors = parser.parse('<p />', 'TestComp').errors
expect(errors.length).toEqual(0)
})
it('should allow self closing custom element', () => {
parser = new HtmlParser({ selfClosingElements: true })
const errors = parser.parse('<my-cmp />', 'TestComp').errors
expect(errors.length).toEqual(0)
})
})
describe('visitor', () => {
it('should visit text nodes', () => {
const result = humanizeDom(parser.parse('text', 'TestComp'))
expect(result).toEqual([[html.Text, 'text', 0]])
})
it('should visit element nodes', () => {
const result = humanizeDom(parser.parse('<div></div>', 'TestComp'))
expect(result).toEqual([[html.Element, 'div', 0]])
})
it('should visit attribute nodes', () => {
const result = humanizeDom(parser.parse('<div id="foo"></div>', 'TestComp'))
expect(result).toContainEqual([html.Attribute, 'id', 'foo'])
})
it('should visit all nodes', () => {
const result = parser.parse('<div id="foo"><span id="bar">a</span><span>b</span></div>', 'TestComp')
const accumulator: html.Node[] = []
const visitor = new class {
visit(node: html.Node, context: any) {
accumulator.push(node)
}
visitElement(element: html.Element, context: any): any {
html.visitAll(this, element.attrs)
html.visitAll(this, element.children)
}
visitAttribute(attribute: html.Attribute, context: any): any {}
visitText(text: html.Text, context: any): any {}
visitDoctype(doctype: html.Doctype, context: any): any {}
visitComment(comment: html.Comment, context: any): any {}
}()
html.visitAll(visitor, result.rootNodes)
expect(accumulator.map(n => n.constructor)).toEqual([
html.Element,
html.Attribute,
html.Element,
html.Attribute,
html.Text,
html.Element,
html.Text
])
})
it('should skip typed visit if visit() returns a truthy value', () => {
const visitor = new class {
visit(node: html.Node, context: any) {
return true
}
visitElement(element: html.Element, context: any): any {
throw Error('Unexpected')
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw Error('Unexpected')
}
visitText(text: html.Text, context: any): any {
throw Error('Unexpected')
}
visitComment(comment: html.Comment, context: any): any {
throw Error('Unexpected')
}
visitDoctype(doctype: html.Doctype, context: any): any {
throw Error('Unexpected')
}
}()
const result = parser.parse('<div id="foo"></div><div id="bar"></div>', 'TestComp')
const traversal = html.visitAll(visitor, result.rootNodes)
expect(traversal).toEqual([true, true])
})
})
describe('errors', () => {
it('should report unexpected closing tags', () => {
const errors = parser.parse('<div></p></div>', 'TestComp').errors
expect(errors.length).toEqual(1)
expect(humanizeErrors(errors)).toEqual([
[
'p',
'Unexpected closing tag "p". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:5'
]
])
})
it('should report subsequent open tags without proper close tag', () => {
const errors = parser.parse('<div</div>', 'TestComp').errors
expect(errors.length).toEqual(1)
expect(humanizeErrors(errors)).toEqual([
[
'div',
'Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:4'
]
])
})
it('should report closing tag for void elements', () => {
const errors = parser.parse('<input></input>', 'TestComp').errors
expect(errors.length).toEqual(1)
expect(humanizeErrors(errors)).toEqual([
['input', 'Void elements do not have end tags "input"', '0:7']
])
})
it('should report self closing html element', () => {
const errors = parser.parse('<p />', 'TestComp').errors
expect(errors.length).toEqual(1)
expect(humanizeErrors(errors)).toEqual([
['p', 'Only void, foreign or custom elements can be self closed "p"', '0:0']
])
})
it('should report self closing custom element', () => {
const errors = parser.parse('<my-cmp />', 'TestComp').errors
expect(errors.length).toEqual(1)
expect(humanizeErrors(errors)).toEqual([
['my-cmp', 'Only void, foreign or custom elements can be self closed "my-cmp"', '0:0']
])
})
it('should also report lexer errors', () => {
const errors = parser.parse('<!-err--><div></p></div>', 'TestComp').errors
expect(errors.length).toEqual(2)
expect(humanizeErrors(errors)).toEqual([
[TokenType.COMMENT_START, 'Unexpected character "e"', '0:3'],
[
'p',
'Unexpected closing tag "p". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags',
'0:14'
]
])
})
})
})
})
}
export function humanizeErrors(errors: ParseError[]): any[] {
return errors.map(e => {
if (e instanceof TreeError) {
// Parser errors
return [<any>e.elementName, e.msg, humanizeLineColumn(e.span.start)]
}
// Tokenizer errors
return [(<any>e).tokenType, e.msg, humanizeLineColumn(e.span.start)]
})
} | the_stack |
import * as coreClient from "@azure/core-client";
export const BasicDef: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "BasicDef",
modelProperties: {
id: {
serializedName: "id",
nullable: true,
type: {
name: "Number"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
},
color: {
serializedName: "color",
type: {
name: "String"
}
}
}
}
};
export const ErrorModel: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorModel",
modelProperties: {
status: {
serializedName: "status",
type: {
name: "Number"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
}
}
}
};
export const IntWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "IntWrapper",
modelProperties: {
field1: {
serializedName: "field1",
type: {
name: "Number"
}
},
field2: {
serializedName: "field2",
type: {
name: "Number"
}
}
}
}
};
export const LongWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "LongWrapper",
modelProperties: {
field1: {
serializedName: "field1",
type: {
name: "Number"
}
},
field2: {
serializedName: "field2",
type: {
name: "Number"
}
}
}
}
};
export const FloatWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "FloatWrapper",
modelProperties: {
field1: {
serializedName: "field1",
type: {
name: "Number"
}
},
field2: {
serializedName: "field2",
type: {
name: "Number"
}
}
}
}
};
export const DoubleWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DoubleWrapper",
modelProperties: {
field1: {
serializedName: "field1",
type: {
name: "Number"
}
},
field56ZerosAfterTheDotAndNegativeZeroBeforeDotAndThisIsALongFieldNameOnPurpose: {
serializedName:
"field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose",
type: {
name: "Number"
}
}
}
}
};
export const BooleanWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "BooleanWrapper",
modelProperties: {
fieldTrue: {
serializedName: "field_true",
type: {
name: "Boolean"
}
},
fieldFalse: {
serializedName: "field_false",
type: {
name: "Boolean"
}
}
}
}
};
export const StringWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "StringWrapper",
modelProperties: {
field: {
serializedName: "field",
type: {
name: "String"
}
},
empty: {
serializedName: "empty",
type: {
name: "String"
}
},
null: {
serializedName: "null",
type: {
name: "String"
}
}
}
}
};
export const DateWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DateWrapper",
modelProperties: {
field: {
serializedName: "field",
type: {
name: "Date"
}
},
leap: {
serializedName: "leap",
type: {
name: "Date"
}
}
}
}
};
export const DatetimeWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DatetimeWrapper",
modelProperties: {
field: {
serializedName: "field",
type: {
name: "DateTime"
}
},
now: {
serializedName: "now",
type: {
name: "DateTime"
}
}
}
}
};
export const Datetimerfc1123Wrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Datetimerfc1123Wrapper",
modelProperties: {
field: {
serializedName: "field",
type: {
name: "DateTimeRfc1123"
}
},
now: {
serializedName: "now",
type: {
name: "DateTimeRfc1123"
}
}
}
}
};
export const DurationWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DurationWrapper",
modelProperties: {
field: {
serializedName: "field",
type: {
name: "TimeSpan"
}
}
}
}
};
export const ByteWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ByteWrapper",
modelProperties: {
field: {
serializedName: "field",
type: {
name: "ByteArray"
}
}
}
}
};
export const ArrayWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ArrayWrapper",
modelProperties: {
array: {
serializedName: "array",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const DictionaryWrapper: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DictionaryWrapper",
modelProperties: {
defaultProgram: {
serializedName: "defaultProgram",
nullable: true,
type: {
name: "Dictionary",
value: { type: { name: "String" } }
}
}
}
}
};
export const Pet: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Pet",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "Number"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
}
}
}
};
export const Fish: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Fish",
uberParent: "Fish",
polymorphicDiscriminator: {
serializedName: "fishtype",
clientName: "fishtype"
},
modelProperties: {
fishtype: {
serializedName: "fishtype",
required: true,
type: {
name: "String"
}
},
species: {
serializedName: "species",
type: {
name: "String"
}
},
length: {
serializedName: "length",
required: true,
type: {
name: "Number"
}
},
siblings: {
serializedName: "siblings",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Fish"
}
}
}
}
}
}
};
export const DotFish: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DotFish",
uberParent: "DotFish",
polymorphicDiscriminator: {
serializedName: "fish\\.type",
clientName: "fishType"
},
modelProperties: {
fishType: {
serializedName: "fish\\.type",
required: true,
type: {
name: "String"
}
},
species: {
serializedName: "species",
type: {
name: "String"
}
}
}
}
};
export const DotFishMarket: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DotFishMarket",
modelProperties: {
sampleSalmon: {
serializedName: "sampleSalmon",
type: {
name: "Composite",
className: "DotSalmon"
}
},
salmons: {
serializedName: "salmons",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DotSalmon"
}
}
}
},
sampleFish: {
serializedName: "sampleFish",
type: {
name: "Composite",
className: "DotFish"
}
},
fishes: {
serializedName: "fishes",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DotFish"
}
}
}
}
}
}
};
export const ReadonlyObj: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ReadonlyObj",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
size: {
serializedName: "size",
type: {
name: "Number"
}
}
}
}
};
export const MyBaseType: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "MyBaseType",
uberParent: "MyBaseType",
polymorphicDiscriminator: {
serializedName: "kind",
clientName: "kind"
},
modelProperties: {
kind: {
serializedName: "kind",
required: true,
type: {
name: "String"
}
},
propB1: {
serializedName: "propB1",
type: {
name: "String"
}
},
propBH1: {
serializedName: "helper.propBH1",
type: {
name: "String"
}
}
}
}
};
export const Dog: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Dog",
modelProperties: {
...Pet.type.modelProperties,
food: {
serializedName: "food",
type: {
name: "String"
}
}
}
}
};
export const Cat: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Cat",
modelProperties: {
...Pet.type.modelProperties,
color: {
serializedName: "color",
type: {
name: "String"
}
},
hates: {
serializedName: "hates",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Dog"
}
}
}
}
}
}
};
export const Salmon: coreClient.CompositeMapper = {
serializedName: "salmon",
type: {
name: "Composite",
className: "Salmon",
uberParent: "Fish",
polymorphicDiscriminator: {
serializedName: "fishtype",
clientName: "fishtype"
},
modelProperties: {
...Fish.type.modelProperties,
location: {
serializedName: "location",
type: {
name: "String"
}
},
iswild: {
serializedName: "iswild",
type: {
name: "Boolean"
}
}
}
}
};
export const Shark: coreClient.CompositeMapper = {
serializedName: "shark",
type: {
name: "Composite",
className: "Shark",
uberParent: "Fish",
polymorphicDiscriminator: {
serializedName: "fishtype",
clientName: "fishtype"
},
modelProperties: {
...Fish.type.modelProperties,
age: {
serializedName: "age",
type: {
name: "Number"
}
},
birthday: {
serializedName: "birthday",
required: true,
type: {
name: "DateTime"
}
}
}
}
};
export const DotSalmon: coreClient.CompositeMapper = {
serializedName: "DotSalmon",
type: {
name: "Composite",
className: "DotSalmon",
uberParent: "DotFish",
polymorphicDiscriminator: DotFish.type.polymorphicDiscriminator,
modelProperties: {
...DotFish.type.modelProperties,
location: {
serializedName: "location",
type: {
name: "String"
}
},
iswild: {
serializedName: "iswild",
type: {
name: "Boolean"
}
}
}
}
};
export const MyDerivedType: coreClient.CompositeMapper = {
serializedName: "Kind1",
type: {
name: "Composite",
className: "MyDerivedType",
uberParent: "MyBaseType",
polymorphicDiscriminator: MyBaseType.type.polymorphicDiscriminator,
modelProperties: {
...MyBaseType.type.modelProperties,
propD1: {
serializedName: "propD1",
type: {
name: "String"
}
}
}
}
};
export const Siamese: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Siamese",
modelProperties: {
...Cat.type.modelProperties,
breed: {
serializedName: "breed",
type: {
name: "String"
}
}
}
}
};
export const SmartSalmon: coreClient.CompositeMapper = {
serializedName: "smart_salmon",
type: {
name: "Composite",
className: "SmartSalmon",
uberParent: "Fish",
additionalProperties: { type: { name: "Object" } },
polymorphicDiscriminator: Fish.type.polymorphicDiscriminator,
modelProperties: {
...Salmon.type.modelProperties,
collegeDegree: {
serializedName: "college_degree",
type: {
name: "String"
}
}
}
}
};
export const Sawshark: coreClient.CompositeMapper = {
serializedName: "sawshark",
type: {
name: "Composite",
className: "Sawshark",
uberParent: "Fish",
polymorphicDiscriminator: Fish.type.polymorphicDiscriminator,
modelProperties: {
...Shark.type.modelProperties,
picture: {
serializedName: "picture",
type: {
name: "ByteArray"
}
}
}
}
};
export const Goblinshark: coreClient.CompositeMapper = {
serializedName: "goblin",
type: {
name: "Composite",
className: "Goblinshark",
uberParent: "Fish",
polymorphicDiscriminator: Fish.type.polymorphicDiscriminator,
modelProperties: {
...Shark.type.modelProperties,
jawsize: {
serializedName: "jawsize",
type: {
name: "Number"
}
},
color: {
defaultValue: "gray",
serializedName: "color",
type: {
name: "String"
}
}
}
}
};
export const Cookiecuttershark: coreClient.CompositeMapper = {
serializedName: "cookiecuttershark",
type: {
name: "Composite",
className: "Cookiecuttershark",
uberParent: "Fish",
polymorphicDiscriminator: Fish.type.polymorphicDiscriminator,
modelProperties: {
...Shark.type.modelProperties
}
}
};
export let discriminators = {
Fish: Fish,
DotFish: DotFish,
MyBaseType: MyBaseType,
"Fish.salmon": Salmon,
"Fish.shark": Shark,
"DotFish.DotSalmon": DotSalmon,
"MyBaseType.Kind1": MyDerivedType,
"Fish.smart_salmon": SmartSalmon,
"Fish.sawshark": Sawshark,
"Fish.goblin": Goblinshark,
"Fish.cookiecuttershark": Cookiecuttershark
}; | the_stack |
import {Watcher, RawMap, RawValue, RawEAV, RawEAVC, maybeIntern} from "./watcher";
import {HTMLWatcher} from "./html";
import {v4 as uuid} from "uuid";
function asValue(value:RawValue|undefined) {
if(typeof value == "string") {
if(value == "true") return true;
if(value == "false") return false;
}
return value;
}
function ixComparator(idMap:{[key:string]:{ix:number}}) {
return (a:string, b:string) => {
return idMap[a].ix - idMap[b].ix;
}
}
let operationFields:{[type:string]: string[]} = {
moveTo: ["x", "y"],
lineTo: ["x", "y"],
bezierQuadraticCurveTo: ["cp1x", "cp1y", "cp2x", "cp2y", "x", "y"],
quadraticCurveTo: ["cpx", "cpy", "x", "y"],
arc: ["x", "y", "radius", "startAngle", "endAngle", "anticlockwise"],
arcTo: ["x1", "y1", "x2", "y2", "radius"],
ellipse: ["x", "y", "radiusX", "radiusY", "rotation", "startAngle", "endAngle", "anticlockwise"],
rect: ["x", "y", "width", "height"],
closePath: []
};
let defaultOperationFieldValue:{[field:string]: any} = {
rotation: 0,
startAngle: 0,
endAngle: 2 * Math.PI,
anticlockwise: false
};
function isOperationType(val:RawValue): val is OperationType {
return !!operationFields[val];
}
const EMPTY = {};
export interface Canvas extends HTMLCanvasElement { __element?: RawValue }
export type OperationType = keyof Path2D;
export interface Operation {type: OperationType, args:any, paths:RawValue[]};
// {fillStyle: "#000000", strokeStyle: "#000000", lineWidth: 1, lineCap: "butt", lineJoin: "miter"}
export interface PathStyle {[key:string]: RawValue|undefined, fillStyle?:string, strokeStyle?:string, lineWidth?:number, lineCap?:string, lineJoin?: string };
export class CanvasWatcher extends Watcher {
html:HTMLWatcher;
canvases:RawMap<RawValue[]|undefined> = {};
paths:RawMap<RawValue[]|undefined> = {};
operations:RawMap<Operation|undefined> = {};
canvasPaths:RawMap<RawValue[]|undefined> = {};
pathToCanvases:RawMap<RawValue[]|undefined> = {};
pathStyles:RawMap<PathStyle|undefined> = {};
pathCache:RawMap<Path2D|undefined> = {};
dirty:RawMap<boolean|undefined> = {};
// addCanvas(canvasId:RawValue, instanceId:RawValue) {
// if(this.canvases[id]) throw new Error(`Recreating canvas instance ${maybeIntern(id)}`);
// let elements = this.html.elementToInstances[id];
// // if(!elements || !elements.length) throw new Error(`No matching canvas instance found for ${id}.`);
// if(!elements || !elements.length) return; // @FIXME: Really seems like this is an error case...
// if(elements.length > 1) throw new Error(`Multiple canvas instances found for ${id}.`);
// return this.canvases[id] = this.html.getInstance(elements[0]) as HTMLCanvasElement;
// }
// clearCanvas(id:RawValue) {
// if(!this.canvases[id]) throw new Error(`Missing canvas instance ${maybeIntern(id)}`);
// this.canvases[id] = undefined;
// }
// getCanvas(id:RawValue) {
// let canvas = this.canvases[id];
// if(!canvas) throw new Error(`Missing canvas instance ${maybeIntern(id)}`);
// return canvas;
// }
addCanvasInstance(canvasId:RawValue, instanceId:RawValue) {
let instances = this.canvases[canvasId] = this.canvases[canvasId] || [];
instances.push(instanceId);
}
clearCanvasInstance(canvasId:RawValue, instanceId:RawValue) {
let instances = this.canvases[canvasId];
if(!instances) return; // @FIXME: Seems like an error though
let ix = instances.indexOf(instanceId);
if(ix !== -1) {
instances.splice(ix, 1);
if(!instances.length) this.canvases[canvasId] = undefined;
}
}
getCanvasInstances(canvasId:RawValue) {
let instances = this.canvases[canvasId];
if(!instances) throw new Error(`Missing canvas instance(s) for ${maybeIntern(canvasId)}`);
return instances;
}
getCanvasPaths(canvasId:RawValue) {
return this.canvasPaths[canvasId];
}
addPath(id:RawValue) {
if(this.paths[id]) throw new Error(`Recreating path instance ${maybeIntern(id)}`);
this.pathStyles[id] = {};
return this.paths[id] = [];
}
clearPath(id:RawValue) {
if(!this.paths[id]) throw new Error(`Missing path instance ${maybeIntern(id)}`);
this.pathStyles[id] = undefined;
this.paths[id] = undefined;
}
getPath(id:RawValue) {
let path = this.paths[id];
if(!path) throw new Error(`Missing path instance ${maybeIntern(id)}`);
return path;
}
addOperation(id:RawValue, type:RawValue) {
if(this.operations[id]) throw new Error(`Recreating operation instance ${maybeIntern(id)}`);
if(!isOperationType(type)) throw new Error(`Invalid operation type ${type}`);
return this.operations[id] = {type, args: {}, paths: []};
}
clearOperation(id:RawValue) {
if(!this.operations[id]) throw new Error(`Missing operation instance ${maybeIntern(id)}`);
this.operations[id] = undefined;
}
getOperation(id:RawValue) {
let operation = this.operations[id];
if(!operation) throw new Error(`Missing operation instance ${maybeIntern(id)}`);
return operation;
}
getOperationArgs(operation:Operation) {
let {type, args} = operation;
let fields:string[] = operationFields[type as string];
let input = [];
let restOptional = false;
for(let field of fields) {
let value = asValue(args[field]) || defaultOperationFieldValue[field];
if(value === undefined) return;
input.push(value);
}
return input;
}
updateCache(dirtyPaths:RawValue[]) {
for(let id of dirtyPaths) {
if(!this.dirty[id]) continue;
let path = this.paths[id];
if(!path) continue;
let path2d = this.pathCache[id] = new window.Path2D();
for(let opId of path) {
let operation = this.getOperation(opId);
let input = this.getOperationArgs(operation);
if(!input) {
console.warn(`Skipping incomplete or invalid operation ${maybeIntern(opId)}`, operation.type, operation.args);
continue;
}
if(!path2d[operation.type]) {
console.warn(`Skipping unavailable operation type ${operation.type}. Check your browser's Path2D compatibility.`);
continue;
}
(path2d[operation.type] as (...args:any[]) => void)(...input);
}
}
}
rerender(dirtyPaths:RawValue[]) {
let dirtyCanvases:RawMap<boolean|undefined> = {};
for(let id of dirtyPaths) {
let canvasIds = this.pathToCanvases[id];
if(!canvasIds) continue;
for(let canvasId of canvasIds) {
dirtyCanvases[canvasId] = true;
}
}
for(let canvasId of Object.keys(dirtyCanvases)) {
let pathIds = this.canvasPaths[canvasId];
for(let instanceId of this.getCanvasInstances(canvasId)) {
let canvas = this.html.getInstance(instanceId) as Canvas;
let ctx = canvas.getContext("2d")!;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(!pathIds) continue;
for(let id of pathIds) {
let cached = this.pathCache[id];
if(!cached) continue // This thing isn't a path (yet?)
let style = this.pathStyles[id] || EMPTY as PathStyle;
let {fillStyle = "#000000", strokeStyle = "#000000", lineWidth = 1, lineCap = "butt", lineJoin = "miter"} = style;
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
ctx.lineCap = lineCap;
ctx.lineJoin = lineJoin;
if(style.strokeStyle) ctx.stroke(cached);
if(style.fillStyle || !style.strokeStyle) ctx.fill(cached);
}
}
}
}
changed = () => {
let dirtyPaths = Object.keys(this.dirty);
this.updateCache(dirtyPaths);
this.rerender(dirtyPaths);
this.dirty = {};
}
setup() {
this.html = this.program.attach("html") as HTMLWatcher;
this.program
.bind("Canvas roots are html elements.", ({find}) => {
let canvas = find("canvas/root");
return [canvas.add({tag: "html/element", tagname: "canvas"})]
})
.bind("If an ellipse operation specifies a radius, copy it into radiusX and radiusY.", ({find}) => {
let path = find("canvas/path");
let operation = path.children;
operation.type == "ellipse";
let {radius} = operation;
return [
operation.add({radiusX: radius, radiusY: radius})
];
})
// .watch("Export canvas roots.", ({find}) => {
// let canvas = find("canvas/root");
// return [canvas.add("tag", "canvas/root")]
// })
// .asDiffs((diffs) => {
// for(let [e] of diffs.adds) this.addCanvas(e);
// for(let [e] of diffs.removes) this.clearCanvas(e);
// setImmediate(this.changed);
// })
.watch("Export canvas instances.", ({find}) => {
let canvas = find("canvas/root");
let instance = find("html/instance", {element: canvas});
return [canvas.add("instance", instance)]
})
.asDiffs((diffs) => {
for(let [canvas, _, instance] of diffs.adds) this.addCanvasInstance(canvas, instance);
for(let [canvas, _, instance] of diffs.removes) this.clearCanvasInstance(canvas, instance);
setImmediate(this.changed);
})
.watch("Export canvas paths.", ({find}) => {
let path = find("canvas/path");
return [path.add("tag", "canvas/path")]
})
.asDiffs((diffs) => {
for(let [e] of diffs.adds) {
this.addPath(e);
this.dirty[e] = true;
}
for(let [e] of diffs.removes) {
this.clearPath(e);
this.dirty[e] = true;
}
setImmediate(this.changed);
})
.watch("Export canvas operations.", ({find}) => {
let path = find("canvas/path");
let operation = path.children;
return [operation.add("type", operation.type)]
})
.asDiffs((diffs) => {
for(let [e, _, type] of diffs.adds) this.addOperation(e, type);
for(let [e] of diffs.removes) this.clearOperation(e);
setImmediate(this.changed);
})
.watch("Export paths of canvas.", ({find, choose, gather, record}) => {
let canvas = find("canvas/root");
let child = canvas.children;
// @FIXME: non-deterministic sort bug :(
//let ix = gather(child.sort).per(canvas).sort();
let ix = choose(() => child.sort, () => child["eve-auto-index"], () => 1);
return [record({canvas, child, ix})]
})
.asObjects<{canvas:RawValue, child:RawValue, ix:number}>((diffs) => {
let removeIds = Object.keys(diffs.removes);
removeIds.sort(ixComparator(diffs.removes)).reverse();
for(let removeId of removeIds) {
let {canvas:canvasId, child:childId, ix} = diffs.removes[removeId];
let instances = this.canvases[canvasId];
let paths = this.canvasPaths[canvasId];
if(paths) paths.splice(ix - 1, 1);
let canvases = this.pathToCanvases[childId] = this.pathToCanvases[childId];
if(canvases) {
let ix = canvases.indexOf(canvasId);
if(ix !== -1) canvases.splice(ix, 1);
}
// @FIXME: need a proper way to indicate dirtyness when an unchanged path is added a canvas.
// This hack just marks the path dirty, which will rerender any other canvases containing it o_o
this.dirty[childId] = true;
}
let addIds = Object.keys(diffs.adds);
addIds.sort(ixComparator(diffs.adds));
for(let addId of addIds) {
let {canvas:canvasId, child:childId, ix} = diffs.adds[addId];
let paths = this.canvasPaths[canvasId] = this.canvasPaths[canvasId] || [];
paths.splice(ix - 1, 0, childId)
let canvases = this.pathToCanvases[childId] = this.pathToCanvases[childId] || [];
canvases.push(canvasId);
// @FIXME: need a proper way to indicate dirtyness when an unchanged path is added a canvas.
// This hack just marks the path dirty, which will rerender any other canvases containing it o_o
this.dirty[childId] = true;
}
setImmediate(this.changed);
})
.watch("Export operations of paths.", ({find, choose, gather, record}) => {
let path = find("canvas/path");
let child = path.children;
// @FIXME: non-deterministic sort bug :(
//let ix = gather(child.sort).per(path).sort();
let ix = choose(() => child.sort, () => child["eve-auto-index"], () => 1);
return [record({path, child, ix})]
})
.asObjects<{path:RawValue, child:RawValue, ix:number}>((diffs) => {
let removeIds = Object.keys(diffs.removes);
removeIds.sort(ixComparator(diffs.removes)).reverse();
for(let removeId of removeIds) {
let {path:pathId, child:childId, ix} = diffs.removes[removeId];
let path = this.paths[pathId];
if(path) path.splice(ix - 1, 1);
let operation = this.operations[childId];
if(operation) {
let ix = operation.paths.indexOf(pathId);
if(ix !== -1) operation.paths.splice(ix, 1);
}
this.dirty[pathId] = true;
}
let addIds = Object.keys(diffs.adds);
addIds.sort(ixComparator(diffs.adds));
for(let addId of addIds) {
let {path:pathId, child:childId, ix} = diffs.adds[addId];
let path = this.getPath(pathId);
path.splice(ix - 1, 0, childId)
let operation = this.getOperation(childId);
operation.paths.push(pathId);
this.dirty[pathId] = true;
}
setImmediate(this.changed);
})
.watch("Export attributes of operations.", ({find, lookup, record}) => {
let path = find("canvas/path");
let child = path.children;
let {attribute, value} = lookup(child);
return [child.add(attribute, value)];
})
.asDiffs((diffs) => {
for(let [opId, attribute, value] of diffs.removes) {
let operation = this.operations[opId];
if(!operation) continue;
operation.args[attribute] = undefined;
for(let pathId of operation.paths) this.dirty[pathId] = true;
}
for(let [opId, attribute, value] of diffs.adds) {
let operation = this.operations[opId];
if(!operation) throw new Error(`Missing operation ${maybeIntern(opId)} for AV ${attribute}: $[value}`);
if(operation.args[attribute]) throw new Error(`Attempting to overwrite existing attribute ${attribute} of ${opId}: ${operation.args[attribute]} => ${value}`);
operation.args[attribute] = value;
for(let pathId of operation.paths) this.dirty[pathId] = true;
}
setImmediate(this.changed);
})
.watch("Export path styles.", ({find, lookup, record}) => {
let path = find("canvas/path");
let {attribute, value} = lookup(path);
attribute != "children";
attribute != "tag";
attribute != "sort";
attribute != "eve-auto-index";
return [path.add(attribute, value)];
})
.asDiffs((diffs) => {
for(let [pathId, attribute, value] of diffs.removes) {
let pathStyle = this.pathStyles[pathId];
if(!pathStyle) continue;
pathStyle[attribute] = undefined;
this.dirty[pathId] = true;
}
for(let [pathId, attribute, value] of diffs.adds) {
let pathStyle = this.pathStyles[pathId];
if(!pathStyle) throw new Error(`Missing path style for ${pathId}.`);
// if(pathStyle[attribute]) throw new Error(`Attempting to overwrite existing attribute ${attribute} of ${pathId}: ${pathStyle[attribute]} => ${value}`);
pathStyle[attribute] = value;
this.dirty[pathId] = true;
}
setImmediate(this.changed);
});
}
}
Watcher.register("canvas", CanvasWatcher);
/*
* [#canvas/root width height children:
* [#canvas/rect x y width height fill? stroke?]]
*/ | the_stack |
import * as express from 'express';
import { extend, intersection, isFunction, isNil, isNumber, isObject, isString, isUndefined, union } from 'lodash';
import { IStore } from '..';
import { IBucket, IDemuxed, IDynamicObject, IOptions, IPermission, IPermissions, IResource, IResources, IRole, IRoles, IRolesObject, IRolesObjectAllows, IRolesObjects, IRolesParent, IRolesParents, IUserId, IUserIds, IUserRoles } from '../types';
import { Common } from './common';
import { HttpError } from './httpError';
/**
* {@inheritDoc}
* @description Acl class.
*/
export class Acl extends Common {
public options: IOptions;
public store: IStore;
constructor(store: IStore, options?: IOptions) {
super();
this.store = store;
this.options = extend({
buckets: {
meta: 'meta',
parents: 'parents',
permissions: 'permissions',
resources: 'resources',
roles: 'roles',
users: 'users',
},
}, options);
}
/**
* @description Adds the given permissions to the given roles over the given resources.
* @param roles
* @param resources
* @param permissions
* @return Promise<void>
*/
public async allow(roles: IRole | IRoles | IRolesObjects, resources?: IResource | IResources, permissions?: IPermission | IPermissions): Promise<void> {
if (arguments.length === 1) {
return this.allowEx(roles as IRolesObjects);
}
const rolesParam = Common.MAKE_ARRAY(roles as IRole | IRoles);
const resourcesParam = Common.MAKE_ARRAY(resources);
this.store.begin();
this.store.add(this.options.buckets.meta, 'roles', rolesParam);
resourcesParam.forEach((resource: IResource) => {
rolesParam.forEach((role: IRole) => this.store.add(this.allowsBucket(resource), role, permissions), this);
});
rolesParam.forEach((role: IRole) => this.store.add(this.options.buckets.resources, role, resourcesParam));
return this.store.end();
}
/**
* @description Adds roles to a given user id.
* @param userId
* @param roles
* @return Promise<void>
*/
public async addUserRoles(userId: IUserId, roles: IRole | IRoles): Promise<void> {
this.store.begin();
const rolesParams = Common.MAKE_ARRAY(roles);
this.store.add(this.options.buckets.meta, 'users', userId);
this.store.add(this.options.buckets.users, userId, roles);
rolesParams.forEach((role: IRole) => this.store.add(this.options.buckets.roles, role, userId));
return this.store.end();
}
/**
* @description Returns all the roles from a given user.
* @param userId
* @return Promise<IUserRoles>
*/
public async userRoles(userId: IUserId): Promise<IUserRoles> {
return this.store.get(this.options.buckets.users, userId);
}
/**
* @description Return boolean whether user is in the role.
* @param userId
* @param role
* @return Promise<boolean>
*/
public async hasRole(userId: IUserId, role: IRole): Promise<boolean> {
const roles = await this.userRoles(userId);
return roles.indexOf(role) !== -1;
}
/**
* @description Returns all users who has a given role.
* @param role
* @return Promise<IUserIds>
*/
public async roleUsers(role: IRole): Promise<IUserIds> {
return this.store.get(this.options.buckets.roles, role);
}
/**
* @description Adds a parent or parent list to role.
* @param role
* @param parents
* @return Promise<void>
*/
public async addRoleParents(role: IRole, parents: IRolesParent | IRolesParents): Promise<void> {
this.store.begin();
this.store.add(this.options.buckets.meta, 'roles', role);
this.store.add(this.options.buckets.parents, role, parents);
return this.store.end();
}
/**
* @description Checks if the given user is allowed to access the resource for the given permissions (note: it must fulfill all the permissions).
* @param userId
* @param resource
* @param permissions
* @return Promise<boolean>
*/
public async isAllowed(userId: IUserId, resource: IResource, permissions: IPermission | IPermissions): Promise<boolean> {
const roles = await this.store.get(this.options.buckets.users, userId);
if (roles.length > 0) {
return this.areAnyRolesAllowed(roles, resource, permissions);
}
return false;
}
/**
* @description Returns true if any of the given roles have the right permissions.
* @param roles
* @param resource
* @param permissions
* @return Promise<boolean>
*/
public async areAnyRolesAllowed(roles: IRole | IRoles, resource: IResource, permissions: IPermission | IPermissions): Promise<boolean> {
const rolesParam = Common.MAKE_ARRAY(roles);
const permissionsParam = Common.MAKE_ARRAY(permissions);
if (rolesParam.length === 0) {
return false;
}
return this.checkPermissions(rolesParam, resource, permissionsParam);
}
/**
* @description Checks role permissions.
* @param roles
* @param resource
* @param permissions
* @return Promise<boolean>
*/
public async checkPermissions(roles: IRoles, resource: IResource, permissions: IPermissions): Promise<boolean> {
const resourcePermissions = await this.store.union(this.allowsBucket(resource), roles);
if (resourcePermissions.indexOf('*') !== -1) {
return true;
}
const permissionsFiltered = permissions.filter((p: IPermission) => resourcePermissions.indexOf(p) === -1);
if (permissionsFiltered.length === 0) {
return true;
}
const parents = await this.store.union(this.options.buckets.parents, roles);
return (parents.length > 0) ? this.checkPermissions(parents, resource, permissionsFiltered) : false;
}
/**
* @description Returns all the allowable permissions a given user have to access the given resources.
* It returns an array of objects where every object maps a resource name to a list of permissions for that resource.
* @param userId
* @param resources
* @return Promise<IDynamicObject>
*/
public async allowedPermissions(userId: IUserId, resources: IResource | IResources): Promise<IDynamicObject> {
if (isFunction(this.store.unions)) {
return this.optimizedAllowedPermissions(userId, resources);
}
const resourcesParams = Common.MAKE_ARRAY(resources);
const roles: IRoles = await this.userRoles(userId);
const result = {};
await Promise.all(resourcesParams.map(async (resource: IResource) => {
result[resource] = await this.resourcePermissions(roles, resource);
}));
return result;
}
/**
* @description Returns all the allowable permissions a given user have to access the given resources.
* It returns a map of resource name to a list of permissions for that resource.
* This is the same as allowedPermissions, it just takes advantage of the unions function if available to reduce the number of backend queries.
* @param userId
* @param resources
* @return Promise<IDynamicObject>
*/
public async optimizedAllowedPermissions(userId: IUserId, resources: IResource | IResources): Promise<IDynamicObject> {
const resourcesParam = Common.MAKE_ARRAY(resources);
const roles: IRoles = await this.allUserRoles(userId);
const buckets = resourcesParam.map(this.allowsBucket, this);
let response = {};
if (roles.length === 0) {
const emptyResult = {};
buckets.forEach((bucket: IBucket) => emptyResult[bucket] = []);
response = emptyResult;
}
response = await this.store.unions(buckets, roles);
const result = {};
Object.keys(response).forEach((bucket: IBucket) => {
result[this.keyFromAllowsBucket(bucket)] = response[bucket]
}, this);
return result;
}
/**
* @description Returns resources from role.
* @param roles
* @param permissions
* @return Promise<IDynamicObject>
*/
public async whatResources(roles: IRole | IRoles, permissions?: IPermission | IPermissions): Promise<IDynamicObject> {
const rolesParam = Common.MAKE_ARRAY(roles);
if (permissions === undefined) {
return this.permittedResources(rolesParam);
}
return this.permittedResources(rolesParam, Common.MAKE_ARRAY(permissions));
}
/**
* @description Returns permitted resources.
* @param roles
* @param permissions
* @return Promise<IResources>
*/
public async permittedResources(roles: IRoles, permissions?: IPermission | IPermissions): Promise<IResources> {
const result = permissions === undefined ? {} : [];
const rolesParam = Common.MAKE_ARRAY(roles);
const resources: IResources = await this.rolesResources(rolesParam);
await Promise.all(resources.map(async (resource: IResource) => {
const resourcePermissions: IPermissions = await this.resourcePermissions(rolesParam, resource);
if (Array.isArray(result)) {
const commonPermissions = intersection(permissions, resourcePermissions);
if (commonPermissions.length > 0) {
result.push(resource);
}
} else {
result[resource] = resourcePermissions;
}
}));
if (isObject(result)) {
const resultArray = [];
Object.entries(result).forEach((item: [string, string]) => resultArray[item[0]] = item[1]);
return resultArray;
}
return result;
}
/**
* @description Removes allow.
* @param role
* @param resources
* @param permissions
* @return Promise<void>
*/
public async removeAllow(role: IRole, resources: IResource | IResources, permissions?: IPermission | IPermissions): Promise<void> {
const resourcesParam = Common.MAKE_ARRAY(resources);
if (permissions !== undefined && !isFunction(permissions)) {
return this.removePermissions(role, resourcesParam, Common.MAKE_ARRAY(permissions));
}
return this.removePermissions(role, resourcesParam);
}
/**
* @description Remove permissions.
* @param role
* @param resources
* @param permissions
* @return Promise<void>
*/
public async removePermissions(role: IRole, resources: IResource | IResources, permissions?: IPermission | IPermissions): Promise<void> {
const resourcesParams = Common.MAKE_ARRAY(resources);
this.store.begin();
resourcesParams.forEach(async (resource: IResource) => {
const bucket = this.allowsBucket(resource);
if (permissions !== undefined) {
await this.store.remove(bucket, role, Common.MAKE_ARRAY(permissions));
} else {
await this.store.del(bucket, role);
await this.store.remove(this.options.buckets.resources, role, resource);
}
}, this);
await this.store.end();
this.store.begin();
await Promise.all(resourcesParams.map(async (resource: IResource) => {
const bucket: IBucket = this.allowsBucket(resource);
const permissionsRetrieved: IPermissions = await this.store.get(bucket, role);
if (permissionsRetrieved.length === 0) {
await this.store.remove(this.options.buckets.resources, role, resource);
}
}, this));
return this.store.end();
}
/**
* @description Removes a role from the system.
* @param role
* @return Promise<void>
*/
public async removeRole(role: IRole): Promise<void> {
const resources: IResources = await this.store.get(this.options.buckets.resources, role);
this.store.begin();
resources.forEach(async (resource: IResource) => {
const bucket = this.allowsBucket(resource);
await this.store.del(bucket, role);
}, this);
await this.store.del(this.options.buckets.resources, role);
await this.store.del(this.options.buckets.parents, role);
await this.store.del(this.options.buckets.roles, role);
await this.store.remove(this.options.buckets.meta, 'roles', role);
return this.store.end();
}
/**
* @description Removes a parent or parent list from role. If `parents` is not specified, removes all parents.
* @param role
* @param parents
* @return Promise<void>
*/
public async removeRoleParents(role: IRole, parents?: IRolesParent | IRolesParents): Promise<void> {
this.store.begin();
if (parents !== undefined) {
await this.store.remove(this.options.buckets.parents, role, parents);
} else {
await this.store.del(this.options.buckets.parents, role);
}
return this.store.end();
}
/**
* @description Removes a resource from the system.
* @param resource
* @return Promise<void>
*/
public async removeResource(resource: IResource): Promise<void> {
const roles: IRoles = await this.store.get(this.options.buckets.meta, 'roles');
this.store.begin();
await this.store.del(this.allowsBucket(resource), roles);
await Promise.all(roles.map(async (role: IRole) => this.store.remove(this.options.buckets.resources, role, resource), this));
return this.store.end();
}
/**
* @description Removes user with his associated roles.
* @param userId
* @return Promise<void>
*/
public async removeUser(userId: string | number): Promise<void> {
const userRoles = await this.userRoles(userId);
await this.removeUserRoles(userId, userRoles);
this.store.begin();
await this.store.del(this.options.buckets.users, userId);
return this.store.end();
}
/**
* @description Remove roles from a given user.
* @param userId
* @param roles
* @return Promise<void>
*/
public async removeUserRoles(userId: IUserId, roles: IRole | IRoles): Promise<void> {
this.store.begin();
await this.store.remove(this.options.buckets.users, userId, roles);
if (Array.isArray(roles)) {
await Promise.all(roles.map(async (role: IRole) => this.store.remove(this.options.buckets.roles, role, userId)));
} else {
await this.store.remove(this.options.buckets.roles, roles, userId);
}
return this.store.end();
}
/**
* @description Express middleware.
* @param numPathComponents
* @param userId
* @param method
* @return void
*/
public middleware(numPathComponents: number, userId: string | number | Function | null, method: string): (req: express.Request, res: express.Response, next: express.NextFunction) => void {
return (req: express.Request, res: express.Response, next: express.NextFunction) => {
let userIdTmp = userId;
let actionsTmp = method;
// Call function to fetch userId
if (isFunction(userId)) {
userIdTmp = userId(req, res); // tslint:disable-line no-unsafe-any
}
if (isNil(userId)) {
// @ts-ignore
if (isObject(req.session) && (isString(req.session.userId) || isNumber(req.session.userId))) { // tslint:disable-line no-unsafe-any
// @ts-ignore
userIdTmp = req.session.userId; // tslint:disable-line no-unsafe-any
// @ts-ignore
} else if (isObject(req.user) && (isString(req.user.id) || isNumber(req.user.id))) { // tslint:disable-line no-unsafe-any
// @ts-ignore
userIdTmp = req.user.id; // tslint:disable-line no-unsafe-any
} else {
return next(new HttpError(401, 'User not authenticated'));
}
}
if (isUndefined(userIdTmp)) {
return next(new HttpError(401, 'User not authenticated'));
}
const url = req.originalUrl.split('?')[0];
const resource = numPathComponents === 0 ? url : url.split('/').slice(0, numPathComponents + 1).join('/');
if (!isUndefined(actionsTmp)) {
actionsTmp = req.method.toLowerCase();
}
// @ts-ignore
this.isAllowed(userIdTmp, resource, actionsTmp)
.then((allowed: boolean) => {//}, (err, allowed) => {
if (!allowed) {
return next(new HttpError(403, 'Insufficient permissions to access resource'));
}
return next();
})
.catch(() => next(new Error('Error checking permissions to access resource')));
};
}
/**
* @description Returns all roles in the hierarchy of the given user.
* @param userId
* @return Promise<IRoles>
*/
private async allUserRoles(userId: IUserId): Promise<IRoles> {
const roles = await this.userRoles(userId);
if (roles.length > 0) {
return this.allRoles(roles);
}
return [];
}
/**
* @description Returns all roles in the hierarchy including the given roles.
* @param roles
* @return Promise<IRoles>
*/
private async allRoles(roles: IRoles): Promise<IRoles> {
const parents = await this.rolesParents(roles);
if (parents.length > 0) {
const parentRoles = await this.allRoles(parents);
return union(roles, parentRoles);
}
return roles;
}
/**
* @description Returns the parents of the given roles.
* @param roles
* @return Promise<IRolesParents>
*/
private async rolesParents(roles: IRoles): Promise<IRolesParents> {
return this.store.union(this.options.buckets.parents, roles);
}
/**
* @description Same as allow but accepts a more compact input.
* @param rolesArray
* @return Promise<void>
*/
private async allowEx(rolesArray: IRolesObjects): Promise<void> {
const rolesArrayParam = rolesArray;
const demuxed = [];
rolesArrayParam.forEach((obj: IRolesObject) => {
const roles = obj.roles;
obj.allows.forEach((allow: IRolesObjectAllows) => {
demuxed.push({
roles:roles,
resources:allow.resources,
permissions:allow.permissions,
});
});
});
demuxed.reduce(async (_: undefined, obj: IDemuxed) => {
await this.allow(obj.roles, obj.resources, obj.permissions)
}, undefined);
}
/**
* @description Returns the permissions for the given resource and set of roles.
* @param roles
* @param resource
* @return Promise<IPermissions>
*/
private async resourcePermissions(roles: IRoles, resource: IResource): Promise<IPermissions> {
const rolesTmp = Common.MAKE_ARRAY(roles);
if (rolesTmp.length ===0 ) {
return [];
}
const resourcePermissions = await this.store.union(this.allowsBucket(resource), rolesTmp);
const parents = await this.rolesParents(rolesTmp);
if (parents.length > 0) {
const morePermissions = await this.resourcePermissions(parents, resource);
return union(resourcePermissions, morePermissions);
}
return resourcePermissions;
}
/**
* @description Returns an array with resources for the given roles.
* @param roles
* @return Promise<IResources>
*/
private async rolesResources(roles: IRole | IRoles): Promise<IResources> {
const rolesTmp = Common.MAKE_ARRAY(roles);
const allRoles = await this.allRoles(rolesTmp);
let result = [];
await Promise.all(allRoles.map(async (role: IRole) => {
const resources: IResources = await this.store.get(this.options.buckets.resources, role);
result = result.concat(resources);
}));
return result;
}
} | the_stack |
import {JVMThread} from './threading';
import {ThreadStatus} from './enums';
import assert from './assert';
/**
* Represents a JVM monitor.
*/
export default class Monitor {
/**
* The owner of the monitor.
*/
private owner: JVMThread = null;
/**
* Number of times that the current owner has locked this monitor.
*/
private count: number = 0;
/**
* JVM threads that are waiting for the current owner to relinquish the
* monitor.
*/
private blocked: {
[threadRef: number]: {
/**
* The blocked thread.
*/
thread: JVMThread;
/**
* A callback that should be triggered once the thread becomes the
* owner of the monitor.
*/
cb: () => void;
/**
* The lock count to restore once the thread owns the lock.
*/
count: number;
}
} = {};
/**
* Queue of JVM threads that are waiting for a JVM thread to notify them.
*/
private waiting: {
[threadRef: number]: {
/**
* The blocked thread.
*/
thread: JVMThread;
/**
* A callback that should be triggered once the thread owns the monitor.
*/
cb: (fromTimer: boolean) => void;
/**
* The thread's lock count at the time it invoked Object.wait.
*/
count: number;
/**
* True if the thread issued waiting with a timeout.
*/
isTimed: boolean;
/**
* The timer ID for the timeout callback, if isTimed is true. Allows us
* to revoke timeout timers before they execute.
*/
timer?: number;
}
} = {};
/**
* Attempts to acquire the monitor.
*
* Thread transitions:
* * RUNNABLE => BLOCKED [If fails to acquire lock]
*
* @param thread The thread that is trying to acquire the monitor.
* @param cb If this method returns false, then this callback will be
* triggered once the thread becomes owner of the monitor. At that time,
* the thread will be in the RUNNABLE state.
* @return True if successfull, false if not. If not successful, the thread
* becomes BLOCKED, and the input callback will be triggered once the
* thread owns the monitor and is RUNNABLE.
*/
public enter(thread: JVMThread, cb: () => void): boolean {
if (this.owner === thread) {
this.count++;
return true;
} else {
return this.contendForLock(thread, 1, ThreadStatus.BLOCKED, cb);
}
}
/**
* Generic version of Monitor.enter for contending for the lock.
*
* Thread transitions:
* * RUNNABLE => UNINTERRUPTIBLY_BLOCKED [If fails to acquire lock]
* * RUNNABLE => BLOCKED [If fails to acquire lock]
*
* @param thread The thread contending for the lock.
* @param count The lock count to use once the thread owns the lock.
* @param blockStatus The ThreadStatus to use should the thread need to
* contend for the lock (either BLOCKED or UNINTERRUPTIBLY_BLOCKED).
* @param cb The callback to call once the thread becomes owner of the lock.
* @return True if the thread immediately acquired the lock, false if the
* thread is now blocked on the lock.
*/
private contendForLock(thread: JVMThread, count: number, blockStatus: ThreadStatus, cb: () => void): boolean {
var owner = this.owner;
assert(owner != thread, "Thread attempting to contend for lock it already owns!");
if (owner === null) {
assert(this.count === 0);
this.owner = thread;
this.count = count;
return true;
} else {
/**
* "If another thread already owns the monitor associated with objectref,
* the thread blocks until the monitor's entry count is zero, then tries
* again to gain ownership."
* @from http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.monitorenter
*/
this.blocked[thread.getRef()] = { thread: thread, cb: cb, count: count };
thread.setStatus(blockStatus, this);
return false;
}
}
/**
* Exits the monitor. Handles notifying the waiting threads if the lock
* becomes available.
*
* Thread transitions:
* * *NONE* on the argument thread.
* * A *BLOCKED* thread may be scheduled if the owner gives up the monitor.
*
* @param thread The thread that is exiting the monitor.
* @return True if exit succeeded, false if an exception occurred.
*/
public exit(thread: JVMThread): boolean {
var owner = this.owner;
if (owner === thread) {
if (--this.count === 0) {
this.owner = null;
this.appointNewOwner();
}
} else {
/**
* "If the thread that executes monitorexit is not the owner of the
* monitor associated with the instance referenced by objectref,
* monitorexit throws an IllegalMonitorStateException."
* @from http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.monitorexit
*/
thread.throwNewException('Ljava/lang/IllegalMonitorStateException;', "Cannot exit a monitor that you do not own.");
}
return owner === thread;
}
/**
* Chooses one of the blocked threads to become the monitor's owner.
*/
private appointNewOwner() {
var blockedThreadRefs = Object.keys(this.blocked);
if (blockedThreadRefs.length > 0) {
// Unblock a random thread.
var unblockedRef = blockedThreadRefs[Math.floor(Math.random() * blockedThreadRefs.length)],
// XXX: Typing hack. Key must be a number.
unblocked = this.blocked[<number><any>unblockedRef];
this.unblock(unblocked.thread, false);
}
}
/**
* "Causes the current thread to wait until another thread invokes the
* notify() method or the notifyAll() method for this object, or some other
* thread interrupts the current thread, or a certain amount of real time
* has elapsed.
*
* This method causes the current thread (call it T) to place itself in the
* wait set for this object and then to relinquish any and all
* synchronization claims on this object."
*
* We coalesce all possible wait configurations into this one function.
* @from http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait(long, int)
* @param thread The thread that wants to wait on this monitor.
* @param cb The callback triggered once the thread wakes up.
* @param timeoutMs? An optional timeout that specifies how long the thread
* should wait, in milliseconds. If this value is 0, then we ignore it.
* @param timeoutNs? An optional timeout that specifies how long the thread
* should wait, in nanosecond precision (currently ignored).
* @todo Use high-precision timers in browsers that support it.
* @return True if the wait succeeded, false if it triggered an exception.
*/
public wait(thread: JVMThread, cb: (fromTimer: boolean) => void, timeoutMs?: number, timeoutNs?: number): boolean {
if (this.getOwner() === thread) {
// INVARIANT: Thread shouldn't currently be blocked on a monitor.
assert(thread.getStatus() !== ThreadStatus.BLOCKED);
this.waiting[thread.getRef()] = {
thread: thread,
cb: cb,
count: this.count,
isTimed: timeoutMs != null && timeoutMs !== 0
};
// Revoke ownership.
this.owner = null;
this.count = 0;
if (timeoutMs != null && timeoutMs !== 0) {
// Scheduler a timer that wakes up the thread.
// XXX: Casting to 'number', since NodeJS typings specify a Timer.
this.waiting[thread.getRef()].timer = <number><any> setTimeout(() => {
this.unwait(thread, true);
}, timeoutMs);
thread.setStatus(ThreadStatus.TIMED_WAITING, this);
} else {
thread.setStatus(ThreadStatus.WAITING, this);
}
// Select a new owner.
this.appointNewOwner();
return true;
} else {
/**
* "The current thread must own this object's monitor"
*/
thread.throwNewException('Ljava/lang/IllegalMonitorStateException;', "Cannot wait on an object that you do not own.");
return false;
}
}
/**
* Removes the specified thread from the waiting set, and makes it compete
* for the monitor lock. Once it acquires the lock, we restore its lock
* count prior to triggering the wait callback.
*
* If the thread is interrupted, the wait callback is *not* triggered.
*
* @param thread The thread to remove.
* @param fromTimer Indicates if this function call was triggered from a
* timer event.
* @param [interrupting] If true, then we are *interrupting* the wait. Do not
* trigger the wait callback.
* @param [unwaitCb] If interrupting is true, then this callback is triggered
* once the thread reacquires the lock.
*/
public unwait(thread: JVMThread, fromTimer: boolean, interrupting: boolean = false, unwaitCb: () => void = null): void {
// Step 1: Remove the thread from the waiting set.
var waitEntry = this.waiting[thread.getRef()],
// Interrupting a previously-waiting thread before it acquires a lock
// makes no semantic sense, as the thread is currently suspended in a
// synchronized block that requires ownership of the monitor.
blockStatus = ThreadStatus.UNINTERRUPTABLY_BLOCKED,
blockCb = () => {
// Thread is RUNNABLE before we trigger the callback.
thread.setStatus(ThreadStatus.RUNNABLE);
if (interrupting) {
unwaitCb();
} else {
waitEntry.cb(fromTimer);
}
};
assert(waitEntry != null);
delete this.waiting[thread.getRef()];
// Step 2: Remove the timer if the timer did not trigger this event.
if (thread.getStatus() === ThreadStatus.TIMED_WAITING && !fromTimer) {
var timerId = waitEntry.timer;
assert(timerId != null);
clearTimeout(timerId);
}
// Step 3: Acquire the monitor [ASYNC]
if (this.contendForLock(thread, waitEntry.count, blockStatus, blockCb)) {
// Success! Trigger the blockCb anyway. If 'contendForLock' returns false,
// it will trigger blockCb once the thread acquires the lock.
blockCb();
}
}
/**
* Removes the specified thread from being blocked on the monitor so it can
* re-compete for ownership.
* @param [interrupting] If true, we are interrupting the monitor block. The
* thread should not acquire the lock, and the block callback should not
* be triggered.
*/
public unblock(thread: JVMThread, interrupting: boolean = false): void {
var blockEntry = this.blocked[thread.getRef()];
// Cannot interrupt an uninterruptibly blocked thread.
assert(interrupting ? thread.getStatus() === ThreadStatus.BLOCKED : true);
if (blockEntry != null) {
delete this.blocked[thread.getRef()];
thread.setStatus(ThreadStatus.RUNNABLE);
if (!interrupting) {
// No one else can own the monitor.
assert(this.owner == null && this.count === 0, "T" + thread.getRef() + ": We're not interrupting a block, but someone else owns the monitor?! Owned by " + (this.owner == null ? "[no one]" : "" + this.owner.getRef()) + " Count: " + this.count);
// Assign this thread as the monitor owner.
this.owner = thread;
this.count = blockEntry.count;
// Trigger the callback.
blockEntry.cb();
}
}
}
/**
* Notifies a single waiting thread.
* @param thread The notifying thread. *MUST* be the owner.
*/
public notify(thread: JVMThread): void {
if (this.owner === thread) {
var waitingRefs = Object.keys(this.waiting);
if (waitingRefs.length > 0) {
// Notify a random thread.
this.unwait(this.waiting[<number><any>waitingRefs[Math.floor(Math.random() * waitingRefs.length)]].thread, false);
}
} else {
/**
* "Throws IllegalMonitorStateException if the current thread is not the
* owner of this object's monitor."
* @from http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notify()
*/
thread.throwNewException('Ljava/lang/IllegalMonitorStateException;', "Cannot notify on a monitor that you do not own.");
}
}
/**
* Notifies all waiting threads.
* @param thread The notifying thread. *MUST* be the owner.
*/
public notifyAll(thread: JVMThread): void {
if (this.owner === thread) {
var waitingRefs = Object.keys(this.waiting), i: number;
// Notify each thread.
for (i = 0; i < waitingRefs.length; i++) {
this.unwait(this.waiting[<number><any>waitingRefs[i]].thread, false);
}
} else {
/**
* "Throws IllegalMonitorStateException if the current thread is not the
* owner of this object's monitor."
* @from http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notifyAll()
*/
thread.throwNewException('Ljava/lang/IllegalMonitorStateException;', "Cannot notifyAll on a monitor that you do not own.");
}
}
/**
* @return The owner of the monitor.
*/
public getOwner(): JVMThread {
return this.owner;
}
public isWaiting(thread: JVMThread): boolean {
// Waiting, but *not* timed waiting.
return this.waiting[thread.getRef()] != null && !this.waiting[thread.getRef()].isTimed;
}
public isTimedWaiting(thread: JVMThread): boolean {
// Timed waiting, *not* waiting.
return this.waiting[thread.getRef()] != null && this.waiting[thread.getRef()].isTimed;
}
public isBlocked(thread: JVMThread): boolean {
// Blocked.
return this.blocked[thread.getRef()] != null;
}
} | the_stack |
import React, { useState, MouseEvent, useEffect, ChangeEvent } from 'react';
import { useLocation, useHistory } from 'react-router-dom';
import {
ThemeProvider,
IconButton,
Button,
InputLabel,
FormControl,
Select,
MenuItem,
} from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add';
import SwapVert from '@material-ui/icons/SwapVert';
import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined';
import { ReactComponent as Euro } from '../../assets/world.svg';
import { ReactComponent as Dollar } from '../../assets/flag.svg';
import { ReactComponent as Pound } from '../../assets/uk.svg';
import { theme } from '../../utils/theme';
import { useAccountStyles } from './styles/Account.style';
import {
useCreateTransactionMutation,
useTransactionsQuery,
TransactionsDocument,
useAddMoneyMutation,
useMeQuery,
CreateTransactionMutation,
CreateTransactionMutationVariables,
AddMoneyMutation,
AddMoneyMutationVariables,
TransactionsQueryResult,
MeQueryResult,
useAccountQuery,
ExchangeMutation,
ExchangeMutationVariables,
useExchangeMutation,
AccountQueryResult,
CardsQueryResult,
useCardsQuery,
AccountsQueryResult,
useAccountsQuery,
DeleteAccountMutationVariables,
DeleteAccountMutation,
useDeleteAccountMutation,
} from '../../generated/graphql';
import { Dialog } from '../../components/Dialog/Dialog';
import { FormTextField } from '../../components/Forms/FormTextField';
import { Form, Formik } from 'formik';
import { Title } from '../../components/Typography/Title';
import { MutationTuple } from '@apollo/react-hooks';
import { ExecutionResult } from 'graphql';
import { ExecutionResultDataDefault } from 'graphql/execution/execute';
import { Transactions } from './Transactions/Transactions';
import { ErrorMessage, SuccessMessage, WarningMessage } from '../../components/Alerts/AlertMessage';
import { addMoneyValidationSchema } from '../../schemas/addMoneyValidationSchema';
import { Loading } from '../../components/Loading/Loading';
export const Account: React.FC = () => {
// State
const [toAccountCurrency, setToAccountCurrency] = useState<string>('');
const [accountBalance, setAccountBalance] = useState<number>(0);
const [openAddDialog, setOpenAddDialog] = useState<boolean>(false);
const [openExchangeDialog, setOpenExchangeDialog] = useState<boolean>(false);
const [openDetailsDialog, setOpenDetailsDialog] = useState<boolean>(false);
const [hasCard, setHasCard] = useState<boolean>(false);
const [cardNumber, setCardNumber] = useState<string>('');
const [successMessage, setSuccessMessage] = useState<string>('');
const [errorMessage, setErrorMessage] = useState<string>('');
const [warningMessage, setWarningMessage] = useState<string>('');
const [showLoadingIcon, setShowLoadingIcon] = useState<boolean>(false);
const location = useLocation<any>();
const history = useHistory();
// GraphQL Mutations
const [createTransaction]: MutationTuple<
CreateTransactionMutation,
CreateTransactionMutationVariables
> = useCreateTransactionMutation();
const [addMoney]: MutationTuple<
AddMoneyMutation,
AddMoneyMutationVariables
> = useAddMoneyMutation();
const [exchange]: MutationTuple<
ExchangeMutation,
ExchangeMutationVariables
> = useExchangeMutation();
const [deleteAccount]: MutationTuple<
DeleteAccountMutation,
DeleteAccountMutationVariables
> = useDeleteAccountMutation();
// GraphQL Queries
const user: MeQueryResult = useMeQuery();
const account: AccountQueryResult = useAccountQuery({
variables: { currency: location.state.currency },
});
const accounts: AccountsQueryResult = useAccountsQuery();
const cards: CardsQueryResult = useCardsQuery();
const { data }: TransactionsQueryResult = useTransactionsQuery({
variables: { currency: location.state.currency },
});
const classes = useAccountStyles();
let currencyIcon: string = '';
let currencyFullText: string = '';
let svg: any | string;
// When the component mounts, fetch the account balance
useEffect(() => {
if (account.data) {
setAccountBalance(account.data.account.balance);
} else {
setAccountBalance(location.state.balance);
}
}, [account, location]);
// When the component mounts, check if a card exists for the account
useEffect(() => {
if (cards.data && cards.data.cards.length > 0) {
setHasCard(true);
setCardNumber(cards.data.cards[0].cardNumber);
}
}, [cards]);
useEffect(() => {
if (accountBalance < 0) {
setWarningMessage(
'Your account balance has fallen below 0. Please top up your account.',
);
}
}, [accountBalance]);
switch (location.state.currency) {
case 'EUR':
currencyIcon = '€';
currencyFullText = 'Euro';
svg = <Euro />;
break;
case 'USD':
currencyIcon = '$';
currencyFullText = 'US Dollar';
svg = <Dollar />;
break;
case 'GBP':
currencyIcon = '£';
currencyFullText = 'British Pound';
svg = <Pound />;
break;
}
const simulate = async (): Promise<void> => {
try {
const response: ExecutionResult<ExecutionResultDataDefault> = await createTransaction({
variables: {
currency: location.state.currency,
},
refetchQueries: [
{
query: TransactionsDocument,
variables: {
currency: location.state.currency,
},
},
],
});
if (response && response.data) {
// Update the account balance
setAccountBalance(response.data.createTransaction);
}
} catch (error) {
const errorMessage: string = error.message.split(':')[1];
console.log(errorMessage);
}
};
const renderAddDialog = (): JSX.Element => {
return (
<Dialog isOpen={openAddDialog} onClose={() => setOpenAddDialog(false)}>
<Title title="Add money" fontSize={18} />
<div style={{ marginTop: 12 }}>
<Formik
initialValues={{ amount: 10 }}
validationSchema={addMoneyValidationSchema}
onSubmit={async (data, { setSubmitting, resetForm }) => {
setSubmitting(true);
// Call the add money mutation
try {
const response = await addMoney({
variables: {
amount: data.amount,
currency: location.state.currency,
},
});
if (response && response.data) {
setSubmitting(false);
setSuccessMessage(response.data.addMoney.message);
resetForm();
}
} catch (error) {
const errorMessage = error.message.split(':')[1];
setErrorMessage(errorMessage);
setSubmitting(false);
}
}}
>
{({ isSubmitting }) => (
<div>
<Form>
<FormTextField
name="amount"
placeholder="amount"
type="number"
/>
<div>
<ThemeProvider theme={theme}>
<Button
className={classes.dialogButton}
disabled={isSubmitting}
variant="contained"
color="secondary"
type="submit"
>
Add money
</Button>
</ThemeProvider>
</div>
</Form>
</div>
)}
</Formik>
</div>
</Dialog>
);
};
const renderExchangeDialog = (): JSX.Element => {
return (
<Dialog isOpen={openExchangeDialog} onClose={() => setOpenExchangeDialog(false)}>
<Title title="Exchange" fontSize={18} />
<div style={{ marginTop: 12 }}>
<Formik
initialValues={{ amount: 10 }}
onSubmit={async (data, { setSubmitting, resetForm }) => {
setSubmitting(true);
// If the user has selected a currency account to exchange to, call the exchange mutation
if (toAccountCurrency !== '') {
try {
const response = await exchange({
variables: {
selectedAccountCurrency: location.state.currency,
toAccountCurrency: toAccountCurrency,
amount: data.amount,
},
});
if (response && response.data) {
// if the exchange was a success update the account balance and render a success message
setSubmitting(false);
setSuccessMessage(response.data.exchange.message);
resetForm();
}
} catch (error) {
const errorMessage: string = error.message.split(':')[1];
setErrorMessage(errorMessage);
setSubmitting(false);
}
}
}}
>
{({ isSubmitting }) => (
<div>
<Form>
<FormTextField
name="amount"
placeholder="amount"
type="number"
/>
<ThemeProvider theme={theme}>
<FormControl style={{ marginLeft: 8 }} variant="outlined">
<InputLabel id="select-filled-label">To</InputLabel>
<Select
labelId="select-filled-label"
id="select-filled"
value={toAccountCurrency}
onChange={(
event: ChangeEvent<{ value: unknown }>,
) => {
setToAccountCurrency(
event.target.value as string,
);
}}
label="To"
>
{accounts.data &&
accounts.data.accounts
.filter(account => {
return (
account.currency !==
location.state.currency
);
})
.map(account => {
return (
<MenuItem
key={account.id}
value={account.currency}
>
{account.currency}
</MenuItem>
);
})}
</Select>
</FormControl>
</ThemeProvider>
<div>
<ThemeProvider theme={theme}>
<Button
className={classes.dialogButton}
disabled={isSubmitting}
variant="contained"
color="secondary"
type="submit"
>
Exchange
</Button>
</ThemeProvider>
</div>
</Form>
</div>
)}
</Formik>
</div>
</Dialog>
);
};
const renderDetailsDialog = (): JSX.Element | undefined => {
if (user && user.data && user.data.me) {
return (
<Dialog isOpen={openDetailsDialog} onClose={() => setOpenDetailsDialog(false)}>
Beneficiary: {user.data.me.firstName} {user.data.me.lastName} <br />
IBAN: {location.state.iban} <br />
BIC: {location.state.bic}
<div style={{ marginTop: 12 }}>
<ThemeProvider theme={theme}>
<Button
className={classes.dialogButton}
variant="contained"
color="secondary"
onClick={async () => {
// On button click, call the deleteAccount mutation
try {
const response: ExecutionResult<ExecutionResultDataDefault> = await deleteAccount(
{
variables: {
currency: location.state.currency,
},
},
);
if (response && response.data) {
setShowLoadingIcon(true);
setTimeout(async () => {
history.push('/dashboard');
history.go(0);
}, 3000);
}
} catch (error) {
const warning: string = error.message.split(':')[1];
setWarningMessage(warning);
}
}}
>
Delete account
</Button>
</ThemeProvider>
</div>
</Dialog>
);
}
};
const renderAlertMessage = (): JSX.Element | undefined => {
if (successMessage.length > 0) {
return (
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
<SuccessMessage message={successMessage} />
</div>
);
} else if (errorMessage.length > 0) {
return (
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
<ErrorMessage message={errorMessage} />
</div>
);
} else if (warningMessage.length > 0) {
return (
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
<WarningMessage message={warningMessage} />
</div>
);
}
};
if (!showLoadingIcon) {
return (
<div className={classes.root}>
{renderAddDialog()}
{renderExchangeDialog()}
{renderDetailsDialog()}
{renderAlertMessage()}
<div style={{ position: 'absolute', right: 20 }}>
<ThemeProvider theme={theme}>
<Button
color="secondary"
variant="contained"
style={{
fontWeight: 'bold',
letterSpacing: 1,
textTransform: 'none',
}}
onClick={() => {
if (hasCard) {
simulate();
} else {
setErrorMessage(
"Can't make this transaction. Please register a card first.",
);
}
if (accountBalance < 0) {
setErrorMessage(
'You do not have the sufficient funds. Please top up your account.',
);
}
}}
>
Simulate
</Button>
</ThemeProvider>
</div>
<div className={classes.accountBalance}>
{currencyIcon}
{accountBalance}
</div>
<div className={classes.accountInfo}>
<div>{currencyFullText}</div>
<div style={{ width: 32 }}>{svg}</div>
<div>{location.state.currency}</div>
</div>
<div className={classes.accountButtonsSection}>
<ThemeProvider theme={theme}>
<div>
<IconButton
className={classes.accountButton}
aria-label="Add"
onClick={e => {
e.preventDefault();
setOpenAddDialog(true);
}}
>
<AddIcon />
</IconButton>
<div className={classes.accountButtonText}>Add money</div>
</div>
<div>
<IconButton
className={classes.accountButton}
aria-label="Exchange"
onClick={(e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
setOpenExchangeDialog(true);
}}
>
<SwapVert />
</IconButton>
<div className={classes.accountButtonText}>Exchange</div>
</div>
<div>
<IconButton
className={classes.accountButton}
aria-label="Details"
onClick={(e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
setOpenDetailsDialog(true);
}}
>
<InfoOutlinedIcon />
</IconButton>
<div className={classes.accountButtonText}>Details</div>
</div>
</ThemeProvider>
</div>
<hr style={{ width: 480, marginTop: 24, color: '#fcfcfc' }} />
<Transactions
account={data}
cardNumber={hasCard ? cardNumber : undefined}
currencyIcon={currencyIcon}
/>
</div>
);
} else {
return (
<div
style={{
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
}}
>
<Loading />
</div>
);
}
}; | the_stack |
import { CSSProperties } from "react";
import { CSSTransitionProps, CSSTransitionDelay } from "./csstransition";
import { resolveTransit } from "./transit";
export interface TransitionState {
id?: StateID;
style?: CSSProperties;
className?: string;
inTransition?: boolean;
}
export enum StateID {
EntryPoint,
DefaultNew,
ActiveNew,
AppearNew,
Default,
Active,
AppearInit,
AppearPrepare,
AppearTriggered,
AppearStarted,
EnterInit,
EnterPrepare,
EnterTriggered,
EnterStarted,
LeaveInit,
LeavePrepare,
LeaveTriggered,
LeaveStarted,
}
export const StateIDList = [
StateID.ActiveNew, StateID.DefaultNew, StateID.AppearNew,
StateID.Active, StateID.Default,
StateID.AppearInit, StateID.AppearTriggered, StateID.AppearStarted,
StateID.EnterInit, StateID.EnterTriggered, StateID.EnterStarted,
StateID.LeaveInit, StateID.LeaveTriggered, StateID.LeaveStarted,
StateID.AppearPrepare, StateID.EnterPrepare, StateID.LeavePrepare,
];
export enum ActionID {
New,
Mount,
TransitionInit,
TransitionPrepare,
TransitionTrigger,
TransitionStart,
TransitionComplete,
Timeout,
}
export type ActionPropKeys =
"active"
| "transitionAppear"
| "transitionDelay"
| "defaultStyle"
| "activeStyle"
| "appearStyle"
| "enterStyle"
| "leaveStyle"
| "appearInitStyle"
| "enterInitStyle"
| "leaveInitStyle"
| "defaultClassName"
| "activeClassName"
| "appearClassName"
| "enterClassName"
| "leaveClassName"
| "appearInitClassName"
| "enterInitClassName"
| "leaveInitClassName";
export const actionPropKeys: ActionPropKeys[] = [
"active",
"transitionAppear",
"transitionDelay",
"defaultStyle",
"activeStyle",
"appearStyle",
"enterStyle",
"leaveStyle",
"appearInitStyle",
"enterInitStyle",
"leaveInitStyle",
"defaultClassName",
"activeClassName",
"appearClassName",
"enterClassName",
"leaveClassName",
"appearInitClassName",
"enterInitClassName",
"leaveInitClassName",
];
export type ActionProps = {[P in ActionPropKeys]?: CSSTransitionProps[P]};
export type Action = {
kind: ActionID;
props: ActionProps;
};
export const transitionNames = ["enter", "leave", "appear"];
export function hasTransition(name: string, props: any): boolean {
const result = props[name + "Style"] !== undefined || props[name + "ClassName"] !== undefined;
return !result && name === "appear"
? hasTransition("enter", props)
: result;
}
export function getDelay(name: string, delay: CSSTransitionDelay): number {
if (!delay) { return 0; }
if (typeof delay === "number") {
return delay as number;
}
return (delay as any)[name] ? (delay as any)[name] : 0;
}
export type GetStateParams = { mode?: "init" | "prepare" };
export function getState(id: StateID, name: string, props: any, params: GetStateParams = {}): TransitionState {
if (name === "appear" && !props.appearStyle && !props.appearClassName) {
return getState(id, "enter", props, params);
}
let style: any;
let className: string;
let inTransition = false;
if (params.mode === "init" || params.mode === "prepare") {
style = props[name + "InitStyle"];
className = props[name + "InitClassName"];
if (style === undefined && className === undefined) {
if (name === "enter" || name === "appear") {
style = props.defaultStyle;
className = props.defaultClassName;
} else if (name === "leave") {
style = props.activeStyle;
className = props.activeClassName;
}
}
// Setting transition before starting one fixes issues on IE & Edge...
if (params.mode === "prepare" && style !== undefined) {
const tmp = resolveTransit(props[name + "Style"], getDelay(name, props.transitionDelay));
if (tmp.transition) {
style = { ...style, transition: tmp.transition };
}
}
} else {
style = props[name + "Style"];
className = props[name + "ClassName"];
if (["enter", "appear", "leave"].indexOf(name) >= 0) {
inTransition = true;
style = resolveTransit(style, getDelay(name, props.transitionDelay));
}
}
style = style || {};
className = className || "";
return {
id,
style,
className,
inTransition,
};
}
export function stateFunc(id: StateID, name: string, params: GetStateParams = {}) {
return (props: Action["props"]) => getState(id, name, props, params);
}
export const activeNewState = stateFunc(StateID.ActiveNew, "active");
export const defaultNewState = stateFunc(StateID.DefaultNew, "default");
export const appearNewState = stateFunc(StateID.AppearNew, "appear", { mode: "init" });
export const activeState = stateFunc(StateID.Active, "active");
export const defaultState = stateFunc(StateID.Default, "default");
export const appearInitState = stateFunc(StateID.AppearInit, "appear", { mode: "init" });
export const enterInitState = stateFunc(StateID.EnterInit, "enter", { mode: "init" });
export const leaveInitState = stateFunc(StateID.LeaveInit, "leave", { mode: "init" });
export const appearPrepareState = stateFunc(StateID.AppearPrepare, "appear", { mode: "prepare" });
export const enterPrepareState = stateFunc(StateID.EnterPrepare, "enter", { mode: "prepare" });
export const leavePrepareState = stateFunc(StateID.LeavePrepare, "leave", { mode: "prepare" });
export const appearTriggeredState = stateFunc(StateID.AppearTriggered, "appear");
export const enterTriggeredState = stateFunc(StateID.EnterTriggered, "enter");
export const leaveTriggeredState = stateFunc(StateID.LeaveTriggered, "leave");
export const appearStartedState = stateFunc(StateID.AppearStarted, "appear");
export const enterStartedState = stateFunc(StateID.EnterStarted, "enter");
export const leaveStartedState = stateFunc(StateID.LeaveStarted, "leave");
const invalidTransitionError = (stateID: StateID, actionID: ActionID) => {
return new Error(`invalid state transition from ${StateID[stateID]} with ${ActionID[actionID]}`);
};
export type Reducer = (stateID: StateID, action: Action) =>
{ state: TransitionState, pending?: ActionID, completed?: boolean };
export const reducer: Reducer = (stateID, action) => {
const props = action.props;
let nextState: TransitionState;
switch (action.kind) {
case ActionID.New:
if (stateID !== StateID.EntryPoint) { throw new Error("invalid entrypoint"); }
if (props.active) {
if (props.transitionAppear) { return { state: appearNewState(props) }; }
return { state: activeNewState(props) };
}
if (!props.transitionAppear && props.active) { return { state: activeNewState(props) }; }
return { state: defaultNewState(props) };
case ActionID.Mount:
switch (stateID) {
case StateID.AppearNew:
return reducer(stateID, { kind: ActionID.TransitionTrigger, props });
default:
return null;
}
case ActionID.TransitionInit:
switch (stateID) {
case StateID.DefaultNew:
case StateID.Default:
if (!hasTransition("enter", props)) {
return { state: activeState(props), completed: true };
}
nextState = enterInitState(props);
break;
case StateID.ActiveNew:
case StateID.Active:
if (!hasTransition("leave", props)) {
return { state: defaultState(props), completed: true };
}
nextState = leaveInitState(props);
break;
case StateID.AppearNew:
if (!hasTransition("appear", props)) {
return { state: activeState(props), completed: true };
}
nextState = appearInitState(props);
break;
default:
throw invalidTransitionError(stateID, action.kind);
};
return { state: nextState, pending: ActionID.TransitionPrepare };
case ActionID.TransitionPrepare:
switch (stateID) {
case StateID.EnterInit:
if (!props.active) { return { state: defaultState(props), completed: true }; }
nextState = enterPrepareState(props);
break;
case StateID.LeaveInit:
if (props.active) { return { state: activeState(props), completed: true }; }
nextState = leavePrepareState(props);
break;
case StateID.AppearInit:
if (!props.active) { return { state: defaultState(props), completed: true }; }
nextState = appearPrepareState(props);
break;
default:
throw invalidTransitionError(stateID, action.kind);
};
return { state: nextState, pending: ActionID.TransitionTrigger };
case ActionID.TransitionStart:
switch (stateID) {
case StateID.EnterTriggered:
return { state: enterStartedState(props) };
case StateID.LeaveTriggered:
return { state: leaveStartedState(props) };
case StateID.AppearTriggered:
return { state: appearStartedState(props) };
default:
// We don't error out, because the workaround for transitionstart
// could happen after transitionend.
return null;
}
case ActionID.TransitionComplete:
switch (stateID) {
case StateID.AppearTriggered:
case StateID.AppearStarted:
case StateID.EnterTriggered:
case StateID.EnterStarted:
return { state: activeState(props), completed: true };
case StateID.LeaveTriggered:
case StateID.LeaveStarted:
return { state: defaultState(props), completed: true };
default:
throw invalidTransitionError(stateID, action.kind);
}
case ActionID.TransitionTrigger:
switch (stateID) {
case StateID.ActiveNew:
case StateID.Active:
case StateID.DefaultNew:
case StateID.Default:
case StateID.AppearNew:
return reducer(stateID, { kind: ActionID.TransitionInit, props });
case StateID.EnterInit:
return { state: defaultState(props), completed: true };
case StateID.LeaveInit:
return { state: activeState(props), completed: true };
case StateID.AppearInit:
return { state: defaultState(props), completed: true };
case StateID.EnterPrepare:
if (props.active) { return { state: enterTriggeredState(props) }; }
return { state: defaultState(props), completed: true };
case StateID.LeavePrepare:
if (!props.active) { return { state: leaveTriggeredState(props) }; }
return { state: activeState(props), completed: true };
case StateID.AppearPrepare:
if (props.active) { return { state: appearTriggeredState(props) }; }
return { state: defaultState(props), completed: true };
case StateID.EnterTriggered:
return { state: defaultState(props), completed: true };
case StateID.LeaveTriggered:
return { state: activeState(props), completed: true };
case StateID.AppearTriggered:
return { state: defaultState(props), completed: true };
case StateID.AppearStarted:
case StateID.EnterStarted:
return { state: leaveStartedState(props) };
case StateID.LeaveStarted:
return { state: enterStartedState(props) };
default:
throw invalidTransitionError(stateID, action.kind);
}
case ActionID.Timeout:
switch (stateID) {
case StateID.AppearTriggered:
case StateID.AppearStarted:
case StateID.EnterTriggered:
case StateID.EnterStarted:
return { state: activeState(props), completed: true };
case StateID.LeaveTriggered:
case StateID.LeaveStarted:
return { state: defaultState(props), completed: true };
default:
throw invalidTransitionError(stateID, action.kind);
}
default:
}
throw new Error("unexpected error");
}; | the_stack |
import { isEmpty, get, set, cloneDeep, uniqBy } from 'lodash';
import {
Edge,
FieldAndAggregation,
GraphData,
GroupEdgeFields,
GroupEdges,
GroupEdgeCandidates,
NumericAggregations,
StringAggregations,
Field,
} from '../types';
import {
average,
count,
max,
min,
sum,
} from '../../../utils/edge-aggregations/numeric-aggregates';
import {
first,
last,
mostFrequent,
} from '../../../utils/edge-aggregations/string-aggregates';
type AggregationFields = Record<string, number | string>;
export type GroupEdgeReturns = {
graphData: GraphData;
groupEdgeIds;
};
const combineEdgeFields = (myArr: Field[], prop: string): Field[] => {
const seen = new Set();
const filteredArr = myArr.filter((el) => {
const duplicate = seen.has(el[prop]);
seen.add(el[prop]);
return !duplicate;
});
return filteredArr;
};
/**
* Obtain the duplicate edge connectivity in graph
*
* @param {GraphData} data - graph data
* @param {string} type - group by type
*/
export const duplicateDictionary = (
data: GraphData,
type = '',
): GroupEdgeCandidates => {
const generateIdentifier = (edge: Edge, type: string): string => {
const { source, target } = edge;
if (type === 'all') {
return `${source}->${target}`;
}
const edgeValue = get(edge, type, '');
if (edgeValue !== '') {
return `${source}->${target}@${edgeValue}`;
}
return `${source}->${target}`;
};
const dictionary = {};
data.edges.reduce((acc: Map<string, Edge>, edge: Edge) => {
const identifier: string = generateIdentifier(edge, type);
if (acc.has(identifier)) {
const matchEdge = acc.get(identifier);
const groupEdgeCandidate = dictionary[identifier] ?? [matchEdge];
groupEdgeCandidate.push(edge);
dictionary[identifier] = groupEdgeCandidate;
}
return acc.set(identifier, edge);
}, new Map());
return dictionary;
};
/**
* Return edges id as array value from group edge candidates.
*
* @param groupEdgeCandidates
* @return {string[]}
*/
const obtainGroupEdgeIds = (
groupEdgeCandidates: GroupEdgeCandidates,
): string[] => {
return Object.values(groupEdgeCandidates).reduce(
(acc: string[], groupEdgeCandidate: Edge[]) => {
const edgeIds: string[] = groupEdgeCandidate.map((edge) => edge.id);
return [...acc, ...edgeIds];
},
[],
);
};
/**
* Perform aggregation on group edges with given fields.
*
* @param {Edge[]} edgeCandidates - edge with duplicate connectivity for grouping
* @param {GroupEdgeFields} fields - property with aggregation methods
* @return {AggregationFields}
*/
const performAggregation = (
edgeCandidates: Edge[],
fields: GroupEdgeFields,
): AggregationFields => {
const aggregations: AggregationFields = {};
return Object.values(fields).reduce(
(acc: AggregationFields, aggregationList: FieldAndAggregation) => {
const { field, aggregation } = aggregationList;
if (aggregation.includes('min' as never)) {
const smallestValue: number | string = min(edgeCandidates, field);
if (smallestValue !== 'no-values') {
set(acc, `min ${field}`, smallestValue);
}
}
if (aggregation.includes('max' as never)) {
const largestValue: number | string = max(edgeCandidates, field);
if (largestValue !== 'no-values') {
set(acc, `max ${field}`, largestValue);
}
}
if (aggregation.includes('sum' as never)) {
const sumValue: number | string = sum(edgeCandidates, field);
if (sumValue !== 'no-values') {
set(acc, `sum ${field}`, sumValue);
}
}
if (aggregation.includes('count' as never)) {
const countValue: number = count(edgeCandidates, field);
set(acc, `count ${field}`, countValue);
}
if (aggregation.includes('average' as never)) {
let averageValue: number | string = average(edgeCandidates, field);
if (averageValue !== 'no-values') {
averageValue = Number(averageValue).toPrecision(5);
set(acc, `average ${field}`, parseFloat(averageValue));
}
}
if (aggregation.includes('first' as never)) {
const firstValue: string = first(edgeCandidates, field);
if (firstValue !== 'no-values') {
set(acc, `first ${field}`, firstValue);
}
}
if (aggregation.includes('last' as never)) {
const lastValue: string = last(edgeCandidates, field);
if (lastValue !== 'no-values') {
set(acc, `last ${field}`, lastValue);
}
}
if (aggregation.includes('most_frequent' as never)) {
const mostFrequentValue: string = mostFrequent(edgeCandidates, field);
if (mostFrequentValue !== 'no-values') {
set(acc, `most_frequent ${field}`, mostFrequentValue);
}
}
return acc;
},
aggregations,
);
};
/**
* Aggregate specific edge with given aggregate's field
*
* @param groupEdgesCandidates - edges to perform aggregations
* @param type - display the aggregated fields without the need to perform aggregations
* @param fields - aggregation methods on specific fields
* @return {Edge[]} - grouped edges
*/
const aggregateGroupEdges = (
groupEdgesCandidates: GroupEdgeCandidates,
type: string,
fields: GroupEdgeFields = {},
): Edge[] => {
return Object.entries(groupEdgesCandidates).map((value) => {
const [, groupEdgeCandidate] = value;
const [firstEdge] = groupEdgeCandidate as Edge[];
const { id, source, target } = firstEdge as Edge;
const aggregationFields: AggregationFields = performAggregation(
groupEdgeCandidate,
fields,
);
const groupByFields = get(firstEdge, type, '');
const properties = {
id: `group-${id}`,
source,
target,
};
if (type !== 'all') {
properties[type] = groupByFields;
}
return {
...properties,
...aggregationFields,
};
});
};
/**
* 1. Remove existing edge from current graph data with duplicate connectivity (same source and target)
* 2. Append grouped edge into the graph data
*
* @param data - existing graph data
* @param edgeIdsForRemoval - edge id with duplicate connectivity required to be removed from graph
* @param groupedEdges - grouped edge ready to append into current graph
* @param fields - group edge's field configuration.
* @return {GraphData} - graph with grouped edges
*/
const produceGraphWithGroupEdges = (
data: GraphData,
edgeIdsForRemoval: string[],
groupedEdges: Edge[],
fields: GroupEdgeFields = {},
): GraphData => {
const graphWithRemovedEdges = data.edges
.filter((edge: Edge) => !edgeIdsForRemoval.includes(edge.id))
.map((edge: Edge) => {
const aggregationFields: AggregationFields = performAggregation(
[edge],
fields,
);
return {
...edge,
...aggregationFields,
};
});
const graphWithGroupedEdges: Edge[] = [
...graphWithRemovedEdges,
...groupedEdges,
];
const modData = { ...data };
Object.assign(modData, { edges: graphWithGroupedEdges });
return modData;
};
/**
* 1. Remove grouped edge from graph flatten.
* 2. Append edges with duplicate connectivity into the graph
*
* @param graphData - original graph list without grouped edges
* @param graphFlatten - current graph data with combination of graph list
* @param edgeIdsForRemoval - group edges' id for removal
* @return {GraphData} - graph data without group edges
*/
const produceGraphWithoutGroupEdges = (
graphData: GraphData,
graphFlatten: GraphData,
edgeIdsForRemoval: string[],
): GraphData => {
const withoutGroupedEdges = graphFlatten.edges.filter(
(edge: Edge) => !edgeIdsForRemoval.includes(edge.id),
);
const graphWithOriginalEdges = uniqBy(
[...withoutGroupedEdges, ...graphData.edges],
(edge: Edge) => edge.id,
);
const modData = { ...graphFlatten };
Object.assign(modData, { edges: graphWithOriginalEdges });
return modData;
};
/**
* Perform group edges during data importation, used in:
* 1. Import Sample Data
* 2. Import Local File
*
* Shall Perform Aggregation based on
* 1. configuration retrieve from the saved files
* 2. user preferences (toggle) during import data
*
* @param {GraphData} data - graph data
* @param {GroupEdges} groupEdgeConfig [groupEdgeConfig={}] - group edge configuration found in every graph list
* @return {GroupEdgeReturns} - graph data with grouped edges
*/
export const groupEdgesForImportation = (
data: GraphData,
groupEdgeConfig: GroupEdges = {},
): GroupEdgeReturns => {
const { type, toggle, fields } = groupEdgeConfig;
if (toggle === false) return { graphData: data, groupEdgeIds: [] };
const groupEdgesCandidates = duplicateDictionary(data, type);
if (isEmpty(groupEdgesCandidates))
return { graphData: data, groupEdgeIds: [] };
const edgeIdsForRemoval: string[] = obtainGroupEdgeIds(groupEdgesCandidates);
const groupedEdges: Edge[] = aggregateGroupEdges(
groupEdgesCandidates,
type,
fields,
);
const graphWithGroupEdges: GraphData = produceGraphWithGroupEdges(
data,
edgeIdsForRemoval,
groupedEdges,
fields,
);
const groupEdgeIds: string[] = groupedEdges.map((edge: Edge) => edge.id);
const modData = cloneDeep(graphWithGroupEdges);
modData.metadata.groupEdges.ids = groupEdgeIds;
if (isEmpty(fields) === false) {
const edgeAggregateFields: Field[] = aggregateMetadataFields(
graphWithGroupEdges,
fields,
);
// combine edge fields with aggregate fields
const combinedEdgeField: Field[] = combineEdgeFields(
[...data.metadata.fields.edges, ...edgeAggregateFields],
'name',
);
Object.assign(modData.metadata.fields.edges, combinedEdgeField);
return { graphData: modData, groupEdgeIds };
}
return { graphData: modData, groupEdgeIds };
};
/**
* Perform group edge based on user preferences in graph list, used in:
* 1. Toggle in Graph List
* 2. Aggregation fields
*
* Shall perform aggregation based on:
* 1. toggle value
* 2. aggregation fields input in data list accordion.
*
* This function supports:
* 1. Convert group edge graph to original graph
* 2. Convert original graph to group edge graph
*
* @param graphData - selected graph list to perform aggregation
* @param graphFlatten - existing graph with combination of graph list
* @param groupEdgesConfig - list of aggregations to be perform on graph list
* @param groupEdges - list of group edges to be removed
* @return {GraphData} - graph combined with grouped edges.
*/
export const groupEdgesWithConfiguration = (
graphData: GraphData,
graphFlatten: GraphData,
groupEdgesConfig: GroupEdges,
): GroupEdgeReturns => {
const groupEdgesWithConfig = (
graphData: GraphData,
graphFlatten: GraphData,
type: string,
fields: GroupEdgeFields,
groupedEdgeIds: string[],
) => {
// clear previous group edges before perform another grouping
const ungroupedGraph: GroupEdgeReturns = revertGroupEdge(
graphData,
graphFlatten,
groupedEdgeIds,
);
// create dictionary with the duplicates source and target edges
const groupEdgesCandidates: GroupEdgeCandidates = duplicateDictionary(
graphData,
type,
);
if (isEmpty(groupEdgesCandidates)) return ungroupedGraph;
const { graphData: ungroupGraphData } = ungroupedGraph;
// obtain edge id for removal from graph flatten.
const edgeIdsForRemoval: string[] =
obtainGroupEdgeIds(groupEdgesCandidates);
// produce grouped edge with aggregations fields.
const groupedEdges: Edge[] = aggregateGroupEdges(
groupEdgesCandidates,
type,
fields,
);
// remove duplicate edges and combine the grouped edges with current graph.
const graphWithGroupEdges: GraphData = produceGraphWithGroupEdges(
ungroupGraphData,
edgeIdsForRemoval,
groupedEdges,
fields,
);
// return grouped edge id to be store in redux states, useful for ungrouped.
const groupEdgeIds: string[] = groupedEdges.map((edge: Edge) => edge.id);
return { graphData: graphWithGroupEdges, groupEdgeIds };
};
const revertGroupEdge = (
graphData: GraphData,
graphFlatten: GraphData,
groupedEdgesId: string[],
) => {
if (groupedEdgesId.length === 0) {
return { graphData: graphFlatten, groupEdgeIds: [] };
}
const combinedGraphData: GraphData = produceGraphWithoutGroupEdges(
graphData,
graphFlatten,
groupedEdgesId,
);
return { graphData: combinedGraphData, groupEdgeIds: [] };
};
const { toggle, type, fields, ids = [] } = groupEdgesConfig;
if (toggle) {
return groupEdgesWithConfig(graphData, graphFlatten, type, fields, ids);
}
return revertGroupEdge(graphData, graphFlatten, ids);
};
/**
* Combine graph metadata edge fields with aggregated fields.
* 1. Variable Inspector
* 2. Edge Selection
*
* @param graphData
* @param groupEdgeField
* @return {Field[]}
*/
export const aggregateMetadataFields = (
graphData: GraphData,
groupEdgeField: GroupEdgeFields = {},
): Field[] => {
const { edges: edgeFields } = graphData.metadata.fields;
if (isEmpty(groupEdgeField)) return edgeFields;
// compute edge aggregate fields ready to append into graph's edge field
const edgeAggregateFields: Field[] = Object.values(groupEdgeField).reduce(
(accumulateField: Field[], fieldsWithAggr: FieldAndAggregation) => {
const { field, aggregation } = fieldsWithAggr;
const edgeAggregateField: Field[] = (
aggregation as (NumericAggregations | StringAggregations)[]
).map((aggr) => {
const aggregateField = `${aggr} ${field}`;
const oriEdgeField: Field = edgeFields.find(
(edgeField: Field) => edgeField.name === field,
);
const { format, type, analyzerType } = oriEdgeField;
return {
name: aggregateField,
format,
type,
analyzerType,
};
});
return [...accumulateField, ...edgeAggregateField];
},
[],
);
return edgeAggregateFields;
}; | the_stack |
import { VNode, VNodeKind, PropsArg } from '../createElement';
import { renderDOM } from '../renderDOM';
import { diffProps } from './props';
import { b } from '../createElement';
import { renderType, machineRegistry } from '../machineRegistry';
export function diff(
oldVNode: VNode,
newVNode: VNode | undefined | null,
parentDom: HTMLElement | null,
nodeDepth: number,
isSvg: boolean = false
): void {
/** for machines not targeted, isLeaf, memo, static elements!
* don't need to pass on dom (test it), same vnode. == for null/undefined
*/
if (oldVNode == newVNode) return;
/** there is no node in the new tree corresponding
* to the old tree, so remove node */
if (!newVNode) {
// dom node "bubbles up" to closest non-element VNode, so every
// node will have dom
oldVNode.d!.remove();
safelyRemoveVNode(oldVNode);
return;
}
// you can't exit the svg namespace, so the logic is simple.
// once you've reached an svg node, it and all of its descendants
// must be created with createElementNS()
isSvg = newVNode.t === 'svg' || isSvg;
newVNode.h = nodeDepth;
switch (oldVNode.x) {
case VNodeKind.E:
switch (newVNode.x) {
case VNodeKind.E:
if (oldVNode.t !== newVNode.t) {
/** different tags can't represent the same node */
return replace(oldVNode, newVNode, parentDom, nodeDepth, isSvg);
} else {
/** most computation is done here. Both VNodes are ELEMENT_NODES and
* have the same tag, so we must diff props (attributes) and children */
diffProps(oldVNode.a, newVNode.a, oldVNode.d as HTMLElement);
/** only call diffKeyedChildren if the first nodes of both lists are keyed.
* users should be aware of this behavior, and be sure to either key all
* children or no children. this shortcut saves many iterations over children lists.
*
* if either of the arrays have 0 elements, only use diffChildren (faster anyways)
*
* most of the time, call diffChildren */
const firstOldChild = oldVNode.c[0],
firstNewChild = newVNode.c[0];
if (
firstOldChild &&
firstOldChild.k != null &&
firstNewChild &&
firstNewChild.k != null
) {
keyedDiffChildren(
oldVNode.c,
newVNode.c,
// asserting the type bc it'll only be null after
// createElement and before renderDOM. can't be null at diff
oldVNode.d as HTMLElement,
nodeDepth,
isSvg
);
} else {
diffChildren(
oldVNode.c,
newVNode.c,
oldVNode.d as HTMLElement,
nodeDepth,
isSvg
);
}
// pass on the dom node since they are the same element
newVNode.d = oldVNode.d;
return;
}
default:
return replace(oldVNode, newVNode, parentDom, nodeDepth, isSvg);
}
case VNodeKind.T:
switch (newVNode.x) {
case VNodeKind.T:
if (oldVNode.a.n === newVNode.a.n) newVNode.d = oldVNode.d;
else {
oldVNode.d && (oldVNode.d.nodeValue = newVNode.a.n);
newVNode.d = oldVNode.d;
}
return;
default:
return replace(oldVNode, newVNode, parentDom, nodeDepth, isSvg);
}
case VNodeKind.M:
switch (newVNode.x) {
case VNodeKind.M:
oldVNode.i !== newVNode.i && unmountMachine(oldVNode.i);
// "children" of a machineVNode is one child
diff(oldVNode.c, newVNode.c, parentDom, nodeDepth + 1, isSvg);
newVNode.d = newVNode.c.d;
return;
default:
return replace(oldVNode, newVNode, parentDom, nodeDepth, isSvg);
}
/**
* lazy/memo nodes can't be roots. this will make it easier to create dynamic import fn
* without wrapping in a div. just store parent dom on the lazy node. when fallback timeout
* or import comes in, replace the placeholder text node using parent.replaceChild(import/fallback, placeholder)
*/
case VNodeKind.O:
switch (newVNode.x) {
case VNodeKind.O:
/**
* all the reasons that a memo component should rerender:
* - the functions are different.
* -
*
* note, the props object itself will most likely be new on each render, so
* that's not a useful check. nvm,, null === null is a good opt!
*/
if (renderType.t === 'r') {
// it already rendered on route change
diff(oldVNode.c, newVNode.c, parentDom, nodeDepth + 1, isSvg);
newVNode.d = newVNode.c.d;
} else if (
oldVNode.t !== newVNode.t ||
shouldRender(oldVNode.a, newVNode.a)
) {
// rerender (create new vnode child)
// memo ignores children. it wouldn't work with children anyways
const vNode = b(newVNode.t, newVNode.a);
newVNode.c = vNode;
// diff
diff(oldVNode.c, newVNode.c, parentDom, nodeDepth + 1, isSvg);
newVNode.d = newVNode.c.d;
} else {
// don't render. pass on the child.
newVNode.c = oldVNode.c;
newVNode.d = oldVNode.d;
}
return;
default:
return replace(oldVNode, newVNode, parentDom, nodeDepth, isSvg);
}
}
}
function replace(
oldVNode: VNode,
newVNode: VNode,
parentDom: HTMLElement | null,
nodeDepth: number,
isSvg: boolean
): void {
/**
* what about replacing an element/text node with a machine?
*
* this works because renderDOM will return the dom node
* of the child of the machine node
*
* what about replacing a machine with an element/text node?
*
* this works because when the oldVNode is a machine node,
* replace is called with the child of oldVNode
*/
const $new = renderDOM(newVNode, nodeDepth, isSvg);
if (parentDom) {
// this might be an unneccesary test, check it. just make sure every node has to have a valid .d at diff time
parentDom.replaceChild($new, oldVNode.d as HTMLElement);
} else {
/**
* this branch is necessary for machine node diffing,
* as the first child doesn't have a reference to the parent
*/
const $d = oldVNode.d;
if ($d) {
const $parent = $d.parentElement;
$parent && $parent.replaceChild($new, $d);
}
}
safelyRemoveVNode(oldVNode);
}
/**
* if this returns true, rerender the memo component
*/
export function shouldRender<Props extends PropsArg = any>(
oldProps: Props | null | undefined,
newProps: Props | null | undefined
): boolean {
// for when they they are both null or undefined, no point in rerendering. it's basically a static vnode/element
if (oldProps == newProps) return false;
if (newProps && oldProps) {
for (let i in oldProps) if (!(i in newProps)) return true;
for (let i in newProps) if (oldProps[i] !== newProps[i]) return true;
} else {
// one of new/old props don't exist, but the other do. have to rerender
// this won't happen with JSX
return true;
}
// this means both newProps and oldProps exist, but they are shallow equal
return false;
}
/** traverses the VNode to be removed in order to
* remove any machine instances that may be a descendant
* of this node */
function safelyRemoveVNode(node: VNode) {
switch (node.x) {
case VNodeKind.M:
// we found a machine to unmount
unmountMachine(node.i);
// keep looking for machine desc.
safelyRemoveVNode(node.c);
return;
case VNodeKind.O:
safelyRemoveVNode(node.c);
return;
case VNodeKind.E: {
// keep looking for machine desc.
let i = node.c.length;
while (i--) safelyRemoveVNode(node.c[i]);
return;
}
default:
// do nothing, text/undefined can't have a machine desc.
return;
}
}
function unmountMachine(idToDelete: string) {
const mInst = machineRegistry.get(idToDelete);
if (mInst) {
mInst.s.unmount && mInst.s.unmount(mInst.x, mInst.st);
machineRegistry.delete(idToDelete);
}
}
const TypedArray = Int32Array;
/**
*
* DIFF CHILDREN (KEYED + UNKEYED)
*
*/
/**
* algorithm for keyed children. Call this when the first
* index of oldVChildren and newVChildren are both keyed.
*
* Inspired by the algorithm used in Ivi, but modified to account
* for different patching process.
*
* References:
* https://github.com/localvoid/ivi/blob/master/packages/ivi/src/vdom/reconciler.ts#L581
* https://github.com/yelouafi/petit-dom/blob/master/src/vdom.js#L240
* https://neil.fraser.name/writing/diff/
*/
function keyedDiffChildren(
oldVChildren: VNode[],
newVChildren: VNode[],
parentDom: HTMLElement,
nodeDepth: number,
isSvg: boolean
): undefined {
let oldStart = 0,
newStart = 0,
oldLen = oldVChildren.length,
oldEnd = oldLen - 1,
newEnd = newVChildren.length - 1,
oldEndNode: VNode,
newEndNode: VNode,
oldStartNode: VNode,
newStartNode: VNode,
$node: HTMLElement | Text | ChildNode | undefined,
$nextNode: HTMLElement | Text | ChildNode | null | undefined = undefined,
oldVNode: VNode,
newVNode: VNode,
indexInOldChildren: number,
indexInNewChildren: number | undefined,
pos = -1,
newChildrenLeft: number;
/**
* Common prefix and suffix optimization.
* Iterate over old children and new children simultaneously from both sides,
* patching nodes in place when keys are equal.
*/
outer: while (true) {
// check common suffix
oldEndNode = oldVChildren[oldEnd];
newEndNode = newVChildren[newEnd];
while (oldEndNode.k === newEndNode.k) {
// this part is important: if the last node not part of the
// common suffix is new, it needs a reference to the leftmost
// member of the common suffix so it can be appended before it
$nextNode = oldEndNode.d;
diff(oldEndNode, newEndNode, parentDom, nodeDepth + 1, isSvg);
oldEnd--;
newEnd--;
oldEndNode = oldVChildren[oldEnd];
newEndNode = newVChildren[newEnd];
if (oldStart > oldEnd || newStart > newEnd) break outer;
}
// exhausted common suffix
// check common prefix
oldStartNode = oldVChildren[oldStart];
newStartNode = newVChildren[newStart];
while (oldStartNode.k === newStartNode.k) {
diff(oldStartNode, newStartNode, parentDom, nodeDepth + 1, isSvg);
oldStart++;
newStart++;
oldStartNode = oldVChildren[oldStart];
newStartNode = newVChildren[newStart];
if (oldStart > oldEnd || newStart > newEnd) break outer;
}
// exhausted common prefix
break outer;
}
/** if either the old children list or new children list
* is empty after common prefix/suffix diffing, then either
* delete the remaining nodes (if new list is empty), or
* add the remaining nodes (if old list is empty)
*/
if (oldStart > oldEnd) {
/** if the start pointer is greater than the oldEnd pointer,
* then all of the nodes in the old children list have been patched.
* Iterate through the new list and mount the leftovers in between
* the nodes at oldStart and oldEnd.
*
* RenderDOM all nodes from newStart to newEnd, insert them before node
* at oldStart
*/
while (newStart <= newEnd) {
$node = renderDOM(newVChildren[newStart], nodeDepth + 1, isSvg);
oldStart >= oldLen
? parentDom.appendChild($node)
: parentDom.insertBefore($node, oldVChildren[oldStart].d);
newStart++;
}
return;
}
if (newStart > newEnd) {
/**
* if the start pointer is greater than the newEnd pointer,
* then all of the nodes in the new children list have been patched.
* Iterate through the old list and delete the leftovers.
*
* Delete all nodes from oldStart to oldEnd
*/
while (oldStart <= oldEnd) {
oldVNode = oldVChildren[oldStart];
// dom node "bubbles up" to closest non-element VNode, so every
// node will have dom
oldVNode.d!.remove();
// we can assert that dom exists because it is only null before "renderDOM",
// which surely would have been run before diffing
safelyRemoveVNode(oldVChildren[oldStart]);
oldStart++;
}
return;
}
newChildrenLeft = newEnd - newStart + 1;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const keyIndex = new Map<any, number>(),
sources = new TypedArray(newChildrenLeft);
/** Iterate over remaining newChildren (left to right),
* storing each child's pos/index (in the new array) by its key
* in the 'keyIndex' map. At the same time, fill the 'sources' array
* with '-1', meaning new node that needs to be mounted. If the node
* existed in the oldChildren list, '-1' will be replaced with its position
* in the oldChildren list!
*/
for (let i = 0; i < newChildrenLeft; i++) {
// newStart is offset between 'sources' and actual new children array
indexInNewChildren = i + newStart;
sources[i] = -1;
keyIndex.set(newVChildren[indexInNewChildren].k, indexInNewChildren);
}
/** -2 for patch in place, -1 for mount, any other value for move */
let actionAtIndex: number;
/**
* Check if old children (that weren't part of common
* prefix/suffix) are in the new list (using key index)
*/
for (let i = oldStart; i <= oldEnd; i++) {
oldVNode = oldVChildren[i];
indexInNewChildren = keyIndex.get(oldVNode.k);
if (typeof indexInNewChildren !== 'undefined') {
/** 99999999 indicates that at least one node has moved,
* so we should mark nodes that are part of the longest increasing
* subsequence to minimize DOM moves.
*
* Set pos to 99999999 when the new position of a node is less
* than the new position of the node that used to precede it */
pos = pos < indexInNewChildren ? indexInNewChildren : movedNum;
sources[indexInNewChildren - newStart] = i;
} else {
// dom node "bubbles up" to closest non-element VNode, so every
// node will have dom
oldVNode.d!.remove();
// we can assert that dom exists because it is only null before "renderDOM",
// which surely would have been run before diffing
safelyRemoveVNode(oldVNode);
}
}
/**
* Iterate over the remaining newChildren (right to left),
* and perform the action corresponding to the value
* in the array at index
*
* $nextNode should be the last node (from the right)
* in the common suffix. If there is no $nextNode yet, this is
* the next last child!
*/
let sourcesActions: Int32Array;
// slightly different logic if nodes have moved
if (pos === movedNum) {
// at least one node has moved
// eslint-disable-next-line @typescript-eslint/no-use-before-define
sourcesActions = markLIS(sources);
while (newChildrenLeft > 0) {
newChildrenLeft--;
newEnd = newChildrenLeft + newStart;
newVNode = newVChildren[newEnd];
/** will have to use the LIS marked array to find
* actionAtIndex to preserve indexInOldChildren
* (using OG sources array)! */
actionAtIndex = sourcesActions[newChildrenLeft];
switch (actionAtIndex) {
case -2:
// existing node, but not moved. that's why you should
// check sources (sourcesActions obv has -2 here)
indexInOldChildren = sources[newChildrenLeft];
oldVNode = oldVChildren[indexInOldChildren];
diff(oldVNode, newVNode, parentDom, nodeDepth + 1, isSvg);
if (newVNode.d) $nextNode = newVNode.d;
continue;
case -1:
// new node. this works for machine nodes as
// well because renderDOM returns child
$node = renderDOM(newVNode, nodeDepth + 1, isSvg);
$nextNode
? parentDom.insertBefore($node, $nextNode)
: parentDom.appendChild($node);
$nextNode = $node;
continue;
default:
// diff, patch, then move node before $nextNode
indexInOldChildren = sources[newChildrenLeft];
oldVNode = oldVChildren[indexInOldChildren];
diff(oldVNode, newVNode, parentDom, nodeDepth + 1, isSvg);
if (newVNode.d) {
$nextNode
? parentDom.insertBefore(newVNode.d, $nextNode)
: parentDom.appendChild(newVNode.d);
$nextNode = newVNode.d;
}
continue;
}
}
} else {
while (newChildrenLeft > 0) {
newChildrenLeft--;
newEnd = newChildrenLeft + newStart;
newVNode = newVChildren[newEnd];
/** will have to use the LIS marked array to find
* actionAtIndex to preserve indexInOldChildren
* (using OG sources array)! */
actionAtIndex = sources[newChildrenLeft];
switch (actionAtIndex) {
case -1:
// new node. this works for machine nodes as
// well because renderDOM returns child
$node = renderDOM(newVNode, nodeDepth + 1, isSvg);
$nextNode
? parentDom.insertBefore($node, $nextNode)
: parentDom.appendChild($node);
$nextNode = $node;
continue;
default:
/** diff, patch. no need to move in this branch, but
* still set as $nextNode for the sake of new nodes */
indexInOldChildren = sources[newChildrenLeft];
oldVNode = oldVChildren[indexInOldChildren];
diff(oldVNode, newVNode, parentDom, nodeDepth + 1, isSvg);
if (newVNode.d) $nextNode = newVNode.d;
continue;
}
}
}
return;
}
/**
* Returns an array that is a copy of the input array, but values that are a part
* of the longest increasing subsequence are replaced with -2
*
* References:
* https://github.com/localvoid/ivi/blob/master/packages/ivi/src/vdom/reconciler.ts#L935
* https://en.wikipedia.org/wiki/Longest_increasing_subsequence
*
* Differs from the algorithm in ivi in that it returns a new array. I do not
* touch the original sources array because I need the
* index i of an existing node for patches to childNode[i]), even if the
* node is part of the longest increasing subsequence.
*
*
* Doesn't work correctly if source array values are -1 or -2,
* but that's irrelevant here because the values represent indices (min 0)
*
* TypedArray is an alias for Int32Array
*/
export function markLIS(sources: Int32Array): Int32Array {
let n = sources.length,
/** The value at each index i is the index (in the sources array)
* of the immediate predecessor in the longest increasing subsequence that ends with sources[i].
* i.e. sources[predecessors[i]] directly precedes sources[i] in an increasing subsequence */
predecessors = new TypedArray(n),
/** Length is n + 1 bc we skip index 0.
* The value at each index i is the index in sources array of the
* (smallest) last member of an increasing subsequence of length i
*/
indices = new TypedArray(n + 1),
length = 0,
lo: number,
hi: number,
mid: number,
newLength: number,
i: number;
for (i = 0; i < n; i++) {
const num = sources[i];
/** Ignore -1 values, meaning new node. If you
* forget this step, and -1 happens to be part of the LIS,
* then you turn -1 into -2. The reconciler will look
* for a node (that might not exist in newVChildren)
* at this position in oldVChildren, as -2 is supposed to
* signal that the node hasn't moved
*/
if (num !== -1) {
lo = 1;
hi = length;
while (lo <= hi) {
// mid = Math.floor((lo + hi) / 2);
mid = ((lo + hi) / 2) | 0;
if (sources[indices[mid]] < num) lo = mid + 1;
else hi = mid - 1;
}
newLength = lo;
predecessors[i] = indices[newLength - 1];
indices[newLength] = i;
length = Math.max(length, newLength);
}
}
// backtracking to mark lis a copy of the sources array
let markedLIS = TypedArray.from(sources),
k = indices[length];
for (i = 0; i < length; i++) {
markedLIS[k] = -2;
k = predecessors[k];
}
return markedLIS;
}
/**
* Diffing "algorithm" for non-keyed children. Call this when the first
* index of oldVChildren and newVChildren are not both keyed.
*
* The indices of the children act as 'implicit keys.' Compare nodes
* in oldVChildren to nodes in newVChildren and diff/patch in place.
*
* This algorithm is slightly faster than the keyed diff, but it may lead
* to unexpected CSS behavior if you are reordering lists.
* More info: https://www.stefankrause.net/wp/?p=342
* If you know that what you are doing will not cause problems (pls read
* the link above), and you need max performance, you can omit keys from lists.
* */
function diffChildren(
oldVChildren: VNode[],
newVChildren: VNode[],
parentDom: HTMLElement,
nodeDepth: number,
isSvg: boolean
): void {
let i = 0,
len = oldVChildren.length,
newLen = newVChildren.length,
oldVChild: VNode,
newVChild: VNode;
/** This will automatically delete removed children, bc newVChildren[i] will be undefined */
for (; i < len; i++) {
oldVChild = oldVChildren[i];
newVChild = newVChildren[i];
// this will remove dom node if no newVChild
diff(oldVChild, newVChild, parentDom, nodeDepth + 1, isSvg);
}
/** This will only be executed if newVChildren is longer than oldVChildren */
for (; i < newLen; i++) {
newVChild = newVChildren[i];
parentDom.appendChild(renderDOM(newVChild, nodeDepth + 1, isSvg));
}
}
let movedNum = 99999999; | the_stack |
import * as vscode from "vscode";
import * as Utils from "./Utils";
import { Position, Range } from "./VimStyle";
enum EditorActionType {
Insert,
Replace,
Delete,
SetPosition,
}
class EditorAction {
public Type: EditorActionType;
public Position: IPosition;
public Range: IRange;
public Text: string;
}
export interface IVSCodeEditorOptions {
showMode: boolean;
changeCursorStyle: boolean;
defaultMode: string;
imapEsc: string;
}
export class VSCodeEditor implements IEditor {
public Options: IVSCodeEditorOptions;
private modeStatusBarItem: vscode.StatusBarItem;
private commandStatusBarItem: vscode.StatusBarItem;
private vimStyle: IVimStyle;
private visualLineModeStartLine: number;
private visualLineModeEndLine: number;
private visualLineModeFocusPosition: IPosition;
private inNormalModeContext: ContextKey;
private inInsertModeContext: ContextKey;
private inVisualModeContext: ContextKey;
private latestPosition: IPosition;
private latestPositionTimestamp: number;
private changeSelectionByVimStyle: boolean;
public constructor(options: IVSCodeEditorOptions) {
this.modeStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
this.commandStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
this.commandStatusBarItem.show();
this.ApplyOptions(options);
this.inNormalModeContext = new ContextKey("vim.inNormalMode");
this.inInsertModeContext = new ContextKey("vim.inInsertMode");
this.inVisualModeContext = new ContextKey("vim.inVisualMode");
}
public SetVimStyle(vim: IVimStyle) {
this.vimStyle = vim;
}
// Status
public CloseCommandStatus() {
this.commandStatusBarItem.text = "";
}
public ShowCommandStatus(text: string) {
this.commandStatusBarItem.text = text;
}
public ShowModeStatus(mode: VimMode) {
this.modeStatusBarItem.text = Utils.ModeToString(mode);
}
public ApplyOptions(option: IVSCodeEditorOptions) {
this.Options = option;
this.Options.showMode ? this.modeStatusBarItem.show() : this.modeStatusBarItem.hide();
}
// Edit
public InsertTextAtCurrentPosition(text: string) {
vscode.window.activeTextEditor.edit((editBuilder) => {
editBuilder.insert(vscode.window.activeTextEditor.selection.active, text);
});
}
public InsertCharactorAtCurrentPosition(char: string) {
vscode.window.activeTextEditor.edit((editBuilder) => {
editBuilder.insert(vscode.window.activeTextEditor.selection.active, char);
});
}
public TypeDirect(char: string) {
vscode.commands.executeCommand("default:type", { text: char });
}
public Insert(position: IPosition, text: string) {
vscode.window.activeTextEditor.edit((editBuilder) => {
editBuilder.insert(tranceVSCodePosition(position), text);
});
}
public DeleteRange(range: IRange, position?: IPosition) {
vscode.window.activeTextEditor.edit((editBuilder) => {
editBuilder.delete(tranceVSCodeRange(range));
if (this.vimStyle.GetMode() === VimMode.Normal) {
this.showBlockCursor();
}
});
}
public ReplaceRange(range: IRange, text: string) {
vscode.window.activeTextEditor.edit((editBuilder) => {
editBuilder.replace(tranceVSCodeRange(range), text);
});
}
// Read Line
public ReadLine(line: number): string {
if (vscode.window.activeTextEditor.document.lineCount > line) {
return vscode.window.activeTextEditor.document.lineAt(line).text;
}
return null;
}
public ReadLineAtCurrentPosition(): string {
return vscode.window.activeTextEditor.document.lineAt(
vscode.window.activeTextEditor.selection.active.line).text;
}
// Read Range
public ReadRange(range: IRange): string {
return vscode.window.activeTextEditor.document.getText(tranceVSCodeRange(range));
}
// Position
public GetCurrentPosition(): IPosition {
if (this.latestPosition) {
let now = new Date().getTime();
if (now < this.latestPositionTimestamp + 400) {
return this.latestPosition;
}
}
if (vscode.window.activeTextEditor) {
return tranceVimStylePosition(vscode.window.activeTextEditor.selection.active);
}
// no active editor
return null;
}
public SetPosition(p: IPosition) {
let cp = tranceVSCodePosition(p);
vscode.window.activeTextEditor.selection = new vscode.Selection(cp, cp);
vscode.window.activeTextEditor.revealRange(
vscode.window.activeTextEditor.selection, vscode.TextEditorRevealType.Default);
this.showBlockCursor();
this.latestPositionTimestamp = new Date().getTime();
this.latestPosition = p;
}
public GetLastPosition(): IPosition {
let end = vscode.window.activeTextEditor.document.lineAt(
vscode.window.activeTextEditor.document.lineCount - 1).range.end;
return tranceVimStylePosition(end);
}
// Document Info
public GetLastLineNum(): number {
return vscode.window.activeTextEditor.document.lineCount - 1;
}
public dispose() {
this.modeStatusBarItem.dispose();
this.commandStatusBarItem.dispose();
}
// changed focused editor or changed position by user
public ChangePositionByUser() {
if (this.changeSelectionByVimStyle) {
this.changeSelectionByVimStyle = false;
return;
}
if (this.vimStyle.GetMode() === VimMode.Insert) {
// do nothing
return;
}
if (vscode.window.activeTextEditor === undefined) {
// do nothing
return;
}
let s = vscode.window.activeTextEditor.selection;
if (!s.start.isEqual(s.end)) {
this.vimStyle.ApplyVisualMode();
return;
}
this.vimStyle.ApplyNormalMode();
}
public ApplyNormalMode(p?: Position) {
let vp: vscode.Position;
if (p) {
vp = tranceVSCodePosition(p);
vscode.window.activeTextEditor.selection = new vscode.Selection(vp, vp);
}
this.showBlockCursor();
this.inInsertModeContext.set(false);
this.inNormalModeContext.set(true);
this.inVisualModeContext.set(false);
}
public ApplyInsertMode(p?: Position) {
if (p) {
let c = tranceVSCodePosition(p);
vscode.window.activeTextEditor.selection = new vscode.Selection(c, c);
}
this.showLineCursor();
this.inInsertModeContext.set(true);
this.inNormalModeContext.set(false);
this.inVisualModeContext.set(false);
}
public ShowVisualMode(range: IRange, focusPosition?: IPosition) {
let s = new vscode.Selection(tranceVSCodePosition(range.start), tranceVSCodePosition(range.end));
this.changeSelectionByVimStyle = true;
vscode.window.activeTextEditor.selection = s;
if (focusPosition !== undefined) {
let p = tranceVSCodePosition(focusPosition);
let r = new vscode.Range(p, p);
vscode.window.activeTextEditor.revealRange(r, vscode.TextEditorRevealType.Default);
}
this.showLineCursor();
this.inInsertModeContext.set(false);
this.inNormalModeContext.set(false);
this.inVisualModeContext.set(true);
}
public GetCurrentVisualModeSelection(): IRange {
return tranceVimStyleRange(vscode.window.activeTextEditor.selection);
}
public ShowVisualLineMode(startLine: number, endLine: number, focusPosition: IPosition) {
this.visualLineModeStartLine = startLine;
this.visualLineModeEndLine = endLine;
this.visualLineModeFocusPosition = focusPosition;
this.changeSelectionByVimStyle = true;
let start: vscode.Position;
let end: vscode.Position;
let line: string;
if (startLine <= endLine) {
start = new vscode.Position(startLine, 0);
line = vscode.window.activeTextEditor.document.lineAt(endLine).text;
end = new vscode.Position(endLine, line.length);
} else if (endLine < startLine) {
line = vscode.window.activeTextEditor.document.lineAt(startLine).text;
start = new vscode.Position(startLine, line.length);
end = new vscode.Position(endLine, 0);
}
let v = new vscode.Selection(start, end);
vscode.window.activeTextEditor.selection = v;
let fc = tranceVSCodePosition(focusPosition);
let rc = new vscode.Range(fc, fc);
vscode.window.activeTextEditor.revealRange(rc);
this.showBlockCursor();
this.inInsertModeContext.set(false);
this.inNormalModeContext.set(false);
this.inVisualModeContext.set(true);
}
public GetCurrentVisualLineModeSelection(): IVisualLineModeSelectionInfo {
return {
startLine: this.visualLineModeStartLine,
endLine: this.visualLineModeEndLine,
focusPosition: this.visualLineModeFocusPosition,
};
}
public UpdateValidPosition(p: IPosition, isBlock?: boolean): IPosition {
let cp = new Position();
cp.Line = p.Line;
cp.Char = p.Char;
if (p.Line <= 0) {
cp.Line = 0;
} else {
let lastLineNum = this.GetLastLineNum();
if (lastLineNum < p.Line) {
cp.Line = lastLineNum;
}
}
if (cp.Char <= 0) {
cp.Char = 0;
} else {
let line = this.ReadLine(cp.Line);
if (isBlock) {
if (line.length === 0) {
cp.Char = 0;
} else if (cp.Char >= line.length) {
cp.Char = line.length - 1;
}
} else {
if (cp.Char > line.length) {
cp.Char = line.length;
}
}
}
return cp;
}
public GetTabSize(): number {
let n = vscode.window.activeTextEditor.options.tabSize;
let ntype = typeof n;
if (ntype === "number") {
return n as number;
} else if (ntype === "string") {
let ns = parseInt(n as string, 10);
if (isNaN(ns)) {
return ns;
}
}
return 4;
}
public CallEditorCommand(argument: string) {
vscode.commands.executeCommand(argument, null);
}
private showLineCursor() {
if (this.Options.changeCursorStyle) {
let opt = vscode.window.activeTextEditor.options;
opt.cursorStyle = vscode.TextEditorCursorStyle.Line;
vscode.window.activeTextEditor.options = opt;
}
}
private showBlockCursor() {
if (vscode.window.activeTextEditor === undefined) {
return;
}
if (this.Options.changeCursorStyle) {
let opt = vscode.window.activeTextEditor.options;
opt.cursorStyle = vscode.TextEditorCursorStyle.Block;
vscode.window.activeTextEditor.options = opt;
}
}
}
function tranceVimStylePosition(org: vscode.Position): IPosition {
let p = new Position();
p.Line = org.line;
p.Char = org.character;
return p;
}
function tranceVimStyleRange(org: vscode.Range): IRange {
let r = new Range();
r.start = tranceVimStylePosition(org.start);
r.end = tranceVimStylePosition(org.end);
return r;
}
function tranceVSCodePosition(org: IPosition): vscode.Position {
return new vscode.Position(org.Line, org.Char);
}
function tranceVSCodeRange(org: IRange): vscode.Range {
let start = tranceVSCodePosition(org.start);
let end = tranceVSCodePosition(org.end);
return new vscode.Range(start, end);
}
class ContextKey {
private name: string;
private lastValue: boolean;
constructor(name: string) {
this.name = name;
}
public set(value: boolean): void {
if (this.lastValue === value) {
return;
}
this.lastValue = value;
vscode.commands.executeCommand("setContext", this.name, this.lastValue);
}
} | the_stack |
import {Directive, Version} from '../csp';
import {Finding, Severity} from '../finding';
import {CspParser} from '../parser';
import {CheckerFunction} from './checker';
import * as securityChecks from './security_checks';
/**
* Helper function for running a check on a CSP string.
*
* @param test CSP string.
* @param checkFunction check.
*/
function checkCsp(test: string, checkFunction: CheckerFunction): Finding[] {
const parsedCsp = (new CspParser(test)).csp;
return checkFunction(parsedCsp);
}
describe('Test security checks', () => {
/** Tests for csp.securityChecks.checkScriptUnsafeInline */
it('CheckScriptUnsafeInlineInScriptSrc', () => {
const test = 'default-src https:; script-src \'unsafe-inline\'';
const violations = checkCsp(test, securityChecks.checkScriptUnsafeInline);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('CheckScriptUnsafeInlineInDefaultSrc', () => {
const test = 'default-src \'unsafe-inline\'';
const violations = checkCsp(test, securityChecks.checkScriptUnsafeInline);
expect(violations.length).toBe(1);
});
it('CheckScriptUnsafeInlineInDefaultSrcAndNotInScriptSrc', () => {
const test = 'default-src \'unsafe-inline\'; script-src https:';
const violations = checkCsp(test, securityChecks.checkScriptUnsafeInline);
expect(violations.length).toBe(0);
});
it('CheckScriptUnsafeInlineWithNonce', () => {
const test = 'script-src \'unsafe-inline\' \'nonce-foobar\'';
const parsedCsp = (new CspParser(test)).csp;
let effectiveCsp = parsedCsp.getEffectiveCsp(Version.CSP1);
let violations = securityChecks.checkScriptUnsafeInline(effectiveCsp);
expect(violations.length).toBe(1);
effectiveCsp = parsedCsp.getEffectiveCsp(Version.CSP3);
violations = securityChecks.checkScriptUnsafeInline(effectiveCsp);
expect(violations.length).toBe(0);
});
/** Tests for csp.securityChecks.checkScriptUnsafeEval */
it('CheckScriptUnsafeEvalInScriptSrc', () => {
const test = 'default-src https:; script-src \'unsafe-eval\'';
const violations = checkCsp(test, securityChecks.checkScriptUnsafeEval);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.MEDIUM_MAYBE);
});
it('CheckScriptUnsafeEvalInDefaultSrc', () => {
const test = 'default-src \'unsafe-eval\'';
const violations = checkCsp(test, securityChecks.checkScriptUnsafeEval);
expect(violations.length).toBe(1);
});
/** Tests for csp.securityChecks.checkPlainUrlSchemes */
it('CheckPlainUrlSchemesInScriptSrc', () => {
const test = 'script-src data: http: https: sthInvalid:';
const violations = checkCsp(test, securityChecks.checkPlainUrlSchemes);
expect(violations.length).toBe(3);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
});
it('CheckPlainUrlSchemesInObjectSrc', () => {
const test = 'object-src data: http: https: sthInvalid:';
const violations = checkCsp(test, securityChecks.checkPlainUrlSchemes);
expect(violations.length).toBe(3);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
});
it('CheckPlainUrlSchemesInBaseUri', () => {
const test = 'base-uri data: http: https: sthInvalid:';
const violations = checkCsp(test, securityChecks.checkPlainUrlSchemes);
expect(violations.length).toBe(3);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
});
it('CheckPlainUrlSchemesMixed', () => {
const test = 'default-src https:; object-src data: sthInvalid:';
const violations = checkCsp(test, securityChecks.checkPlainUrlSchemes);
expect(violations.length).toBe(2);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
expect(violations[0].directive).toBe(Directive.DEFAULT_SRC);
expect(violations[1].directive).toBe(Directive.OBJECT_SRC);
});
it('CheckPlainUrlSchemesDangerousDirectivesOK', () => {
const test =
'default-src https:; object-src \'none\'; script-src \'none\'; ' +
'base-uri \'none\'';
const violations = checkCsp(test, securityChecks.checkPlainUrlSchemes);
expect(violations.length).toBe(0);
});
/** Tests for csp.securityChecks.checkWildcards */
it('CheckWildcardsInScriptSrc', () => {
const test = 'script-src * http://* //*';
const violations = checkCsp(test, securityChecks.checkWildcards);
expect(violations.length).toBe(3);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
});
it('CheckWildcardsInObjectSrc', () => {
const test = 'object-src * http://* //*';
const violations = checkCsp(test, securityChecks.checkWildcards);
expect(violations.length).toBe(3);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
});
it('CheckWildcardsInBaseUri', () => {
const test = 'base-uri * http://* //*';
const violations = checkCsp(test, securityChecks.checkWildcards);
expect(violations.length).toBe(3);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
});
it('CheckWildcardsSchemesMixed', () => {
const test = 'default-src *; object-src * ignore.me.com';
const violations = checkCsp(test, securityChecks.checkWildcards);
expect(violations.length).toBe(2);
expect(violations.every((v) => v.severity === Severity.HIGH)).toBeTrue();
expect(violations[0].directive).toBe(Directive.DEFAULT_SRC);
expect(violations[1].directive).toBe(Directive.OBJECT_SRC);
});
it('CheckWildcardsDangerousDirectivesOK', () => {
const test = 'default-src *; object-src *.foo.bar; script-src \'none\'; ' +
'base-uri \'none\'';
const violations = checkCsp(test, securityChecks.checkWildcards);
expect(violations.length).toBe(0);
});
/** Tests for csp.securityChecks.checkMissingDirectives */
it('CheckMissingDirectivesMissingObjectSrc', () => {
const test = 'script-src \'none\'';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('CheckMissingDirectivesMissingScriptSrc', () => {
const test = 'object-src \'none\'';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('CheckMissingDirectivesObjectSrcSelf', () => {
const test = 'object-src \'self\'';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('CheckMissingDirectivesMissingBaseUriInNonceCsp', () => {
const test = 'script-src \'nonce-123\'; object-src \'none\'';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('CheckMissingDirectivesMissingBaseUriInHashWStrictDynamicCsp', () => {
const test =
'script-src \'sha256-123456\' \'strict-dynamic\'; object-src \'none\'';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('CheckMissingDirectivesMissingBaseUriInHashCsp', () => {
const test = 'script-src \'sha256-123456\'; object-src \'none\'';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(0);
});
it('CheckMissingDirectivesScriptAndObjectSrcSet', () => {
const test = 'script-src \'none\'; object-src \'none\'';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(0);
});
it('CheckMissingDirectivesDefaultSrcSet', () => {
const test = 'default-src https:;';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(0);
});
it('CheckMissingDirectivesDefaultSrcSetToNone', () => {
const test = 'default-src \'none\';';
const violations = checkCsp(test, securityChecks.checkMissingDirectives);
expect(violations.length).toBe(0);
});
/** Tests for csp.securityChecks.checkScriptAllowlistBypass */
it('checkScriptAllowlistBypassJSONPBypass', () => {
const test = 'script-src *.google.com';
const violations =
checkCsp(test, securityChecks.checkScriptAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
expect(violations[0].description.includes(
'www.google.com is known to host JSONP endpoints which'))
.toBeTrue();
});
it('checkScriptAllowlistBypassWithNoneAndJSONPBypass', () => {
const test = 'script-src *.google.com \'none\'';
const violations =
checkCsp(test, securityChecks.checkScriptAllowlistBypass);
expect(violations.length).toBe(0);
});
it('checkScriptAllowlistBypassJSONPBypassEvalRequired', () => {
const test = 'script-src https://googletagmanager.com \'unsafe-eval\'';
const violations =
checkCsp(test, securityChecks.checkScriptAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('checkScriptAllowlistBypassJSONPBypassEvalRequiredNotPresent', () => {
const test = 'script-src https://googletagmanager.com';
const violations =
checkCsp(test, securityChecks.checkScriptAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.MEDIUM_MAYBE);
});
it('checkScriptAllowlistBypassAngularBypass', () => {
const test = 'script-src gstatic.com';
const violations =
checkCsp(test, securityChecks.checkScriptAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
expect(violations[0].description.includes(
'gstatic.com is known to host Angular libraries which'))
.toBeTrue();
});
it('checkScriptAllowlistBypassNoBypassWarningOnly', () => {
const test = 'script-src foo.bar';
const violations =
checkCsp(test, securityChecks.checkScriptAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.MEDIUM_MAYBE);
});
it('checkScriptAllowlistBypassNoBypassSelfWarningOnly', () => {
const test = 'script-src \'self\'';
const violations =
checkCsp(test, securityChecks.checkScriptAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.MEDIUM_MAYBE);
});
/** Tests for csp.securityChecks.checkFlashObjectAllowlistBypass */
it('checkFlashObjectAllowlistBypassFlashBypass', () => {
const test = 'object-src https://*.googleapis.com';
const violations =
checkCsp(test, securityChecks.checkFlashObjectAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.HIGH);
});
it('checkFlashObjectAllowlistBypassNoFlashBypass', () => {
const test = 'object-src https://foo.bar';
const violations =
checkCsp(test, securityChecks.checkFlashObjectAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.MEDIUM_MAYBE);
});
it('checkFlashObjectAllowlistBypassSelfAllowed', () => {
const test = 'object-src \'self\'';
const violations =
checkCsp(test, securityChecks.checkFlashObjectAllowlistBypass);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.MEDIUM_MAYBE);
expect(violations[0].description)
.toBe('Can you restrict object-src to \'none\' only?');
});
/** Tests for csp.securityChecks.checkIpSource */
it('CheckIpSource', () => {
const test =
'script-src 8.8.8.8; font-src //127.0.0.1 https://[::1] not.an.ip';
const violations = checkCsp(test, securityChecks.checkIpSource);
expect(violations.length).toBe(3);
expect(violations.every((v) => v.severity === Severity.INFO)).toBeTrue();
});
it('LooksLikeIpAddressIPv4', () => {
expect(securityChecks.looksLikeIpAddress('8.8.8.8')).toBeTrue();
});
it('LooksLikeIpAddressIPv6', () => {
expect(securityChecks.looksLikeIpAddress('[::1]')).toBeTrue();
});
it('CheckDeprecatedDirectiveReportUriWithReportTo', () => {
const test = 'report-uri foo.bar/csp;report-to abc';
const violations = checkCsp(test, securityChecks.checkDeprecatedDirective);
expect(violations.length).toBe(0);
});
it('CheckDeprecatedDirectiveWithoutReportUriButWithReportTo', () => {
const test = 'report-to abc';
const violations = checkCsp(test, securityChecks.checkDeprecatedDirective);
expect(violations.length).toBe(0);
});
it('CheckDeprecatedDirectiveReflectedXss', () => {
const test = 'reflected-xss block';
const violations = checkCsp(test, securityChecks.checkDeprecatedDirective);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.INFO);
});
it('CheckDeprecatedDirectiveReferrer', () => {
const test = 'referrer origin';
const violations = checkCsp(test, securityChecks.checkDeprecatedDirective);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.INFO);
});
/** Tests for csp.securityChecks.checkNonceLength */
it('CheckNonceLengthWithLongNonce', () => {
const test = 'script-src \'nonce-veryLongRandomNonce\'';
const violations = checkCsp(test, securityChecks.checkNonceLength);
expect(violations.length).toBe(0);
});
it('CheckNonceLengthWithShortNonce', () => {
const test = 'script-src \'nonce-short\'';
const violations = checkCsp(test, securityChecks.checkNonceLength);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.MEDIUM);
});
it('CheckNonceLengthInvalidCharset', () => {
const test = 'script-src \'nonce-***notBase64***\'';
const violations = checkCsp(test, securityChecks.checkNonceLength);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.INFO);
});
/** Tests for csp.securityChecks.checkSrcHttp */
it('CheckSrcHttp', () => {
const test =
'script-src http://foo.bar https://test.com; report-uri http://test.com';
const violations = checkCsp(test, securityChecks.checkSrcHttp);
expect(violations.length).toBe(2);
expect(violations.every((v) => v.severity === Severity.MEDIUM)).toBeTrue();
});
/** Tests for csp.securityChecks.checkHasConfiguredReporting */
it('CheckHasConfiguredReporting_whenNoReporting', () => {
const test = 'script-src \'nonce-aaaaaaaaaa\'';
const violations =
checkCsp(test, securityChecks.checkHasConfiguredReporting);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.INFO);
expect(violations[0].directive).toBe('report-uri');
});
it('CheckHasConfiguredReporting_whenOnlyReportTo', () => {
const test = 'script-src \'nonce-aaaaaaaaaa\'; report-to name';
const violations =
checkCsp(test, securityChecks.checkHasConfiguredReporting);
expect(violations.length).toBe(1);
expect(violations[0].severity).toBe(Severity.INFO);
expect(violations[0].directive).toBe('report-to');
});
it('CheckHasConfiguredReporting_whenOnlyReportUri', () => {
const test = 'script-src \'nonce-aaaaaaaaaa\'; report-uri url';
const violations =
checkCsp(test, securityChecks.checkHasConfiguredReporting);
expect(violations.length).toBe(0);
});
it('CheckHasConfiguredReporting_whenReportUriAndReportTo', () => {
const test =
'script-src \'nonce-aaaaaaaaaa\'; report-uri url; report-to name';
const violations =
checkCsp(test, securityChecks.checkHasConfiguredReporting);
expect(violations.length).toBe(0);
});
}); | the_stack |
import {UserLayer} from 'neuroglancer/layer';
import {WatchableValue} from 'neuroglancer/trackable_value';
import {DEFAULT_SIDE_PANEL_LOCATION, SidePanelLocation, TrackableSidePanelLocation} from 'neuroglancer/ui/side_panel_location';
import {arraysEqual} from 'neuroglancer/util/array';
import {RefCounted} from 'neuroglancer/util/disposable';
import {parseArray, verifyObject, verifyOptionalObjectProperty, verifyString, verifyStringArray} from 'neuroglancer/util/json';
import {Signal} from 'neuroglancer/util/signal';
const TAB_JSON_KEY = 'tab';
const TABS_JSON_KEY = 'tabs';
const PANELS_JSON_KEY = 'panels';
export const SELECTED_LAYER_SIDE_PANEL_DEFAULT_LOCATION = {
...DEFAULT_SIDE_PANEL_LOCATION,
row: 0,
};
export const LAYER_SIDE_PANEL_DEFAULT_LOCATION = {
...DEFAULT_SIDE_PANEL_LOCATION,
visible: true,
row: 0,
};
export class UserLayerSidePanelState extends RefCounted {
layer = this.panels.layer;
location = new TrackableSidePanelLocation(LAYER_SIDE_PANEL_DEFAULT_LOCATION);
constructor(public panels: UserLayerSidePanelsState) {
super();
}
initialize() {
const {panels} = this;
this.tabsChanged.add(panels.specificationChanged.dispatch);
this.selectedTab.changed.add(panels.specificationChanged.dispatch);
this.location.changed.add(() => {
panels.specificationChanged.dispatch();
const {layer} = this;
const {selectedLayer} = layer.manager.root;
if (selectedLayer.layer?.layer !== layer) return;
if (this !== layer.panels.panels[0]) return;
const curLocation = this.location.value;
if (selectedLayer.location.value !== curLocation) {
selectedLayer.location.value = curLocation;
selectedLayer.location.locationChanged.dispatch();
}
});
this.location.locationChanged.add(() => {
if (this.location.visible) return;
if (this === this.panels.panels[0]) return;
this.panels.removePanel(this);
});
}
tabsChanged = new Signal();
selectedTab = new WatchableValue<string|undefined>(undefined);
explicitTabs: Set<string>|undefined;
tabs: string[] = [];
normalizeTabs() {
const {tabs} = this;
if (tabs.length === 0) {
this.selectedTab.value = undefined;
return;
}
const layerTabs = this.layer.tabs.options;
const getOrder = (tab: string) => layerTabs.get(tab)!.order ?? 0;
tabs.sort((a, b) => getOrder(a) - getOrder(b));
const {selectedTab} = this;
const selectedTabValue = selectedTab.value;
if (selectedTabValue === undefined || !tabs.includes(selectedTabValue)) {
selectedTab.value = tabs[0];
}
}
pin() {
// "Pin" this panel, which means converting it from the selected layer panel to an extra panel.
const {layer} = this;
const {selectedLayer} = layer.manager.root;
// Check that this is the selected layer panel.
if (selectedLayer.layer?.layer !== layer) return;
if (this !== layer.panels.panels[0]) return;
if (this.tabs.length === 0) return;
const {panels} = this;
const newPanel = layer.registerDisposer(new UserLayerSidePanelState(panels));
panels.panels.splice(0, 1, newPanel);
panels.panels.push(this);
panels.updateTabs();
newPanel.initialize();
selectedLayer.layerManager.layersChanged.dispatch();
this.panels.specificationChanged.dispatch();
}
unpin() {
// "Unpin" this panel, which means pinning the current selected layer panel, if any, and making
// this panel the selected layer panel.
const {panels} = this;
const panelIndex = panels.panels.indexOf(this);
if (panelIndex === -1 || panelIndex === 0) return;
const {layer} = this;
const {selectedLayer} = layer.manager.root;
const selectedUserLayer = selectedLayer.layer?.layer;
if (selectedLayer.visible && selectedUserLayer != null && selectedUserLayer != layer) {
const prevSelectedLayerPanel = selectedUserLayer.panels.panels[0];
prevSelectedLayerPanel.pin();
}
panels.panels.splice(panelIndex, 1);
const [origSelectedPanel] = panels.panels.splice(0, 1, this);
if (this.explicitTabs === undefined) {
// This layer will contain all remaining tabs. The old selected layer panel should be
// removed, as otherwise `updateTabs` will incorrectly assign it all tabs.
layer.unregisterDisposer(origSelectedPanel);
} else {
panels.panels.push(origSelectedPanel);
// This layer will contain only the explicit tabs. All other extra layers must be set to have
// explicit tabs as well, as otherwise `updateTabs` will assign all tabs to them.
for (let i = 1, length = panels.panels.length; i < length; ++i) {
const panel = panels.panels[i];
if (panel.explicitTabs === undefined) {
panel.explicitTabs = new Set(panel.tabs);
}
}
}
this.explicitTabs = undefined;
panels.updateTabs();
selectedLayer.layer = layer.managedLayer;
selectedLayer.location.value = this.location.value;
selectedLayer.location.locationChanged.dispatch();
selectedLayer.layerManager.layersChanged.dispatch();
this.panels.specificationChanged.dispatch();
}
splitOffTab(tab: string, location: SidePanelLocation) {
// Move the specified tab to a new panel.
if (!this.tabs.includes(tab)) return;
const {panels} = this;
{
const {explicitTabs} = this;
if (explicitTabs !== undefined) {
explicitTabs.delete(tab);
}
}
const {layer} = this;
const newPanel = layer.registerDisposer(new UserLayerSidePanelState(panels));
newPanel.location.value = location;
newPanel.explicitTabs = new Set([tab]);
panels.panels.splice(1, 0, newPanel);
panels.updateTabs();
newPanel.initialize();
layer.manager.root.layerManager.layersChanged.dispatch();
panels.specificationChanged.dispatch();
}
moveTabTo(tab: string, target: UserLayerSidePanelState) {
if (!this.tabs.includes(tab)) return;
{
const {explicitTabs} = this;
if (explicitTabs !== undefined) {
explicitTabs.delete(tab);
}
}
{
const {explicitTabs} = target;
if (explicitTabs !== undefined) {
explicitTabs.add(tab);
}
}
const {panels} = this;
panels.updateTabs();
target.selectedTab.value = tab;
panels.specificationChanged.dispatch();
}
mergeInto(target: UserLayerSidePanelState) {
const {explicitTabs} = target;
if (explicitTabs !== undefined) {
for (const tab of this.tabs) {
explicitTabs.add(tab);
}
}
const {panels} = this;
panels.removePanel(this);
}
}
export class UserLayerSidePanelsState {
panels: UserLayerSidePanelState[];
specificationChanged = new Signal();
updating = false;
constructor(public layer: UserLayer) {
this.panels = [layer.registerDisposer(new UserLayerSidePanelState(this))];
}
restoreState(obj: unknown) {
const {panels} = this;
panels[0].selectedTab.value = verifyOptionalObjectProperty(obj, TAB_JSON_KEY, verifyString);
const {layer} = this;
const {tabs} = layer;
const availableTabs = new Set<string>(tabs.options.keys());
verifyOptionalObjectProperty(
obj, PANELS_JSON_KEY,
panelsObj => parseArray(panelsObj, panelObj => {
verifyObject(panelObj);
const panel = new UserLayerSidePanelState(this);
panel.location.restoreState(panelObj);
if (!panel.location.visible) return;
panel.selectedTab.value =
verifyOptionalObjectProperty(panelObj, TAB_JSON_KEY, verifyString);
panel.explicitTabs = verifyOptionalObjectProperty(panelObj, TABS_JSON_KEY, tabsObj => {
const curTabs = new Set<string>();
for (const tab of verifyStringArray(tabsObj)) {
if (!availableTabs.has(tab)) continue;
availableTabs.delete(tab);
curTabs.add(tab);
}
return curTabs;
});
if (panel.explicitTabs === undefined) {
panel.tabs = Array.from(availableTabs);
availableTabs.clear();
} else {
panel.tabs = Array.from(panel.explicitTabs);
}
if (panel.tabs.length === 0) return;
panel.normalizeTabs();
layer.registerDisposer(panel);
panel.initialize();
panels.push(panel);
}));
panels[0].tabs = Array.from(availableTabs);
panels[0].normalizeTabs();
this.panels[0].initialize();
}
removePanel(panel: UserLayerSidePanelState) {
if (this.updating) return;
const i = this.panels.indexOf(panel);
this.panels.splice(i, 1);
this.layer.unregisterDisposer(panel);
this.updateTabs();
}
updateTabs() {
const {layer} = this;
const {tabs} = layer;
const availableTabs = new Set<string>(tabs.options.keys());
const {panels} = this;
this.updating = true;
const updatePanelTabs = (panel: UserLayerSidePanelState) => {
const oldTabs = panel.tabs;
if (panel.explicitTabs === undefined) {
panel.tabs = Array.from(availableTabs);
availableTabs.clear();
} else {
panel.tabs = Array.from(panel.explicitTabs);
for (const tab of panel.tabs) {
availableTabs.delete(tab);
}
}
if (!arraysEqual(oldTabs, panel.tabs)) {
panel.normalizeTabs();
panel.tabsChanged.dispatch();
}
};
for (let i = 1; i < panels.length;) {
const panel = panels[i];
if (panel.location.visible) {
updatePanelTabs(panel);
if (panel.tabs.length !== 0) {
++i;
continue;
}
}
panels.splice(i, 1);
layer.unregisterDisposer(panel);
}
updatePanelTabs(panels[0]);
if (panels[0].tabs.length === 0) {
const {selectedLayer} = this.layer.manager.root;
if (selectedLayer.layer?.layer === this.layer) {
selectedLayer.location.visible = false;
}
}
this.updating = false;
}
toJSON() {
const {panels} = this;
const obj: any = {};
obj[TAB_JSON_KEY] = panels[0].selectedTab.value;
if (panels.length > 1) {
const panelsObj: any[] = [];
for (let i = 1, numPanels = panels.length; i < numPanels; ++i) {
const panel = panels[i];
const panelObj = panel.location.toJSON() ?? {};
panelObj[TAB_JSON_KEY] = panel.selectedTab.value;
const {explicitTabs} = panel;
if (explicitTabs !== undefined) {
panelObj[TABS_JSON_KEY] = Array.from(explicitTabs);
}
panelsObj.push(panelObj);
}
obj[PANELS_JSON_KEY] = panelsObj;
}
return obj;
}
} | the_stack |
import * as Fs from 'fs-extra';
import * as Path from 'path';
import * as Tmp from 'tmp';
import { Git } from './git';
import { localStorage as LocalStorage } from './local-storage';
import { Manual } from './manual';
import { Paths, resolveProject } from './paths';
import { prompt } from './prompt';
import { Step } from './step';
import { Submodule } from './submodule';
import { Utils } from './utils';
/**
The 'release' module contains different utilities and methods which are responsible
for release management. Before invoking any method, be sure to fetch **all** the step
tags from the git-host, since most calculations are based on them.
*/
// TODO: Create a dedicated registers/temp dirs module with no memory leaks
const tmp1Dir = Tmp.dirSync({ unsafeCleanup: true });
const tmp2Dir = Tmp.dirSync({ unsafeCleanup: true });
const tmp3Dir = Tmp.dirSync({ unsafeCleanup: true });
async function promptForGitRevision(submoduleName, submodulePath) {
const mostRecentCommit = Git.recentCommit(null, '--format=oneline', null, submodulePath);
const answer = await prompt([
{
type: 'list',
name: 'update-module',
message: `Submodule '${submoduleName}' is pointing to the following commit: ${mostRecentCommit}, is that correct?`,
choices: [
{ name: `Yes, it's the correct commit!`, value: 'yes' },
{ name: `No - I need to make sure some things before releasing`, value: 'exit' },
],
default: 'yes',
},
]);
if (answer === 'yes') {
const commitId = Git.recentCommit(null, '--format="%H"', null, submodulePath);
return {
[submodulePath]: { gitRevision: commitId },
};
} else if (answer === 'exit') {
return null;
}
}
async function promptAndHandleSubmodules(listSubmodules) {
console.log(`ℹ️ Found total of ${listSubmodules.length} submodules.`);
console.log(`❗ Note that you need to make sure your submodules are pointing the correct versions:`);
console.log(`\t- If your submodule is a Tortilla project, make sure to release a new version there.`);
console.log(`\t- If your submodule is NOT a Tortilla project, make sure it's updated and pointing to the correct Git revision.\n`);
let modulesToVersionsMap: any = {};
for (const submodulePath of listSubmodules) {
const fullPath = Path.resolve(Utils.cwd(), submodulePath);
const submoduleName = Path.basename(submodulePath);
Submodule.update(submoduleName)
// If hash doesn't exist
if (
Git(['diff', '--name-only']).split('\n').filter(Boolean).includes(submoduleName)
) {
// Fetch so we can have all release tags available to us
Submodule.fetch(submoduleName)
}
const isTortillaProject = Utils.exists(resolveProject(fullPath).tortillaDir);
if (isTortillaProject) {
const allReleases = getAllReleasesOfAllBranches(fullPath);
if (allReleases.length === 0) {
console.log(`🛑 Found a Tortilla project submodule: '${submoduleName}', but there are no Tortilla releases!`);
console.log(`Please make sure to release a version with Tortilla, and then try again`);
return null;
} else {
const answer = await prompt([
{
type: 'list',
name: submodulePath,
message: `Submodule '${submoduleName}' is a valid Tortilla project. Please pick a release from the list:`,
choices: allReleases.map(releaseInfo => releaseInfo.tagName),
},
]);
modulesToVersionsMap = {
...(modulesToVersionsMap || {}),
[fullPath]: { tortillaVersion: answer },
};
}
} else {
const result = await promptForGitRevision(submoduleName, fullPath);
if (result === null) {
return null;
}
modulesToVersionsMap = {
...modulesToVersionsMap,
...result,
};
}
}
return modulesToVersionsMap;
}
// Creates a bumped release tag of the provided type
// e.g. if the current release is @1.0.0 and we provide this function with a release type
// of 'patch', the new release would be @1.0.1
async function bumpRelease(releaseType, options) {
options = options || {};
let currentRelease;
if (releaseType === 'next') {
currentRelease = {
major: 0,
minor: 0,
patch: 0,
next: true,
};
}
else {
currentRelease = getCurrentRelease(true);
// Increase release type
switch (releaseType) {
case 'major':
currentRelease.major++;
currentRelease.minor = 0;
currentRelease.patch = 0;
break;
case 'minor':
currentRelease.minor++;
currentRelease.patch = 0;
break;
case 'patch':
currentRelease.patch++;
break;
default:
throw Error('Provided release type must be one of "major", "minor", "patch" or "next"');
}
}
const listSubmodules = Submodule.list();
let submodulesRevisions: { [submoduleName: string]: string } = {};
let onInitialCheckout = async () => undefined;
const hasSubmodules = listSubmodules.length > 0;
if (hasSubmodules) {
// This will run at the root commit, just before we render all the manuals
onInitialCheckout = async () => {
submodulesRevisions = await promptAndHandleSubmodules(listSubmodules);
if (!submodulesRevisions || Object.keys(submodulesRevisions).length !== listSubmodules.length) {
throw new Error(`Unexpected submodules versions results!`);
} else {
for (const [submodulePath, revisionChoice] of Object.entries<any>(submodulesRevisions)) {
if (revisionChoice && revisionChoice.tortillaVersion) {
console.log(`▶️ Checking out "${revisionChoice.tortillaVersion}" in Tortilla submodule "${Path.basename(submodulePath)}"...`);
Git(['checkout', revisionChoice.tortillaVersion], { cwd: submodulePath });
} else if (revisionChoice && revisionChoice.gitRevision) {
console.log(`▶️ Checking out "${revisionChoice.gitRevision}" in submodule "${Path.basename(submodulePath)}"...`);
Git(['checkout', revisionChoice.gitRevision], { cwd: submodulePath });
}
}
}
}
}
// Since 'next' release is weakly held, it should be overridden by the given release
deleteNextReleaseTags();
try {
// Store potential release so it can be used during rendering
LocalStorage.setItem('POTENTIAL_RELEASE', JSON.stringify(currentRelease));
Step.edit('root')
// Render once we continue
Git.print(['rebase', '--edit-todo'], {
env: {
GIT_SEQUENCE_EDITOR: `node ${Paths.tortilla.editor} render`,
},
});
// Update the submodules to desired versions
try {
await onInitialCheckout()
} catch (e) {
// Abort before throw if error occurred
Git.print(['rebase', '--abort'])
throw e
}
Git.print(['rebase', '--continue'])
} finally {
LocalStorage.removeItem('POTENTIAL_RELEASE');
}
const branch = Git.activeBranchName();
// The formatted release e.g. 1.0.0
const formattedRelease = formatRelease(currentRelease);
// Extract root data
const rootHash = Git.rootHash();
const rootTag = [branch, 'root', formattedRelease].join('@');
// Create root tag
// e.g. master@root@1.0.1
createReleaseTag(rootTag, rootHash);
// Create a release tag for each super step
Git([
// Log commits
'log',
// Specifically for steps
'--grep', '^Step [0-9]\\+:',
// Formatted with their subject followed by their hash
'--format=%s %H',
]).split('\n')
.filter(Boolean)
.forEach((line) => {
// Extract data
const words = line.split(' ');
const hash = words.pop();
const subject = words.join(' ');
const descriptor = Step.descriptor(subject);
const currentTag = [branch, `step${descriptor.number}`, formattedRelease].join('@');
// Create tag
// e.g. master@step1@1.0.1
createReleaseTag(currentTag, hash);
});
const tag = `${branch}@${formattedRelease}`;
// Create a tag with the provided message which will reference to HEAD
// e.g. 'master@1.0.1'
if (options.message) {
createReleaseTag(tag, 'HEAD', options.message);
// If no message provided, open the editor
} else {
createReleaseTag(tag, 'HEAD', true);
}
createDiffReleasesBranch();
printCurrentRelease();
}
// Removes all the references of the most recent release so the previous one would be the latest
function revertRelease() {
const branch = Git.activeBranchName();
// Getting all branch release tags. Most recent would be first
const branchTags = Git(['tag', '-l'])
.split('\n')
.map((tag) => {
if (!tag) { return null; }
if (new RegExp(`^${branch}@(\\d+\\.\\d+\\.\\d+|next)$`).test(tag)) { return tag; }
if (new RegExp(`^${branch}@root@(\\d+\\.\\d+\\.\\d+|next)$`).test(tag)) { return tag; }
if (new RegExp(`^${branch}@step\\d+@(\\d+\\.\\d+\\.\\d+|next)$`).test(tag)) { return tag; }
})
.filter(Boolean)
.map((tag) => {
const splitted = tag.split('@');
return {
tag,
deformatted: deformatRelease(splitted[1]),
};
})
.sort((a, b) => (
b.deformatted.next ? 1 : a.deformatted.next ? -1 :
(b.deformatted.major - a.deformatted.major) ||
(b.deformatted.minor - a.deformatted.minor) ||
(b.deformatted.patch - a.deformatted.patch)
))
.map(({ tag }) => tag);
if (!branchTags.length) {
throw Error(`No release found for branch ${branch}`)
}
const recentRelease = branchTags[0].split('@').pop()
const recentReleaseTags = branchTags.filter(t => t.split('@').pop() === recentRelease)
Git.print(['tag', '--delete', ...recentReleaseTags])
// Move history branch pointer one commit backward
try {
Git.print(['branch', '-f', `${branch}-history`, `${branch}-history~1`])
}
// was probably root, in which case we will delete the history branch
catch (e) {
Git.print(['branch', '--delete', `${branch}-history`])
}
console.log(`${branch}@${recentRelease} has been successfuly reverted`)
}
// Creates a branch that represents a list of our releases, this way we can view any
// diff combination in the git-host
function createDiffReleasesBranch() {
const destinationDir = createDiffReleasesRepo();
const sourceDir = destinationDir === tmp1Dir.name ? tmp2Dir.name : tmp1Dir.name;
// e.g. master
const currBranch = Git.activeBranchName();
// e.g. master-history
const historyBranch = `${currBranch}-history`;
// Make sure source is empty
Fs.emptyDirSync(sourceDir);
// Create dummy repo in source
Git(['init', sourceDir, '--bare']);
Git(['checkout', '-b', historyBranch], { cwd: destinationDir });
Git(['push', sourceDir, historyBranch], { cwd: destinationDir });
// Pull the newly created project to the branch name above
if (Git.tagExists(historyBranch)) {
Git(['branch', '-D', historyBranch]);
}
Git(['fetch', sourceDir, historyBranch]);
Git(['branch', historyBranch, 'FETCH_HEAD']);
// Clear registers
tmp1Dir.removeCallback();
tmp2Dir.removeCallback();
}
// Invokes 'git diff' with the given releases. An additional arguments vector which will
// be invoked as is may be provided
function diffRelease(
sourceRelease: string,
destinationRelease: string,
argv?: string[],
options: {
branch?: string,
pipe?: boolean
} = {}
) {
// Will work even if null
argv = argv || [];
// Will assume that we would like to run diff with the most recent release
if (!destinationRelease) {
const releases = getAllReleases().map(formatRelease);
const destinationIndex = releases.indexOf(sourceRelease) + 1;
destinationRelease = releases[destinationIndex];
}
const branch = options.branch || Git.activeBranchName();
// Compose tags
// If release ain't exist we will print the entire changes
const sourceReleaseTag = sourceRelease && `${branch}@${sourceRelease}`;
const destinationReleaseTag = `${branch}@${destinationRelease}`;
// Create repo
const sourceDir = createDiffReleasesRepo(sourceReleaseTag, destinationReleaseTag);
const gitOptions = {
cwd: sourceDir,
stdio: options.pipe ? 'pipe' : 'inherit'
};
// Exclude manual view files because we already have templates
argv.push('--', '.', "':!.tortilla/manuals/views'", "':!README.md'");
// Exclude submodules Tortilla files completely
Submodule.getFSNodes({ cwd: sourceDir }).forEach(({ file }) => {
argv.push(`':!${file}/.tortilla'`, `':!${file}/README.md'`);
});
let result
if (sourceReleaseTag) {
// Run 'diff' between the newly created commits
result = Git.print(['diff', 'HEAD^', 'HEAD'].concat(argv), gitOptions);
} else {
// Run so called 'diff' between HEAD and --root. A normal diff won't work here
result = Git.print(['show', '--format='].concat(argv), gitOptions);
}
// Clear registers
tmp1Dir.removeCallback();
tmp2Dir.removeCallback();
// If the right arguments were specified we could receive the diff as a string
// Remove trailing white space so patch can be applied
return result.output && result.output.join('').replace(/ +\n/g, '\n')
}
// Creates the releases diff repo in a temporary dir. The result will be a path for the
// newly created repo
function createDiffReleasesRepo(...tags) {
if (tags.length === 0) {
const branch = Git.activeBranchName();
// Fetch all releases in reversed order, since the commits are going to be stacked
// in the opposite order
tags = getAllReleases()
.map(formatRelease)
.reverse()
.map((releaseString) => `${branch}@${releaseString}`);
} else {
// Sometimes an empty argument might be provided e.g. diffRelease() method
tags = tags.filter(Boolean);
}
const submodules = Submodule.list();
// Resolve relative git module paths into absolute ones so they can be initialized
// later on
const submodulesUrls = submodules.reduce((result, submodule) => {
const urlField = `submodule.${submodule}.url`;
let url = Git(['config', '--file', '.gitmodules', urlField]);
// Resolve relative paths
if (url.substr(0, 1) === '.') {
url = Path.resolve(Utils.cwd(), url);
}
result[submodule] = url;
return result;
}, {});
// We're gonna clone the projects once, and copy paste them whenever a re-clone is needed
const submodulesProjectsDir = tmp3Dir.name;
Fs.ensureDirSync(submodulesProjectsDir);
const existingSubmodules = Fs.readdirSync(submodulesProjectsDir);
const submodulesProjects = submodules.reduce((result, submodule) => {
const url = submodulesUrls[submodule];
result[submodule] = submodulesProjectsDir + '/' + submodule;
// Clone only if haven't cloned before
if (!existingSubmodules.includes(submodule)) {
const authorizedUrl = addHttpCredentials(url)
Git.print(['clone', authorizedUrl, submodule], { cwd: submodulesProjectsDir });
}
return result;
}, {});
// The 'registers' are directories which will be used for temporary FS calculations
let destinationDir = tmp1Dir.name;
let sourceDir = tmp2Dir.name;
// Make sure register2 is empty
Fs.emptyDirSync(sourceDir);
// Initialize an empty git repo in register2
Git(['init'], { cwd: sourceDir });
// Start building the diff-branch by stacking releases on top of each-other
return tags.reduce((registers, tag, index) => {
sourceDir = registers[0];
destinationDir = registers[1];
const sourcePaths = Paths.resolveProject(sourceDir);
const destinationPaths = Paths.resolveProject(destinationDir);
// Make sure destination is empty
Fs.emptyDirSync(destinationDir);
// Copy current git dir to destination
Fs.copySync(Paths.git.resolve(), destinationPaths.git.resolve(), {
filter(filePath) {
// Exclude .git/.tortilla
return !/\.git\/\.tortilla/.test(filePath);
},
});
// Checkout release
Git(['checkout', tag], { cwd: destinationDir });
Git(['checkout', '.'], { cwd: destinationDir });
// Dir will be initialized with git at master by default
Submodule.getFSNodes({
whitelist: submodules,
revision: tag,
}).forEach(({ hash, file }, ...args) => {
const url = submodulesUrls[file];
const subDir = `${destinationDir}/${file}`;
const subPaths = Paths.resolveProject(subDir);
Fs.copySync(submodulesProjects[file], subDir);
try {
Git(['checkout', hash], { cwd: subDir });
} catch (e) {
console.warn();
console.warn(`Object ${hash} is missing for submodule ${file} at release ${tag}.`);
console.warn(`I don't think release for submodule exists anymore...`);
console.warn();
}
Fs.removeSync(subPaths.readme);
Fs.removeSync(subPaths.tortillaDir);
Fs.removeSync(subPaths.git.resolve());
});
// Removing views which are irrelevant to diff. It's much more comfortable to view
// the templates instead
Fs.removeSync(destinationPaths.readme);
Fs.removeSync(destinationPaths.manuals.views);
Fs.removeSync(destinationPaths.gitModules);
Fs.removeSync(destinationPaths.git.resolve());
// Copy destination to source, but without the git dir so there won't be any
// conflicts with the commits
Fs.copySync(sourcePaths.git.resolve(), destinationPaths.git.resolve());
// Add commit for release
Git(['add', '.'], { cwd: destinationDir });
Git(['add', '-u'], { cwd: destinationDir });
// Extracting tag message
const tagLine = Git(['tag', '-l', tag, '-n99']);
const tagMessage = tagLine.replace(/([^\s]+)\s+((?:.|\n)+)/, '$1: $2');
// Creating a new commit with the tag's message
Git(['commit', '-m', tagMessage, '--allow-empty'], {
cwd: destinationDir,
});
return registers.reverse();
}, [
sourceDir, destinationDir,
]).shift();
}
function printCurrentRelease() {
const currentRelease = getCurrentRelease();
const formattedRelease = formatRelease(currentRelease);
const branch = Git.activeBranchName();
console.log();
console.log(`🌟 Release: ${formattedRelease}`);
console.log(`🌟 Branch: ${branch}`);
console.log();
}
// Will transform SSH url into HTTP and will add credentials to HTTP. Originally created
// because of tortilla.academy github app.
function addHttpCredentials(url) {
if (!process.env.TORTILLA_USERNAME || !process.env.TORTILLA_PASSWORD) { return url }
// e.g. git@github.com:Urigo/WhatsApp.git
const sshMatch = url.match(/^\w+@(\w+\.\w+):([\w-]+\/[\w-]+)\.git$/)
if (sshMatch) {
url = `https://${sshMatch[1]}/${sshMatch[2]}`
}
return url.replace(
/^http(s)?:\/\/(.+)$/,
`http$1://${process.env.TORTILLA_USERNAME}:${process.env.TORTILLA_PASSWORD}@$2`
)
}
// Gets the current release based on the latest release tag
// e.g. if we have the tags 'master@0.0.1', 'master@0.0.2' and 'master@0.1.0' this method
// will return { major: 0, minor: 1, patch: 0, next: false }
function getCurrentRelease(skipNext = false) {
// Return potential release, if defined
const potentialRelease = LocalStorage.getItem('POTENTIAL_RELEASE');
if (potentialRelease) {
return JSON.parse(potentialRelease);
}
const allReleases = getAllReleases();
let currentRelease = allReleases.shift();
// If version was yet to be released, assume this is a null version
if (!currentRelease) {
return {
major: 0,
minor: 0,
patch: 0,
next: false,
};
}
// Skip next if we asked to and if necessary
if (skipNext && currentRelease.next) {
currentRelease = allReleases.shift();
}
// No version before next
if (!currentRelease) {
return {
major: 0,
minor: 0,
patch: 0,
next: false,
};
}
return currentRelease;
}
function getAllReleasesOfAllBranches(path = null) {
return Git(['tag'], path ? { cwd: path } : null)
// Put tags into an array
.split('\n')
// If no tags found, filter the empty string
.filter(Boolean)
// Filter all the release tags which are proceeded by their release
.filter((tagName) => {
const pattern1 = /^[^@]+@\d+\.\d+\.\d+$/;
const pattern2 = /^[^@]+@next$/;
return (
tagName.match(pattern1) ||
tagName.match(pattern2)
);
})
// Map all the release strings
.map((tagName) => {
const splitted = tagName.split('@');
return {
tagName,
deformatted: deformatRelease(splitted[1]),
};
})
// Put the latest release first
.sort((a, b) => (
b.deformatted.next ? 1 : a.deformatted.next ? -1 :
(b.deformatted.major - a.deformatted.major) ||
(b.deformatted.minor - a.deformatted.minor) ||
(b.deformatted.patch - a.deformatted.patch)
));
}
// Gets a list of all the releases represented as JSONs e.g.
// [{ major: 0, minor: 1, patch: 0 }]
function getAllReleases(path = null, branch = Git.activeBranchName(path)) {
return Git(['tag'], path ? { cwd: path } : null)
// Put tags into an array
.split('\n')
// If no tags found, filter the empty string
.filter(Boolean)
// Filter all the release tags which are proceeded by their release
.filter((tagName) => {
const pattern1 = new RegExp(`^${branch}@\\d+\\.\\d+\\.\\d+`);
const pattern2 = new RegExp(`${branch}@next$`);
return (
tagName.match(pattern1) ||
tagName.match(pattern2)
)
})
// Map all the release strings
.map((tagName) => tagName.split('@').pop())
// Deformat all the releases into a json so it would be more comfortable to work with
.map((releaseString) => deformatRelease(releaseString))
// Put the latest release first
.sort((a, b) => (
b.next ? 1 : a.next ? -1 :
(b.major - a.major) ||
(b.minor - a.minor) ||
(b.patch - a.patch)
));
}
// Takes a release json and puts it into a pretty string
// e.g. { major: 1, minor: 1, patch: 1, next: false } -> '1.1.1'
function formatRelease(releaseJson) {
if (releaseJson.next) {
return 'next';
}
return [
releaseJson.major,
releaseJson.minor,
releaseJson.patch,
].join('.');
}
// Takes a release string and puts it into a pretty json object
// e.g. '1.1.1' -> { major: 1, minor: 1, patch: 1, next: false }
function deformatRelease(releaseString) {
if (releaseString === 'next') {
return {
major: 0,
minor: 0,
patch: 0,
next: true,
};
}
const releaseSlices = releaseString.split('.').map(Number);
return {
major: releaseSlices[0],
minor: releaseSlices[1],
patch: releaseSlices[2],
next: false,
};
}
function createReleaseTag(tag, dstHash, message?) {
let srcHash = Git.activeBranchName();
if (srcHash === 'HEAD') {
srcHash = Git(['rev-parse', 'HEAD']);
}
Git(['checkout', dstHash]);
// Remove files which shouldn't be included in releases
// TODO: Remove files based on a user defined blacklist
Fs.removeSync(Paths.travis);
Fs.removeSync(Paths.renovate);
// Releasing a version
Git.print(['commit', '--amend'], { env: { GIT_EDITOR: true } });
// Provide a quick message
if (typeof message === 'string') {
Git.print(['tag', tag, '-m', message]);
// Open editor
} else if (message === true) {
Git.print(['tag', tag, '-a']);
// No message
} else {
Git(['tag', tag]);
}
// Returning to the original hash
Git(['checkout', srcHash]);
// Restore renovate.json and .travis.yml
Git(['checkout', '.']);
}
// Delete all @next tag releases of the current branch.
// e.g. master@next, master@root@next, master@step1@next
function deleteNextReleaseTags() {
const branch = Git.activeBranchName();
Git(['tag', '-l']).split('\n').filter(Boolean).forEach((tagName) => {
if (
new RegExp(`^${branch}@`).test(tagName) &&
new RegExp(`@next$`).test(tagName)
) {
Git(['tag', '--delete', tagName]);
}
});
}
export const Release = {
bump: bumpRelease,
revert: revertRelease,
createDiffBranch: createDiffReleasesBranch,
printCurrent: printCurrentRelease,
current: getCurrentRelease,
all: getAllReleases,
diff: diffRelease,
format: formatRelease,
deformat: deformatRelease,
}; | the_stack |
import { Fetcher } from "./Fetcher";
import { FetchableType } from "./Fetchable";
export class DependencyManager {
/*
* key: Name the root entity type of query
*/
private rootTypeResourceMap = new Map<string, Resources>();
/*
* level-1 key: FieldName
* level-2 key: Field name
*/
private fieldResourceMap = new Map<string, Map<string, Resources>>();
private _idGetter: (obj: any) => any;
constructor(idGetter?: (obj: any) => any) {
(window as any).dependencyManager = this;
this._idGetter = idGetter ?? getDefaultId;
}
register(resource: string, fetcher: Fetcher<string, object, object>, fieldDependencies?: readonly Fetcher<string, object, object>[]) {
if (fieldDependencies !== undefined) {
this.registerTypes(resource, [fetcher, ...fieldDependencies]);
this.registerFields(resource, fieldDependencies);
} else {
this.registerTypes(resource, [fetcher]);
}
}
unregister(resource: string) {
removeResource(this.rootTypeResourceMap, resource);
removeResource(this.fieldResourceMap, resource);
}
resources<TObject extends object>(
fetcher: Fetcher<string, TObject, object>,
oldObject: TObject | null | undefined,
newObject: TObject | null | undefined
): string[] {
const resources = new Set<string>();
this.collectResources(
fetcher,
nullToUndefined(oldObject),
nullToUndefined(newObject),
resources
);
return Array.from(resources);
}
allResources(fetcher: Fetcher<string, object, object>) {
const resources = new Set<string>();
this.collectAllResources(fetcher, resources);
return Array.from(resources);
}
private registerTypes(resource: string, fetchers: readonly Fetcher<string, object, object>[]) {
for (const fetcher of fetchers) {
const isOperation = isOperationFetcher(fetcher);
for (const [fieldName, field] of fetcher.fieldMap) {
if (!fieldName.startsWith("...")) {
const declaringTypeNames = getDeclaringTypeNames(fieldName, fetcher);
for (const declaringTypeName of declaringTypeNames) {
compute(this.rootTypeResourceMap, declaringTypeName, () => new Resources()).retain(resource);
}
}
if (field.childFetchers !== undefined) {
this.registerTypes(resource, field.childFetchers);
}
}
}
}
private registerFields(resource: string, fetchers: readonly Fetcher<string, object, object>[]) {
for (const fetcher of fetchers) {
const isOperation = isOperationFetcher(fetcher);
for (const [fieldName, field] of fetcher.fieldMap) {
if (!isOperation && !fieldName.startsWith("...")) {
const subMap = compute(this.fieldResourceMap, fieldName, () => new Map<string, Resources>());
const declaringTypeNames = getDeclaringTypeNames(fieldName, fetcher);
for (const declaringTypeName of declaringTypeNames) {
compute(subMap, declaringTypeName, () => new Resources()).retain(resource);
}
}
if (field.childFetchers !== undefined) {
this.registerFields(resource, field.childFetchers);
}
}
}
}
private collectResources(
fetcher: Fetcher<string, object, object>,
oldObject: object | undefined,
newObject: object | undefined,
output: Set<string>
) {
if (oldObject === newObject) { // Include both undefined
return;
}
if (oldObject === undefined || newObject === undefined) {
this.rootTypeResourceMap.get(fetcher.fetchableType.name)?.copyTo(output);
} else if (!isOperationFetcher(fetcher)) {
const oldId = this._idGetter(oldObject);
const newId = this._idGetter(newObject);
if (oldId !== newId) {
this.rootTypeResourceMap.get(fetcher.fetchableType.name)?.copyTo(output);
}
}
for (const [fieldName, field] of fetcher.fieldMap) {
if (fieldName.startsWith("...")) { // Fragment, not assocaition
if (field.childFetchers !== undefined) {
for (const childFetcher of field.childFetchers) {
this.collectResources(childFetcher, oldObject, newObject, output);
}
}
} else {
const oldValue = nullToUndefined(oldObject !== undefined ? oldObject[fieldName] : undefined);
const newValue = nullToUndefined(newObject !== undefined ? newObject[fieldName] : undefined);
if (field.childFetchers !== undefined && field.childFetchers.length !== 0) { // association
if (oldValue !== newValue) { // Not both undefined
for (const childFetcher of field.childFetchers) {
this.collectResourcesByAssocaiton(fetcher, fieldName, childFetcher, oldValue, newValue, output);
}
}
} else if (!scalarEqual(oldValue, newValue)) { // scalar
const subMap = this.fieldResourceMap.get(fieldName);
if (subMap !== undefined) {
const declaringTypeNames = getDeclaringTypeNames(fieldName, fetcher);
for (const declaringTypeName of declaringTypeNames) {
subMap.get(declaringTypeName)?.copyTo(output);
}
}
}
}
}
}
private collectResourcesByAssocaiton(
parentFetcher: Fetcher<string, object, object>,
fieldName: string,
childFetcher: Fetcher<string, object, object>,
oldAssociation: any,
newAssociation: any,
output: Set<string>
) {
if (oldAssociation === undefined || newAssociation === undefined || Array.isArray(oldAssociation) !== Array.isArray(newAssociation)) {
if (Array.isArray(oldAssociation)) {
for (const element of oldAssociation) {
this.collectResources(childFetcher, nullToUndefined(element), undefined, output);
}
} else if (typeof oldAssociation === 'object') {
this.collectResources(childFetcher, oldAssociation, undefined, output);
}
if (Array.isArray(newAssociation)) {
for (const element of newAssociation) {
this.collectResources(childFetcher, undefined, nullToUndefined(element), output);
}
} else if (typeof newAssociation === 'object') {
this.collectResources(childFetcher, undefined, newAssociation, output);
}
} else if (Array.isArray(oldAssociation) && Array.isArray(newAssociation)) {
const map1 = associatedBy(oldAssociation, this._idGetter);
const map2 = associatedBy(newAssociation, this._idGetter);
for (const [k, o1] of map1) {
const o2 = map2.get(k);
this.collectResources(childFetcher, nullToUndefined(o1), nullToUndefined(o2), output);
}
for (const [k, o2] of map2) {
if (!map2.has(k)) {
this.collectResources(childFetcher, undefined, nullToUndefined(o2), output);
}
}
} else if (typeof oldAssociation === 'object' && typeof newAssociation === 'object') {
this.collectResources(childFetcher, oldAssociation, newAssociation, output);
} else {
const declaringType = getDeclaringTypeNames(fieldName, parentFetcher)[0];
console.warn(`Illegal data, cannot compare the data ${oldAssociation} and ${newAssociation} for the assocaiton ${declaringType}.${fieldName}`);
}
}
private collectAllResources(fetcher: Fetcher<string, object, object>, output: Set<string>) {
this.rootTypeResourceMap.get(fetcher.fetchableType.name)?.copyTo(output);
for (const [fieldName, field] of fetcher.fieldMap) {
if (!fieldName.startsWith("...")) { // Not fragment
const declaringTypes = getDeclaringTypeNames(fieldName, fetcher);
for (const declaringType of declaringTypes) {
this.rootTypeResourceMap.get(declaringType)?.copyTo(output);
this.fieldResourceMap.get(fieldName)?.get(declaringType)?.copyTo(output);
}
}
if (field.childFetchers !== undefined) {
for (const childFetcher of field.childFetchers) {
this.collectAllResources(childFetcher, output);
}
}
}
}
}
class Resources {
private refCountMap = new Map<string, number>();
retain(resource: string) {
this.refCountMap.set(resource, (this.refCountMap.get(resource) ?? 0) + 1);
}
release(resource: string): number {
const refCount = this.refCountMap.get(resource);
if (refCount !== undefined) {
if (refCount > 1) {
this.refCountMap.set(resource, refCount - 1);
} else {
this.refCountMap.delete(resource);
}
}
return this.refCountMap.size;
}
copyTo(output: Set<string>) {
for (const [resource] of this.refCountMap) {
output.add(resource);
}
}
}
function isOperationFetcher(fetcher: Fetcher<string, object, object>): boolean {
const fetcherName = fetcher.fetchableType.name;
return fetcherName === "Query" || fetcherName === 'Mutation';
}
function getDeclaringTypeNames(fieldName: string, fetcher: Fetcher<string, object, object>): Set<string> {
const declaringTypeNames = new Set<string>();
if (fieldName !== '' && fieldName !== '...') {
collectDeclaringTypeNames(fieldName, fetcher.fetchableType, declaringTypeNames);
}
return declaringTypeNames;
}
function collectDeclaringTypeNames(fieldName: string, fetchableType: FetchableType<string>, output: Set<string>) {
if (fetchableType.declaredFields.has(fieldName)) {
output.add(fetchableType.name);
} else {
for (const superType of fetchableType.superTypes) {
collectDeclaringTypeNames(fieldName, superType, output);
}
}
}
function getDefaultId(value: any): any {
const id = value.id ?? value._id;
if (id === undefined) {
throw Error(`There is no id/_id in the object ${JSON.stringify(value)}`);
}
return id;
}
function compute<K, V>(map: Map<K, V>, key: K, valueSupplier: (key: K) => V): V {
let value = map.get(key);
if (value === undefined) {
map.set(key, value = valueSupplier(key));
}
return value;
}
type RecursiveResourceMap = Map<string, Resources | RecursiveResourceMap>;
function removeResource(recursiveResourceMap: RecursiveResourceMap, resource: string) {
const deletedKeys = new Set<string>();
for (const [key, deeperValue] of recursiveResourceMap) {
if (deeperValue instanceof Resources) {
if (deeperValue.release(resource) === 0) {
deletedKeys.add(key);
}
} else {
removeResource(deeperValue, resource);
if (deeperValue.size === 0) {
deletedKeys.add(key);
}
}
}
for (const deletedKey of deletedKeys) {
recursiveResourceMap.delete(deletedKey);
}
}
function associatedBy<K, V>(values: V[], keyGetter: (value: V) => K): Map<K, V> {
const map = new Map<K, V>();
for (const value of values) {
if (value !== undefined && value !== null) {
const key = keyGetter(value);
map.set(key, value);
}
}
return map;
}
function scalarEqual(left: any, right: any) {
if (Array.isArray(left) && Array.isArray(right)) {
if (left.length !== right.length) {
return false;
}
for (let i = left.length - 1; i >= 0; --i) {
if (nullToUndefined(left[i]) !== nullToUndefined(right[i])) {
return false;
}
}
return true;
}
return left === right;
}
function nullToUndefined<T>(value: T | null | undefined): T | undefined {
return value === null ? undefined : value;
} | the_stack |
* Copyright 2015 Dev Shop Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// notice_end
import * as esp from '../../src';
describe('Router', () => {
let _router;
beforeEach(() => {
_router = new esp.Router();
});
describe('eventProcessors', () => {
let _model1: { },
_model2: { },
_model3: { },
_model5: {
preProcessCount: number,
eventDispatchItems: {eventType:string, event: any, stage: esp.ObservationStage}[],
eventDispatchedItems: {eventType:string, event: any, stage: esp.ObservationStage}[],
postProcessCount: number,
eventsProcessed: string[],
preProcess: ()=> void;
eventDispatch: (eventType: string, event: any, observationStage: esp.ObservationStage) => void,
eventDispatched: (eventType: string, event: any, observationStage: esp.ObservationStage) => void,
postProcess: (eventsProcessed: string[])=> void;
},
_model6: {},
_modelsSentForPreProcessing = [],
_eventsSentToDispatch = [],
_eventsSentToDispatched = [],
_modelsSentForPostProcessing = [],
_options = {
preEventProcessor: (model) => {
_modelsSentForPreProcessing.push(model);
},
eventDispatchProcessor: (model: any, eventType: string, event: any, stage: esp.ObservationStage) => {
_eventsSentToDispatch.push({model, eventType, event, stage});
},
eventDispatchedProcessor: (model: any, eventType: string, event: any, stage: esp.ObservationStage) => {
_eventsSentToDispatched.push({model, eventType, event, stage});
},
postEventProcessor: (model, eventsProcessed) => {
_modelsSentForPostProcessing.push({model, eventsProcessed});
}
};
beforeEach(() => {
_model1 = { };
_model2 = { };
_model3 = { };
_model5 = {
preProcessCount : 0,
eventDispatchItems: [],
eventDispatchedItems: [],
postProcessCount : 0,
eventsProcessed: [],
preProcess() {
this.preProcessCount++;
},
eventDispatch(eventType: string, event: any, stage: esp.ObservationStage) {
this.eventDispatchItems.push({eventType, event, stage});
},
eventDispatched(eventType: string, event: any, stage: esp.ObservationStage) {
this.eventDispatchedItems.push({eventType, event, stage});
},
postProcess(eventsProcessed) {
this.postProcessCount++;
this.eventsProcessed = eventsProcessed;
}
};
_model6 = { };
_modelsSentForPreProcessing = [];
_eventsSentToDispatch = [];
_eventsSentToDispatched = [];
_modelsSentForPostProcessing = [];
_router.addModel('modelId1', _model1, _options);
_router.addModel('modelId2', _model2, _options);
_router.addModel('modelId3', _model3, _options);
_router.addModel('modelId5', _model5);
_router.addModel('modelId6', _model6, _options);
_router.getEventObservable('modelId1', 'startEvent').subscribe(() => {
_router.publishEvent('modelId3', 'Event1', 'theEvent');
_router.publishEvent('modelId2', 'Event1', 'theEvent');
_router.publishEvent('modelId1', 'Event1', 'theEvent');
});
_router.getEventObservable('modelId5', 'startEvent').subscribe(() => {
/* noop */
});
_router.getEventObservable('modelId6', 'startEvent').subscribe(() => {
/* noop */
});
});
function assertDispatchedItems(array: {eventType: string, event:any, stage:esp.ObservationStage}[]) {
expect(array.length).toBe(3);
expect(array[0].eventType).toEqual('startEvent');
expect(array[0].event).toEqual('theEvent');
expect(array[0].stage).toEqual(esp.ObservationStage.preview);
expect(array[1].eventType).toEqual('startEvent');
expect(array[1].event).toEqual('theEvent');
expect(array[1].stage).toEqual(esp.ObservationStage.normal);
expect(array[2].eventType).toEqual('startEvent');
expect(array[2].event).toEqual('theEvent');
expect(array[2].stage).toEqual(esp.ObservationStage.final);
}
it('calls preProcess() if the model has this method before processing the first event', () => {
_router.publishEvent('modelId5', 'startEvent', 'theEvent');
expect(_model5.preProcessCount).toBe(1);
});
it('calls eventDispatch() if the model has this method before each event is dispatched', () => {
_router.publishEvent('modelId5', 'startEvent', 'theEvent');
assertDispatchedItems(_model5.eventDispatchItems);
});
it('calls eventDispatched() if the model has this method after each event is dispatched', () => {
_router.publishEvent('modelId5', 'startEvent', 'theEvent');
assertDispatchedItems(_model5.eventDispatchedItems);
});
it('calls eventDispatchProcessor() if the the function exists on the options given at registration time', () => {
_router.publishEvent('modelId6', 'startEvent', 'theEvent');
assertDispatchedItems(_eventsSentToDispatch);
});
it('calls eventDispatchedProcessor() if the the function exists on the options given at registration time', () => {
_router.publishEvent('modelId6', 'startEvent', 'theEvent');
assertDispatchedItems(_eventsSentToDispatched);
});
it('calls postProcess() if the model has this method after processing the first event', () => {
_router.publishEvent('modelId5', 'startEvent', 'theEvent');
expect(_model5.postProcessCount).toBe(1);
});
it('postProcess() passes the events published to postProcess', () => {
_router.publishEvent('modelId5', 'startEvent', 'theEvent');
expect(_model5.eventsProcessed).toEqual(['startEvent']);
});
it('calls a models preProcess() function if the model is NOT observing the published event', () => {
_router.publishEvent('modelId5', 'nothingListeningToThisEvent', 'theEventPayload');
expect(_model5.preProcessCount).toBe(1);
});
it('calls a models postProcess() function if the model is NOT observing the published event', () => {
_router.publishEvent('modelId5', 'nothingListeningToThisEvent', 'theEventPayload');
expect(_model5.postProcessCount).toBe(1);
});
it('calls a models pre event processor even if the model is not observing the published event', () => {
_router.publishEvent('modelId1', 'nothingListeningToThisEvent', 'theEventPayload');
const passed = _modelsSentForPreProcessing.length === 1;
expect(passed).toBe(true);
});
it('calls a models post event processor even if the model is not observing the published event', () => {
_router.publishEvent('modelId1', 'nothingListeningToThisEvent', 'theEventPayload');
const passed = _modelsSentForPostProcessing.length === 1;
expect(passed).toBe(true);
});
it('calls a models post processors in order before processing the next models events', () => {
/**
* This test also assets that models get processed in the order they had events published to them.
*/
let passed = true, callbackCount = 0;
_router.getEventObservable('modelId1', 'Event1').subscribe(() => {
callbackCount++;
});
_router.getEventObservable('modelId2', 'Event1').subscribe(() => {
callbackCount++;
passed = passed && _modelsSentForPostProcessing.length === 2 && _modelsSentForPostProcessing[1].model === _model3;
});
_router.getEventObservable('modelId3', 'Event1').subscribe(() => {
callbackCount++;
passed = passed && _modelsSentForPostProcessing.length === 1 && _modelsSentForPostProcessing[0].model === _model1;
});
_router.publishEvent('modelId1', 'startEvent', 'theEvent');
passed = passed && _modelsSentForPostProcessing.length === 3 && _modelsSentForPostProcessing[2].model === _model2;
expect(passed).toBe(true);
expect(callbackCount).toBe(3);
});
it('calls a models pre processors before dispatching to processors', () => {
let passed = false;
_router.getEventObservable('modelId1', 'Event1').subscribe(() => {
passed = _modelsSentForPreProcessing.length === 1 && _modelsSentForPreProcessing[0] === _model1;
});
_router.publishEvent('modelId1', 'Event1', 'theEvent');
expect(passed).toBe(true);
});
it('only calls the pre event processor for the model the event was targeted at', () => {
_router.getEventObservable('modelId1', 'Event1').subscribe(() => {
});
_router.publishEvent('modelId1', 'Event1', 'theEvent');
const passed = _modelsSentForPreProcessing.length === 1 && _modelsSentForPreProcessing[0] === _model1;
expect(passed).toBe(true);
});
it('should allow a preEventProcessor to publish an event', () => {
_router.addModel('modelId4', _model1, { preEventProcessor : () => {_router.publishEvent('modelId4', 'Event2', 'theEvent'); } });
let wasPublished = false;
_router.getEventObservable('modelId4', 'Event2').subscribe(() => {
wasPublished = true;
});
_router.getEventObservable('modelId4', 'Event1').subscribe(() => {
/* noop */
});
_router.publishEvent('modelId4', 'Event1', 'theEvent');
expect(wasPublished).toEqual(true);
});
it('should allow a postEventProcessor to publish an event', () => {
let eventReceived = false,
eventWasRaisedInNewEventLoop = false,
postProcessorPublished = false;
_router.addModel(
'modelId4',
{ version: 1 }, // model
{
preEventProcessor : (model) => { model.version++; },
postEventProcessor : () => {
if(!postProcessorPublished) {
postProcessorPublished = true;
_router.publishEvent('modelId4', 'Event2', 'theEvent2');
}
}
});
_router.getEventObservable('modelId4', 'Event1').subscribe(({event, context, model}) => {
eventReceived = true;
eventWasRaisedInNewEventLoop = model.version ===2;
});
_router.publishEvent('modelId4', 'Event1', 'theEvent');
expect(eventReceived).toBe(true);
expect(eventWasRaisedInNewEventLoop).toBe(true);
});
});
}); | the_stack |
import * as assert from 'assert';
import * as fs from 'fs';
import * as sinon from 'sinon';
import appInsights from '../../../../appInsights';
import auth from '../../../../Auth';
import { Cli, Logger } from '../../../../cli';
import Command from '../../../../Command';
import request from '../../../../request';
import { sinonUtil } from '../../../../utils';
import commands from '../../commands';
const command: Command = require('./o365group-recyclebinitem-clear');
describe(commands.O365GROUP_RECYCLEBINITEM_CLEAR, () => {
let log: string[];
let logger: Logger;
let promptOptions: any;
before(() => {
sinon.stub(auth, 'restoreAuth').callsFake(() => Promise.resolve());
sinon.stub(appInsights, 'trackEvent').callsFake(() => { });
sinon.stub(fs, 'readFileSync').callsFake(() => 'abc');
auth.service.connected = true;
});
beforeEach(() => {
log = [];
logger = {
log: (msg: string) => {
log.push(msg);
},
logRaw: (msg: string) => {
log.push(msg);
},
logToStderr: (msg: string) => {
log.push(msg);
}
};
sinon.stub(Cli, 'prompt').callsFake((options: any, cb: (result: { continue: boolean }) => void) => {
promptOptions = options;
cb({ continue: false });
});
promptOptions = undefined;
});
afterEach(() => {
sinonUtil.restore([
request.get,
request.delete,
Cli.prompt
]);
});
after(() => {
sinonUtil.restore([
auth.restoreAuth,
fs.readFileSync,
appInsights.trackEvent
]);
auth.service.connected = false;
});
it('has correct name', () => {
assert.strictEqual(command.name.startsWith(commands.O365GROUP_RECYCLEBINITEM_CLEAR), true);
});
it('has a description', () => {
assert.notStrictEqual(command.description, null);
});
it('clears the recycle bin items without prompting for confirmation when --confirm option specified', (done) => {
const deleteStub = sinon.stub(request, 'delete').callsFake(() => Promise.resolve());
// Stub representing the get deleted items operation
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://graph.microsoft.com/v1.0/directory/deletedItems/Microsoft.Graph.Group?$filter=groupTypes/any(c:c+eq+'Unified')&$top=100`) {
return Promise.resolve({
"value": [
{
"id": "010d2f0a-0c17-4ec8-b694-e85bbe607013",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-07T13:58:01Z",
"description": "Team 1",
"displayName": "Team 1",
"groupTypes": [
"Unified"
],
"mail": "team_1@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_1",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_1@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-07T13:58:01Z",
"securityEnabled": false,
"visibility": "Private"
},
{
"id": "0157132c-bf82-48ff-99e4-b19a74950fe0",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-17T13:30:42Z",
"description": "Team 2",
"displayName": "Team 2",
"groupTypes": [
"Unified"
],
"mail": "team_2@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_2",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_2@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-17T13:30:42Z",
"securityEnabled": false,
"visibility": "Private"
}
]
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { debug: false, confirm: true } }, () => {
try {
assert(deleteStub.calledTwice);
done();
}
catch (e) {
done(e);
}
});
});
it('clears the recycle bin items when deleted items data is served in pages and --confirm option specified', (done) => {
const deleteStub = sinon.stub(request, 'delete').callsFake(() => Promise.resolve());
// Stub representing the get deleted items operation
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://graph.microsoft.com/v1.0/directory/deletedItems/Microsoft.Graph.Group?$filter=groupTypes/any(c:c+eq+'Unified')&$top=100`) {
return Promise.resolve({
"@odata.nextLink": "https://graph.microsoft.com/v1.0/directory/deletedItems/Microsoft.Graph.Group?$filter=groupTypes/any(c:c+eq+'Unified')&$top=100&$skiptoken=X%2744537074090001000000000000000014000000C233BFA08475B84E8BF8C40335F8944D01000000000000000000000000000017312E322E3834302E3131333535362E312E342E32333331020000000000017D06501DC4C194438D57CFE494F81C1E%27",
"value": [
{
"id": "010d2f0a-0c17-4ec8-b694-e85bbe607013",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-07T13:58:01Z",
"description": "Team 1",
"displayName": "Team 1",
"groupTypes": [
"Unified"
],
"mail": "team_1@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_1",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_1@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-07T13:58:01Z",
"securityEnabled": false,
"visibility": "Private"
},
{
"id": "0157132c-bf82-48ff-99e4-b19a74950fe0",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-17T13:30:42Z",
"description": "Team 2",
"displayName": "Team 2",
"groupTypes": [
"Unified"
],
"mail": "team_2@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_2",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_2@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-17T13:30:42Z",
"securityEnabled": false,
"visibility": "Private"
}
]
});
}
if (opts.url === `https://graph.microsoft.com/v1.0/directory/deletedItems/Microsoft.Graph.Group?$filter=groupTypes/any(c:c+eq+'Unified')&$top=100&$skiptoken=X%2744537074090001000000000000000014000000C233BFA08475B84E8BF8C40335F8944D01000000000000000000000000000017312E322E3834302E3131333535362E312E342E32333331020000000000017D06501DC4C194438D57CFE494F81C1E%27`) {
return Promise.resolve({
"value": [
{
"id": "310d2f0a-0c17-4ec8-b694-e85bbe607013",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-07T13:58:01Z",
"description": "Team 3",
"displayName": "Team 3",
"groupTypes": [
"Unified"
],
"mail": "team_1@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_3",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_1@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-07T13:58:01Z",
"securityEnabled": false,
"visibility": "Private"
}
]
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { debug: false, confirm: true } }, () => {
try {
assert(deleteStub.calledThrice);
done();
}
catch (e) {
done(e);
}
});
});
it('does not call delete when there are no items in the O365 group recycle bin', (done) => {
const deleteStub = sinon.stub(request, 'delete').callsFake(() => Promise.resolve());
// Stub representing the get deleted items operation
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://graph.microsoft.com/v1.0/directory/deletedItems/Microsoft.Graph.Group?$filter=groupTypes/any(c:c+eq+'Unified')&$top=100`) {
return Promise.resolve({
"value": []
});
}
return Promise.reject('Invalid request');
});
command.action(logger, { options: { debug: false, confirm: true } }, () => {
try {
assert(deleteStub.notCalled);
done();
}
catch (e) {
done(e);
}
});
});
it('prompts before clearing the O365 Group recycle bin items when --confirm option is not passed', (done) => {
command.action(logger, { options: { debug: false } }, () => {
let promptIssued = false;
if (promptOptions && promptOptions.type === 'confirm') {
promptIssued = true;
}
try {
assert(promptIssued);
done();
}
catch (e) {
done(e);
}
});
});
it('aborts clearing the O365 Group recyclebin items when prompt not confirmed', (done) => {
const deleteSpy = sinon.spy(request, 'delete');
sinonUtil.restore(Cli.prompt);
sinon.stub(Cli, 'prompt').callsFake((options: any, cb: (result: { continue: boolean }) => void) => {
cb({ continue: false });
});
command.action(logger, { options: { debug: false } }, () => {
try {
assert(deleteSpy.notCalled);
done();
}
catch (e) {
done(e);
}
});
});
it('aborts clearing the recycle bin items when prompt not confirmed (debug)', (done) => {
const deleteSpy = sinon.spy(request, 'delete');
sinonUtil.restore(Cli.prompt);
sinon.stub(Cli, 'prompt').callsFake((options: any, cb: (result: { continue: boolean }) => void) => {
cb({ continue: false });
});
command.action(logger, { options: { debug: true } }, () => {
try {
assert(deleteSpy.notCalled);
done();
}
catch (e) {
done(e);
}
});
});
it('clears the O365 Group recycle bin items when prompt is confirmed', (done) => {
const deleteStub = sinon.stub(request, 'delete').callsFake(() => Promise.resolve());
// Stub representing the get deleted items operation
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://graph.microsoft.com/v1.0/directory/deletedItems/Microsoft.Graph.Group?$filter=groupTypes/any(c:c+eq+'Unified')&$top=100`) {
return Promise.resolve({
"value": [
{
"id": "010d2f0a-0c17-4ec8-b694-e85bbe607013",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-07T13:58:01Z",
"description": "Team 1",
"displayName": "Team 1",
"groupTypes": [
"Unified"
],
"mail": "team_1@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_1",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_1@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-07T13:58:01Z",
"securityEnabled": false,
"visibility": "Private"
},
{
"id": "0157132c-bf82-48ff-99e4-b19a74950fe0",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-17T13:30:42Z",
"description": "Team 2",
"displayName": "Team 2",
"groupTypes": [
"Unified"
],
"mail": "team_2@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_2",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_2@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-17T13:30:42Z",
"securityEnabled": false,
"visibility": "Private"
}
]
});
}
return Promise.reject('Invalid request');
});
sinonUtil.restore(Cli.prompt);
sinon.stub(Cli, 'prompt').callsFake((options: any, cb: (result: { continue: boolean }) => void) => {
cb({ continue: true });
});
command.action(logger, { options: { debug: false } }, () => {
try {
assert(deleteStub.calledTwice);
done();
}
catch (e) {
done(e);
}
});
});
it('clears the O365 Group recycle bin items when prompt is confirmed (debug)', (done) => {
const deleteStub = sinon.stub(request, 'delete').callsFake(() => Promise.resolve());
// Stub representing the get deleted items operation
sinon.stub(request, 'get').callsFake((opts) => {
if (opts.url === `https://graph.microsoft.com/v1.0/directory/deletedItems/Microsoft.Graph.Group?$filter=groupTypes/any(c:c+eq+'Unified')&$top=100`) {
return Promise.resolve({
"value": [
{
"id": "010d2f0a-0c17-4ec8-b694-e85bbe607013",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-07T13:58:01Z",
"description": "Team 1",
"displayName": "Team 1",
"groupTypes": [
"Unified"
],
"mail": "team_1@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_1",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_1@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-07T13:58:01Z",
"securityEnabled": false,
"visibility": "Private"
},
{
"id": "0157132c-bf82-48ff-99e4-b19a74950fe0",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-17T13:30:42Z",
"description": "Team 2",
"displayName": "Team 2",
"groupTypes": [
"Unified"
],
"mail": "team_2@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_2",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_2@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-17T13:30:42Z",
"securityEnabled": false,
"visibility": "Private"
},
{
"id": "269f3774-ec52-4ef7-a220-6940fb7b0325",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2017-12-17T13:30:42Z",
"description": "Team 3",
"displayName": "Team 3",
"groupTypes": [
"Unified"
],
"mail": "team_3@contoso.onmicrosoft.com",
"mailEnabled": true,
"mailNickname": "team_3",
"onPremisesLastSyncDateTime": null,
"onPremisesProvisioningErrors": [],
"onPremisesSecurityIdentifier": null,
"onPremisesSyncEnabled": null,
"preferredDataLocation": null,
"proxyAddresses": [
"SMTP:team_2@contoso.onmicrosoft.com"
],
"renewedDateTime": "2017-12-17T13:30:42Z",
"securityEnabled": false,
"visibility": "Private"
}
]
});
}
return Promise.reject('Invalid request');
});
sinonUtil.restore(Cli.prompt);
sinon.stub(Cli, 'prompt').callsFake((options: any, cb: (result: { continue: boolean }) => void) => {
cb({ continue: true });
});
command.action(logger, { options: { debug: true } }, () => {
try {
assert(deleteStub.calledThrice);
done();
}
catch (e) {
done(e);
}
});
});
it('supports debug mode', () => {
const options = command.options();
let containsOption = false;
options.forEach(o => {
if (o.option === '--debug') {
containsOption = true;
}
});
assert(containsOption);
});
it('supports specifying confirmation flag', () => {
const options = command.options();
let containsOption = false;
options.forEach(o => {
if (o.option.indexOf('--confirm') > -1) {
containsOption = true;
}
});
assert(containsOption);
});
}); | the_stack |
import {io, linalg, randomNormal, Tensor, zeros} from '@tensorflow/tfjs-core';
import * as tfl from './index';
// tslint:disable-next-line:max-line-length
import {describeMathCPUAndGPU, describeMathCPUAndWebGL2, expectTensorsClose} from './utils/test_utils';
import {version} from './version';
describeMathCPUAndGPU('LayersModel.save', () => {
class IOHandlerForTest implements io.IOHandler {
savedArtifacts: io.ModelArtifacts;
async save(modelArtifacts: io.ModelArtifacts): Promise<io.SaveResult> {
this.savedArtifacts = modelArtifacts;
return {modelArtifactsInfo: null};
}
}
class EmptyIOHandler implements io.IOHandler {}
it('Model artifacts contains meta-information: Sequential', async () => {
const model = tfl.sequential();
model.add(tfl.layers.dense({units: 3, inputShape: [5]}));
const handler = new IOHandlerForTest();
await model.save(handler);
expect(handler.savedArtifacts.format).toEqual('layers-model');
expect(handler.savedArtifacts.generatedBy)
.toEqual(`TensorFlow.js tfjs-layers v${version}`);
expect(handler.savedArtifacts.convertedBy).toEqual(null);
});
it('Model artifacts contains meta-information: Functional', async () => {
const input = tfl.input({shape: [5]});
const output =
tfl.layers.dense({units: 3}).apply(input) as tfl.SymbolicTensor;
const model = tfl.model({inputs: input, outputs: output});
const handler = new IOHandlerForTest();
await model.save(handler);
expect(handler.savedArtifacts.format).toEqual('layers-model');
expect(handler.savedArtifacts.generatedBy)
.toEqual(`TensorFlow.js tfjs-layers v${version}`);
expect(handler.savedArtifacts.convertedBy).toEqual(null);
});
it('Saving all weights succeeds', async () => {
const model = tfl.sequential();
model.add(tfl.layers.dense({units: 3, inputShape: [5]}));
const handler = new IOHandlerForTest();
await model.save(handler);
expect(handler.savedArtifacts.modelTopology)
.toEqual(model.toJSON(null, false));
expect(handler.savedArtifacts.weightSpecs.length).toEqual(2);
expect(handler.savedArtifacts.weightSpecs[0].name.indexOf('/kernel'))
.toBeGreaterThan(0);
expect(handler.savedArtifacts.weightSpecs[0].shape).toEqual([5, 3]);
expect(handler.savedArtifacts.weightSpecs[0].dtype).toEqual('float32');
expect(handler.savedArtifacts.weightSpecs[1].name.indexOf('/bias'))
.toBeGreaterThan(0);
expect(handler.savedArtifacts.weightSpecs[1].shape).toEqual([3]);
expect(handler.savedArtifacts.weightSpecs[1].dtype).toEqual('float32');
});
it('Saving only trainable weights succeeds', async () => {
const model = tfl.sequential();
model.add(tfl.layers.dense({units: 3, inputShape: [5], trainable: false}));
model.add(tfl.layers.dense({units: 2}));
const handler = new IOHandlerForTest();
await model.save(handler, {trainableOnly: true});
expect(handler.savedArtifacts.modelTopology)
.toEqual(model.toJSON(null, false));
// Verify that only the trainable weights (i.e., weights from the
// 2nd, trainable Dense layer) are saved.
expect(handler.savedArtifacts.weightSpecs.length).toEqual(2);
expect(handler.savedArtifacts.weightSpecs[0].name.indexOf('/kernel'))
.toBeGreaterThan(0);
expect(handler.savedArtifacts.weightSpecs[0].shape).toEqual([3, 2]);
expect(handler.savedArtifacts.weightSpecs[0].dtype).toEqual('float32');
expect(handler.savedArtifacts.weightSpecs[1].name.indexOf('/bias'))
.toBeGreaterThan(0);
expect(handler.savedArtifacts.weightSpecs[1].shape).toEqual([2]);
expect(handler.savedArtifacts.weightSpecs[1].dtype).toEqual('float32');
});
it('Saving to a handler without save method fails', async done => {
const model = tfl.sequential();
model.add(tfl.layers.dense({units: 3, inputShape: [5]}));
const handler = new EmptyIOHandler();
model.save(handler)
.then(saveResult => {
fail(
'Saving with an IOHandler without `save` succeeded ' +
'unexpectedly.');
})
.catch(err => {
expect(err.message)
.toEqual(
'LayersModel.save() cannot proceed because the IOHandler ' +
'provided does not have the `save` attribute defined.');
done();
});
});
});
describeMathCPUAndWebGL2('Save-load round trips', () => {
it('Sequential model, Local storage', async () => {
const model1 = tfl.sequential();
model1.add(
tfl.layers.dense({units: 2, inputShape: [2], activation: 'relu'}));
model1.add(tfl.layers.dense({units: 1, useBias: false}));
// Use a randomly generated model path to prevent collision.
const path = `testModel${new Date().getTime()}_${Math.random()}`;
// First save the model to local storage.
const modelURL = `localstorage://${path}`;
await model1.save(modelURL);
// Once the saving succeeds, load the model back.
const model2 = await tfl.loadLayersModel(modelURL);
// Verify that the topology of the model is correct.
expect(model2.toJSON(null, false)).toEqual(model1.toJSON(null, false));
// Check the equality of the two models' weights.
const weights1 = model1.getWeights();
const weights2 = model2.getWeights();
expect(weights2.length).toEqual(weights1.length);
for (let i = 0; i < weights1.length; ++i) {
expectTensorsClose(weights1[i], weights2[i]);
}
});
it('Functional model, IndexedDB', async () => {
const input = tfl.input({shape: [2, 2]});
const layer1 = tfl.layers.flatten().apply(input);
const layer2 =
tfl.layers.dense({units: 2}).apply(layer1) as tfl.SymbolicTensor;
const model1 = tfl.model({inputs: input, outputs: layer2});
// Use a randomly generated model path to prevent collision.
const path = `testModel${new Date().getTime()}_${Math.random()}`;
// First save the model to local storage.
const modelURL = `indexeddb://${path}`;
await model1.save(modelURL);
// Once the saving succeeds, load the model back.
const model2 = await tfl.loadLayersModel(modelURL);
// Verify that the topology of the model is correct.
expect(model2.toJSON(null, false)).toEqual(model1.toJSON(null, false));
// Check the equality of the two models' weights.
const weights1 = model1.getWeights();
const weights2 = model2.getWeights();
expect(weights2.length).toEqual(weights1.length);
for (let i = 0; i < weights1.length; ++i) {
expectTensorsClose(weights1[i], weights2[i]);
}
});
it('Call predict() and fit() after load: conv2d model', async () => {
const model = tfl.sequential();
model.add(tfl.layers.conv2d({
filters: 8,
kernelSize: 4,
inputShape: [28, 28, 1],
padding: 'same',
activation: 'relu'
}));
model.add(tfl.layers.maxPooling2d({
poolSize: 2,
padding: 'same',
}));
model.add(tfl.layers.flatten());
model.add(tfl.layers.dense({units: 1}));
const x = randomNormal([1, 28, 28, 1]);
const y = model.predict(x) as Tensor;
const path = `testModel${new Date().getTime()}_${Math.random()}`;
const url = `indexeddb://${path}`;
await model.save(url);
// Load the model back.
const modelPrime = await tfl.loadLayersModel(url);
// Call predict() on the loaded model and assert the result
// equals the original predict() result.
const yPrime = modelPrime.predict(x) as Tensor;
expectTensorsClose(y, yPrime);
// Call compile and fit() on the loaded model.
modelPrime.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const trainExamples = 10;
await modelPrime.fit(
randomNormal([trainExamples, 28, 28, 1]),
randomNormal([trainExamples, 1]), {epochs: 4});
});
it('Call predict() and fit() after load: conv1d model', async () => {
const model = tfl.sequential();
model.add(tfl.layers.conv1d({
filters: 8,
kernelSize: 4,
inputShape: [100, 1],
padding: 'same',
activation: 'relu'
}));
model.add(tfl.layers.maxPooling1d({
poolSize: 2,
padding: 'same',
}));
model.add(tfl.layers.flatten());
model.add(tfl.layers.dense({units: 1}));
const x = randomNormal([1, 100, 1]);
const y = model.predict(x) as Tensor;
const path = `testModel${new Date().getTime()}_${Math.random()}`;
const url = `indexeddb://${path}`;
await model.save(url);
// Load the model back.
const modelPrime = await tfl.loadLayersModel(url);
// Call predict() on the loaded model and assert the
// result equals the original predict() result.
const yPrime = modelPrime.predict(x) as Tensor;
expectTensorsClose(y, yPrime);
// Call compile and fit() on the loaded model.
modelPrime.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const trainExamples = 10;
await modelPrime.fit(
randomNormal([trainExamples, 100, 1]), randomNormal([trainExamples, 1]),
{epochs: 4});
});
it('Call predict() and fit() after load: Bidirectional LSTM', async () => {
const model = tfl.sequential();
const lstmUnits = 3;
const sequenceLength = 4;
const inputDims = 5;
model.add(tfl.layers.bidirectional({
layer: tfl.layers.lstm({units: lstmUnits}) as tfl.RNN,
mergeMode: 'concat',
inputShape: [sequenceLength, inputDims]
}));
const x = randomNormal([2, 4, 5]);
const y = model.predict(x) as Tensor;
const path = `testModel${new Date().getTime()}_${Math.random()}`;
const url = `indexeddb://${path}`;
await model.save(url);
const modelPrime = await tfl.loadLayersModel(url);
const yPrime = modelPrime.predict(x) as Tensor;
expectTensorsClose(y, yPrime);
// Call compile and fit() on the loaded model.
modelPrime.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const trainExamples = 2;
await modelPrime.fit(
randomNormal([trainExamples, sequenceLength, inputDims]),
randomNormal([trainExamples, lstmUnits * 2]), {epochs: 2});
});
it('Load model: Fast init w/ weights: Sequential & LSTM', async () => {
const model = tfl.sequential();
model.add(tfl.layers.lstm({
units: 2,
inputShape: [3, 4],
recurrentInitializer: 'orthogonal',
kernelInitializer: 'orthogonal',
biasInitializer: 'randomNormal',
}));
let savedArtifacts: io.ModelArtifacts;
await model.save(
io.withSaveHandler(async (artifacts: io.ModelArtifacts) => {
savedArtifacts = artifacts;
return {modelArtifactsInfo: null};
}));
const weights = model.getWeights();
const modelPrime = await tfl.loadLayersModel(io.fromMemory(savedArtifacts));
const weightsPrime = modelPrime.getWeights();
expect(weightsPrime.length).toEqual(weights.length);
for (let i = 0; i < weights.length; ++i) {
expectTensorsClose(weightsPrime[i], weights[i]);
}
});
it('Loading model: Fast init w/ weights: timeDistributed', async () => {
const model = tfl.sequential();
model.add(tfl.layers.timeDistributed({
inputShape: [3, 4],
layer: tfl.layers.dense(
{units: 4, kernelInitializer: 'orthogonal', useBias: false})
}));
let savedArtifacts: io.ModelArtifacts;
await model.save(
io.withSaveHandler(async (artifacts: io.ModelArtifacts) => {
savedArtifacts = artifacts;
return {modelArtifactsInfo: null};
}));
const weights = model.getWeights();
const modelPrime = await tfl.loadLayersModel(io.fromMemory(savedArtifacts));
const weightsPrime = modelPrime.getWeights();
expect(weightsPrime.length).toEqual(weights.length);
for (let i = 0; i < weights.length; ++i) {
expectTensorsClose(weightsPrime[i], weights[i]);
}
});
it('Loading model: Fast init w/ weights: bidirectional', async () => {
const model = tfl.sequential();
model.add(tfl.layers.bidirectional({
inputShape: [3, 4],
mergeMode: 'concat',
layer: tfl.layers.lstm({
units: 4,
kernelInitializer: 'orthogonal',
recurrentInitializer: 'orthogonal',
biasInitializer: 'glorotNormal'
}) as tfl.RNN
}));
let savedArtifacts: io.ModelArtifacts;
await model.save(
io.withSaveHandler(async (artifacts: io.ModelArtifacts) => {
savedArtifacts = artifacts;
return {modelArtifactsInfo: null};
}));
const weights = model.getWeights();
const modelPrime = await tfl.loadLayersModel(io.fromMemory(savedArtifacts));
const weightsPrime = modelPrime.getWeights();
expect(weightsPrime.length).toEqual(weights.length);
for (let i = 0; i < weights.length; ++i) {
expectTensorsClose(weightsPrime[i], weights[i]);
}
});
it('Loading model: Fast init w/ weights: functional model', async () => {
const input1 = tfl.input({shape: [3, 2]});
const input2 = tfl.input({shape: [3, 2]});
let y =
tfl.layers.concatenate().apply([input1, input2]) as tfl.SymbolicTensor;
y = tfl.layers
.lstm({
units: 4,
kernelInitializer: 'orthogonal',
recurrentInitializer: 'orthogonal',
biasInitializer: 'glorotNormal'
})
.apply(y) as tfl.SymbolicTensor;
const model = tfl.model({inputs: [input1, input2], outputs: y});
let savedArtifacts: io.ModelArtifacts;
await model.save(
io.withSaveHandler(async (artifacts: io.ModelArtifacts) => {
savedArtifacts = artifacts;
return {modelArtifactsInfo: null};
}));
const weights = model.getWeights();
const modelPrime = await tfl.loadLayersModel(io.fromMemory(savedArtifacts));
const weightsPrime = modelPrime.getWeights();
expect(weightsPrime.length).toEqual(weights.length);
for (let i = 0; i < weights.length; ++i) {
expectTensorsClose(weightsPrime[i], weights[i]);
}
});
it('modelFromJSON calls correct weight initializers', async () => {
const model = tfl.sequential();
model.add(tfl.layers.lstm({
units: 2,
inputShape: [3, 4],
recurrentInitializer: 'orthogonal',
kernelInitializer: 'orthogonal',
biasInitializer: 'randomNormal',
}));
const modelJSON = model.toJSON(null, false);
const gramSchmidtSpy = spyOn(linalg, 'gramSchmidt').and.callThrough();
const modelPrime =
await tfl.models.modelFromJSON({modelTopology: modelJSON});
// Make sure modelPrime builds.
modelPrime.predict(zeros([2, 3, 4]));
// Assert the orthogonal initializer has been called.
expect(gramSchmidtSpy).toHaveBeenCalled();
});
it('Partial non-strict load calls weight initializers', async () => {
const model = tfl.sequential();
model.add(tfl.layers.lstm({
units: 2,
inputShape: [3, 4],
recurrentInitializer: 'orthogonal',
kernelInitializer: 'orthogonal',
biasInitializer: 'randomNormal',
}));
let savedArtifacts: io.ModelArtifacts;
await model.save(
io.withSaveHandler(async (artifacts: io.ModelArtifacts) => {
savedArtifacts = artifacts;
return {modelArtifactsInfo: null};
}));
const weights = model.getWeights();
expect(savedArtifacts.weightSpecs.length).toEqual(3);
savedArtifacts.weightSpecs = savedArtifacts.weightSpecs.slice(0, 1);
const gramSchmidtSpy = spyOn(linalg, 'gramSchmidt').and.callThrough();
const strict = false;
const modelPrime =
await tfl.loadLayersModel(io.fromMemory(savedArtifacts), {strict});
const weightsPrime = modelPrime.getWeights();
expect(weightsPrime.length).toEqual(weights.length);
expectTensorsClose(weightsPrime[0], weights[0]);
// Assert the orthogonal initializer has been called.
expect(gramSchmidtSpy).toHaveBeenCalled();
});
it('loadLayersModel: non-strict load calls weight initializers', async () => {
const model = tfl.sequential();
model.add(tfl.layers.lstm({
units: 2,
inputShape: [3, 4],
recurrentInitializer: 'orthogonal',
kernelInitializer: 'orthogonal',
biasInitializer: 'randomNormal',
}));
let savedArtifacts: io.ModelArtifacts;
await model.save(
io.withSaveHandler(async (artifacts: io.ModelArtifacts) => {
savedArtifacts = artifacts;
return {modelArtifactsInfo: null};
}));
const weights = model.getWeights();
expect(savedArtifacts.weightSpecs.length).toEqual(3);
savedArtifacts.weightSpecs = savedArtifacts.weightSpecs.slice(0, 1);
const gramSchmidtSpy = spyOn(linalg, 'gramSchmidt').and.callThrough();
const strict = false;
const modelPrime =
await tfl.loadLayersModel(io.fromMemory(savedArtifacts), {strict});
const weightsPrime = modelPrime.getWeights();
expect(weightsPrime.length).toEqual(weights.length);
expectTensorsClose(weightsPrime[0], weights[0]);
// Assert the orthogonal initializer has been called.
expect(gramSchmidtSpy).toHaveBeenCalled();
});
it('Load model artifact with ndarray-format scalar objects', async () => {
// The following model config contains a scalar parameter serialized in the
// ndarray-style format: `{"type": "ndarray", "value": 6}`.
const modelJSON = JSON.stringify({
'class_name': 'Sequential',
'keras_version': '2.2.4',
'config': {
'layers': [
{
'class_name': 'Dense',
'config': {
'kernel_initializer': {
'class_name': 'VarianceScaling',
'config': {
'distribution': 'uniform',
'scale': 1.0,
'seed': null,
'mode': 'fan_avg'
}
},
'name': 'dense_1',
'kernel_constraint': null,
'bias_regularizer': null,
'bias_constraint': null,
'dtype': 'float32',
'activation': 'linear',
'trainable': true,
'kernel_regularizer': null,
'bias_initializer': {'class_name': 'Zeros', 'config': {}},
'units': 2,
'batch_input_shape': [null, 3],
'use_bias': true,
'activity_regularizer': null
}
},
{
'class_name': 'ReLU',
'config': {
'threshold': 0.0,
'max_value': {'type': 'ndarray', 'value': 6},
'trainable': true,
'name': 're_lu_1',
'negative_slope': 0.0
}
},
{
'class_name': 'Dense',
'config': {
'kernel_initializer': {
'class_name': 'VarianceScaling',
'config': {
'distribution': 'uniform',
'scale': 1.0,
'seed': null,
'mode': 'fan_avg'
}
},
'name': 'dense_2',
'kernel_constraint': null,
'bias_regularizer': null,
'bias_constraint': null,
'activation': 'linear',
'trainable': true,
'kernel_regularizer': null,
'bias_initializer': {'class_name': 'Zeros', 'config': {}},
'units': 1,
'use_bias': true,
'activity_regularizer': null
}
}
],
'name': 'sequential_1'
},
'backend': 'tensorflow'
});
const model =
await tfl.models.modelFromJSON({modelTopology: JSON.parse(modelJSON)});
expect(model.layers.length).toEqual(3);
expect(model.layers[1].getConfig().maxValue).toEqual(6);
const xs = randomNormal([5].concat(model.inputs[0].shape.slice(1)));
const ys = model.predict(xs) as Tensor;
expect(ys.shape).toEqual([5, 1]);
});
// TODO(cais): Test fast initialization of models consisting of
// StackedRNN layers.
}); | the_stack |
export type Map = {
name?: string;
category?: string;
author?: string;
data: string[];
};
export const fourfour: Map = {
name: '4x4',
category: '4x4',
data: [
'----',
'-wb-',
'-bw-',
'----'
]
};
export const sixsix: Map = {
name: '6x6',
category: '6x6',
data: [
'------',
'------',
'--wb--',
'--bw--',
'------',
'------'
]
};
export const roundedSixsix: Map = {
name: '6x6 rounded',
category: '6x6',
author: 'syuilo',
data: [
' ---- ',
'------',
'--wb--',
'--bw--',
'------',
' ---- '
]
};
export const roundedSixsix2: Map = {
name: '6x6 rounded 2',
category: '6x6',
author: 'syuilo',
data: [
' -- ',
' ---- ',
'--wb--',
'--bw--',
' ---- ',
' -- '
]
};
export const eighteight: Map = {
name: '8x8',
category: '8x8',
data: [
'--------',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
'--------'
]
};
export const eighteightH1: Map = {
name: '8x8 handicap 1',
category: '8x8',
data: [
'b-------',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
'--------'
]
};
export const eighteightH2: Map = {
name: '8x8 handicap 2',
category: '8x8',
data: [
'b-------',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
'-------b'
]
};
export const eighteightH3: Map = {
name: '8x8 handicap 3',
category: '8x8',
data: [
'b------b',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
'-------b'
]
};
export const eighteightH4: Map = {
name: '8x8 handicap 4',
category: '8x8',
data: [
'b------b',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
'b------b'
]
};
export const eighteightH12: Map = {
name: '8x8 handicap 12',
category: '8x8',
data: [
'bb----bb',
'b------b',
'--------',
'---wb---',
'---bw---',
'--------',
'b------b',
'bb----bb'
]
};
export const eighteightH16: Map = {
name: '8x8 handicap 16',
category: '8x8',
data: [
'bbb---bb',
'b------b',
'-------b',
'---wb---',
'---bw---',
'b-------',
'b------b',
'bb---bbb'
]
};
export const eighteightH20: Map = {
name: '8x8 handicap 20',
category: '8x8',
data: [
'bbb--bbb',
'b------b',
'b------b',
'---wb---',
'---bw---',
'b------b',
'b------b',
'bbb---bb'
]
};
export const eighteightH28: Map = {
name: '8x8 handicap 28',
category: '8x8',
data: [
'bbbbbbbb',
'b------b',
'b------b',
'b--wb--b',
'b--bw--b',
'b------b',
'b------b',
'bbbbbbbb'
]
};
export const roundedEighteight: Map = {
name: '8x8 rounded',
category: '8x8',
author: 'syuilo',
data: [
' ------ ',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
' ------ '
]
};
export const roundedEighteight2: Map = {
name: '8x8 rounded 2',
category: '8x8',
author: 'syuilo',
data: [
' ---- ',
' ------ ',
'--------',
'---wb---',
'---bw---',
'--------',
' ------ ',
' ---- '
]
};
export const roundedEighteight3: Map = {
name: '8x8 rounded 3',
category: '8x8',
author: 'syuilo',
data: [
' -- ',
' ---- ',
' ------ ',
'---wb---',
'---bw---',
' ------ ',
' ---- ',
' -- '
]
};
export const eighteightWithNotch: Map = {
name: '8x8 with notch',
category: '8x8',
author: 'syuilo',
data: [
'--- ---',
'--------',
'--------',
' --wb-- ',
' --bw-- ',
'--------',
'--------',
'--- ---'
]
};
export const eighteightWithSomeHoles: Map = {
name: '8x8 with some holes',
category: '8x8',
author: 'syuilo',
data: [
'--- ----',
'----- --',
'-- -----',
'---wb---',
'---bw- -',
' -------',
'--- ----',
'--------'
]
};
export const circle: Map = {
name: 'Circle',
category: '8x8',
author: 'syuilo',
data: [
' -- ',
' ------ ',
' ------ ',
'---wb---',
'---bw---',
' ------ ',
' ------ ',
' -- '
]
};
export const smile: Map = {
name: 'Smile',
category: '8x8',
author: 'syuilo',
data: [
' ------ ',
'--------',
'-- -- --',
'---wb---',
'-- bw --',
'--- ---',
'--------',
' ------ '
]
};
export const window: Map = {
name: 'Window',
category: '8x8',
author: 'syuilo',
data: [
'--------',
'- -- -',
'- -- -',
'---wb---',
'---bw---',
'- -- -',
'- -- -',
'--------'
]
};
export const reserved: Map = {
name: 'Reserved',
category: '8x8',
author: 'Aya',
data: [
'w------b',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
'b------w'
]
};
export const x: Map = {
name: 'X',
category: '8x8',
author: 'Aya',
data: [
'w------b',
'-w----b-',
'--w--b--',
'---wb---',
'---bw---',
'--b--w--',
'-b----w-',
'b------w'
]
};
export const parallel: Map = {
name: 'Parallel',
category: '8x8',
author: 'Aya',
data: [
'--------',
'--------',
'--------',
'---bb---',
'---ww---',
'--------',
'--------',
'--------'
]
};
export const lackOfBlack: Map = {
name: 'Lack of Black',
category: '8x8',
data: [
'--------',
'--------',
'--------',
'---w----',
'---bw---',
'--------',
'--------',
'--------'
]
};
export const squareParty: Map = {
name: 'Square Party',
category: '8x8',
author: 'syuilo',
data: [
'--------',
'-wwwbbb-',
'-w-wb-b-',
'-wwwbbb-',
'-bbbwww-',
'-b-bw-w-',
'-bbbwww-',
'--------'
]
};
export const minesweeper: Map = {
name: 'Minesweeper',
category: '8x8',
author: 'syuilo',
data: [
'b-b--w-w',
'-w-wb-b-',
'w-b--w-b',
'-b-wb-w-',
'-w-bw-b-',
'b-w--b-w',
'-b-bw-w-',
'w-w--b-b'
]
};
export const tenthtenth: Map = {
name: '10x10',
category: '10x10',
data: [
'----------',
'----------',
'----------',
'----------',
'----wb----',
'----bw----',
'----------',
'----------',
'----------',
'----------'
]
};
export const hole: Map = {
name: 'The Hole',
category: '10x10',
author: 'syuilo',
data: [
'----------',
'----------',
'--wb--wb--',
'--bw--bw--',
'---- ----',
'---- ----',
'--wb--wb--',
'--bw--bw--',
'----------',
'----------'
]
};
export const grid: Map = {
name: 'Grid',
category: '10x10',
author: 'syuilo',
data: [
'----------',
'- - -- - -',
'----------',
'- - -- - -',
'----wb----',
'----bw----',
'- - -- - -',
'----------',
'- - -- - -',
'----------'
]
};
export const cross: Map = {
name: 'Cross',
category: '10x10',
author: 'Aya',
data: [
' ---- ',
' ---- ',
' ---- ',
'----------',
'----wb----',
'----bw----',
'----------',
' ---- ',
' ---- ',
' ---- '
]
};
export const charX: Map = {
name: 'Char X',
category: '10x10',
author: 'syuilo',
data: [
'--- ---',
'---- ----',
'----------',
' -------- ',
' --wb-- ',
' --bw-- ',
' -------- ',
'----------',
'---- ----',
'--- ---'
]
};
export const charY: Map = {
name: 'Char Y',
category: '10x10',
author: 'syuilo',
data: [
'--- ---',
'---- ----',
'----------',
' -------- ',
' --wb-- ',
' --bw-- ',
' ------ ',
' ------ ',
' ------ ',
' ------ '
]
};
export const walls: Map = {
name: 'Walls',
category: '10x10',
author: 'Aya',
data: [
' bbbbbbbb ',
'w--------w',
'w--------w',
'w--------w',
'w---wb---w',
'w---bw---w',
'w--------w',
'w--------w',
'w--------w',
' bbbbbbbb '
]
};
export const cpu: Map = {
name: 'CPU',
category: '10x10',
author: 'syuilo',
data: [
' b b b b ',
'w--------w',
' -------- ',
'w--------w',
' ---wb--- ',
' ---bw--- ',
'w--------w',
' -------- ',
'w--------w',
' b b b b '
]
};
export const checker: Map = {
name: 'Checker',
category: '10x10',
author: 'Aya',
data: [
'----------',
'----------',
'----------',
'---wbwb---',
'---bwbw---',
'---wbwb---',
'---bwbw---',
'----------',
'----------',
'----------'
]
};
export const japaneseCurry: Map = {
name: 'Japanese curry',
category: '10x10',
author: 'syuilo',
data: [
'w-b-b-b-b-',
'-w-b-b-b-b',
'w-w-b-b-b-',
'-w-w-b-b-b',
'w-w-wwb-b-',
'-w-wbb-b-b',
'w-w-w-b-b-',
'-w-w-w-b-b',
'w-w-w-w-b-',
'-w-w-w-w-b'
]
};
export const mosaic: Map = {
name: 'Mosaic',
category: '10x10',
author: 'syuilo',
data: [
'- - - - - ',
' - - - - -',
'- - - - - ',
' - w w - -',
'- - b b - ',
' - w w - -',
'- - b b - ',
' - - - - -',
'- - - - - ',
' - - - - -',
]
};
export const arena: Map = {
name: 'Arena',
category: '10x10',
author: 'syuilo',
data: [
'- - -- - -',
' - - - - ',
'- ------ -',
' -------- ',
'- --wb-- -',
'- --bw-- -',
' -------- ',
'- ------ -',
' - - - - ',
'- - -- - -'
]
};
export const reactor: Map = {
name: 'Reactor',
category: '10x10',
author: 'syuilo',
data: [
'-w------b-',
'b- - - -w',
'- --wb-- -',
'---b w---',
'- b wb w -',
'- w bw b -',
'---w b---',
'- --bw-- -',
'w- - - -b',
'-b------w-'
]
};
export const sixeight: Map = {
name: '6x8',
category: 'Special',
data: [
'------',
'------',
'------',
'--wb--',
'--bw--',
'------',
'------',
'------'
]
};
export const spark: Map = {
name: 'Spark',
category: 'Special',
author: 'syuilo',
data: [
' - - ',
'----------',
' -------- ',
' -------- ',
' ---wb--- ',
' ---bw--- ',
' -------- ',
' -------- ',
'----------',
' - - '
]
};
export const islands: Map = {
name: 'Islands',
category: 'Special',
author: 'syuilo',
data: [
'-------- ',
'---wb--- ',
'---bw--- ',
'-------- ',
' - - ',
' - - ',
' --------',
' --------',
' --------',
' --------'
]
};
export const galaxy: Map = {
name: 'Galaxy',
category: 'Special',
author: 'syuilo',
data: [
' ------ ',
' --www--- ',
' ------w--- ',
'---bbb--w---',
'--b---b-w-b-',
'-b--wwb-w-b-',
'-b-w-bww--b-',
'-b-w-b---b--',
'---w--bbb---',
' ---w------ ',
' ---www-- ',
' ------ '
]
};
export const triangle: Map = {
name: 'Triangle',
category: 'Special',
author: 'syuilo',
data: [
' -- ',
' -- ',
' ---- ',
' ---- ',
' --wb-- ',
' --bw-- ',
' -------- ',
' -------- ',
'----------',
'----------'
]
};
export const iphonex: Map = {
name: 'iPhone X',
category: 'Special',
author: 'syuilo',
data: [
' -- -- ',
'--------',
'--------',
'--------',
'--------',
'---wb---',
'---bw---',
'--------',
'--------',
'--------',
'--------',
' ------ '
]
};
export const dealWithIt: Map = {
name: 'Deal with it!',
category: 'Special',
author: 'syuilo',
data: [
'------------',
'--w-b-------',
' --b-w------',
' --w-b---- ',
' ------- '
]
};
export const experiment: Map = {
name: 'Let\'s experiment',
category: 'Special',
author: 'syuilo',
data: [
' ------------ ',
'------wb------',
'------bw------',
'--------------',
' - - ',
'------ ------',
'bbbbbb wwwwww',
'bbbbbb wwwwww',
'bbbbbb wwwwww',
'bbbbbb wwwwww',
'wwwwww bbbbbb'
]
};
export const bigBoard: Map = {
name: 'Big board',
category: 'Special',
data: [
'----------------',
'----------------',
'----------------',
'----------------',
'----------------',
'----------------',
'----------------',
'-------wb-------',
'-------bw-------',
'----------------',
'----------------',
'----------------',
'----------------',
'----------------',
'----------------',
'----------------'
]
};
export const twoBoard: Map = {
name: 'Two board',
category: 'Special',
author: 'Aya',
data: [
'-------- --------',
'-------- --------',
'-------- --------',
'---wb--- ---wb---',
'---bw--- ---bw---',
'-------- --------',
'-------- --------',
'-------- --------'
]
};
export const test1: Map = {
name: 'Test1',
category: 'Test',
data: [
'--------',
'---wb---',
'---bw---',
'--------'
]
};
export const test2: Map = {
name: 'Test2',
category: 'Test',
data: [
'------',
'------',
'-b--w-',
'-w--b-',
'-w--b-'
]
};
export const test3: Map = {
name: 'Test3',
category: 'Test',
data: [
'-w-',
'--w',
'w--',
'-w-',
'--w',
'w--',
'-w-',
'--w',
'w--',
'-w-',
'---',
'b--',
]
};
export const test4: Map = {
name: 'Test4',
category: 'Test',
data: [
'-w--b-',
'-w--b-',
'------',
'-w--b-',
'-w--b-'
]
};
// https://misskey.xyz/games/reversi/5aaabf7fe126e10b5216ea09 64
export const test5: Map = {
name: 'Test5',
category: 'Test',
data: [
'--wwwwww--',
'--wwwbwwww',
'-bwwbwbwww',
'-bwwwbwbww',
'-bwwbwbwbw',
'-bwbwbwb-w',
'bwbwwbbb-w',
'w-wbbbbb--',
'--w-b-w---',
'----------'
]
}; | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class ComprehendMedical extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: ComprehendMedical.Types.ClientConfiguration)
config: Config & ComprehendMedical.Types.ClientConfiguration;
/**
* Gets the properties associated with a medical entities detection job. Use this operation to get the status of a detection job.
*/
describeEntitiesDetectionV2Job(params: ComprehendMedical.Types.DescribeEntitiesDetectionV2JobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeEntitiesDetectionV2JobResponse) => void): Request<ComprehendMedical.Types.DescribeEntitiesDetectionV2JobResponse, AWSError>;
/**
* Gets the properties associated with a medical entities detection job. Use this operation to get the status of a detection job.
*/
describeEntitiesDetectionV2Job(callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeEntitiesDetectionV2JobResponse) => void): Request<ComprehendMedical.Types.DescribeEntitiesDetectionV2JobResponse, AWSError>;
/**
* Gets the properties associated with an InferICD10CM job. Use this operation to get the status of an inference job.
*/
describeICD10CMInferenceJob(params: ComprehendMedical.Types.DescribeICD10CMInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeICD10CMInferenceJobResponse) => void): Request<ComprehendMedical.Types.DescribeICD10CMInferenceJobResponse, AWSError>;
/**
* Gets the properties associated with an InferICD10CM job. Use this operation to get the status of an inference job.
*/
describeICD10CMInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeICD10CMInferenceJobResponse) => void): Request<ComprehendMedical.Types.DescribeICD10CMInferenceJobResponse, AWSError>;
/**
* Gets the properties associated with a protected health information (PHI) detection job. Use this operation to get the status of a detection job.
*/
describePHIDetectionJob(params: ComprehendMedical.Types.DescribePHIDetectionJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.DescribePHIDetectionJobResponse) => void): Request<ComprehendMedical.Types.DescribePHIDetectionJobResponse, AWSError>;
/**
* Gets the properties associated with a protected health information (PHI) detection job. Use this operation to get the status of a detection job.
*/
describePHIDetectionJob(callback?: (err: AWSError, data: ComprehendMedical.Types.DescribePHIDetectionJobResponse) => void): Request<ComprehendMedical.Types.DescribePHIDetectionJobResponse, AWSError>;
/**
* Gets the properties associated with an InferRxNorm job. Use this operation to get the status of an inference job.
*/
describeRxNormInferenceJob(params: ComprehendMedical.Types.DescribeRxNormInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeRxNormInferenceJobResponse) => void): Request<ComprehendMedical.Types.DescribeRxNormInferenceJobResponse, AWSError>;
/**
* Gets the properties associated with an InferRxNorm job. Use this operation to get the status of an inference job.
*/
describeRxNormInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeRxNormInferenceJobResponse) => void): Request<ComprehendMedical.Types.DescribeRxNormInferenceJobResponse, AWSError>;
/**
* Gets the properties associated with an InferSNOMEDCT job. Use this operation to get the status of an inference job.
*/
describeSNOMEDCTInferenceJob(params: ComprehendMedical.Types.DescribeSNOMEDCTInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeSNOMEDCTInferenceJobResponse) => void): Request<ComprehendMedical.Types.DescribeSNOMEDCTInferenceJobResponse, AWSError>;
/**
* Gets the properties associated with an InferSNOMEDCT job. Use this operation to get the status of an inference job.
*/
describeSNOMEDCTInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.DescribeSNOMEDCTInferenceJobResponse) => void): Request<ComprehendMedical.Types.DescribeSNOMEDCTInferenceJobResponse, AWSError>;
/**
* The DetectEntities operation is deprecated. You should use the DetectEntitiesV2 operation instead. Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information .
*/
detectEntities(params: ComprehendMedical.Types.DetectEntitiesRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.DetectEntitiesResponse) => void): Request<ComprehendMedical.Types.DetectEntitiesResponse, AWSError>;
/**
* The DetectEntities operation is deprecated. You should use the DetectEntitiesV2 operation instead. Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information .
*/
detectEntities(callback?: (err: AWSError, data: ComprehendMedical.Types.DetectEntitiesResponse) => void): Request<ComprehendMedical.Types.DetectEntitiesResponse, AWSError>;
/**
* Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information. Amazon Comprehend Medical only detects medical entities in English language texts. The DetectEntitiesV2 operation replaces the DetectEntities operation. This new action uses a different model for determining the entities in your medical text and changes the way that some entities are returned in the output. You should use the DetectEntitiesV2 operation in all new applications. The DetectEntitiesV2 operation returns the Acuity and Direction entities as attributes instead of types.
*/
detectEntitiesV2(params: ComprehendMedical.Types.DetectEntitiesV2Request, callback?: (err: AWSError, data: ComprehendMedical.Types.DetectEntitiesV2Response) => void): Request<ComprehendMedical.Types.DetectEntitiesV2Response, AWSError>;
/**
* Inspects the clinical text for a variety of medical entities and returns specific information about them such as entity category, location, and confidence score on that information. Amazon Comprehend Medical only detects medical entities in English language texts. The DetectEntitiesV2 operation replaces the DetectEntities operation. This new action uses a different model for determining the entities in your medical text and changes the way that some entities are returned in the output. You should use the DetectEntitiesV2 operation in all new applications. The DetectEntitiesV2 operation returns the Acuity and Direction entities as attributes instead of types.
*/
detectEntitiesV2(callback?: (err: AWSError, data: ComprehendMedical.Types.DetectEntitiesV2Response) => void): Request<ComprehendMedical.Types.DetectEntitiesV2Response, AWSError>;
/**
* Inspects the clinical text for protected health information (PHI) entities and returns the entity category, location, and confidence score for each entity. Amazon Comprehend Medical only detects entities in English language texts.
*/
detectPHI(params: ComprehendMedical.Types.DetectPHIRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.DetectPHIResponse) => void): Request<ComprehendMedical.Types.DetectPHIResponse, AWSError>;
/**
* Inspects the clinical text for protected health information (PHI) entities and returns the entity category, location, and confidence score for each entity. Amazon Comprehend Medical only detects entities in English language texts.
*/
detectPHI(callback?: (err: AWSError, data: ComprehendMedical.Types.DetectPHIResponse) => void): Request<ComprehendMedical.Types.DetectPHIResponse, AWSError>;
/**
* InferICD10CM detects medical conditions as entities listed in a patient record and links those entities to normalized concept identifiers in the ICD-10-CM knowledge base from the Centers for Disease Control. Amazon Comprehend Medical only detects medical entities in English language texts.
*/
inferICD10CM(params: ComprehendMedical.Types.InferICD10CMRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.InferICD10CMResponse) => void): Request<ComprehendMedical.Types.InferICD10CMResponse, AWSError>;
/**
* InferICD10CM detects medical conditions as entities listed in a patient record and links those entities to normalized concept identifiers in the ICD-10-CM knowledge base from the Centers for Disease Control. Amazon Comprehend Medical only detects medical entities in English language texts.
*/
inferICD10CM(callback?: (err: AWSError, data: ComprehendMedical.Types.InferICD10CMResponse) => void): Request<ComprehendMedical.Types.InferICD10CMResponse, AWSError>;
/**
* InferRxNorm detects medications as entities listed in a patient record and links to the normalized concept identifiers in the RxNorm database from the National Library of Medicine. Amazon Comprehend Medical only detects medical entities in English language texts.
*/
inferRxNorm(params: ComprehendMedical.Types.InferRxNormRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.InferRxNormResponse) => void): Request<ComprehendMedical.Types.InferRxNormResponse, AWSError>;
/**
* InferRxNorm detects medications as entities listed in a patient record and links to the normalized concept identifiers in the RxNorm database from the National Library of Medicine. Amazon Comprehend Medical only detects medical entities in English language texts.
*/
inferRxNorm(callback?: (err: AWSError, data: ComprehendMedical.Types.InferRxNormResponse) => void): Request<ComprehendMedical.Types.InferRxNormResponse, AWSError>;
/**
* InferSNOMEDCT detects possible medical concepts as entities and links them to codes from the Systematized Nomenclature of Medicine, Clinical Terms (SNOMED-CT) ontology
*/
inferSNOMEDCT(params: ComprehendMedical.Types.InferSNOMEDCTRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.InferSNOMEDCTResponse) => void): Request<ComprehendMedical.Types.InferSNOMEDCTResponse, AWSError>;
/**
* InferSNOMEDCT detects possible medical concepts as entities and links them to codes from the Systematized Nomenclature of Medicine, Clinical Terms (SNOMED-CT) ontology
*/
inferSNOMEDCT(callback?: (err: AWSError, data: ComprehendMedical.Types.InferSNOMEDCTResponse) => void): Request<ComprehendMedical.Types.InferSNOMEDCTResponse, AWSError>;
/**
* Gets a list of medical entity detection jobs that you have submitted.
*/
listEntitiesDetectionV2Jobs(params: ComprehendMedical.Types.ListEntitiesDetectionV2JobsRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.ListEntitiesDetectionV2JobsResponse) => void): Request<ComprehendMedical.Types.ListEntitiesDetectionV2JobsResponse, AWSError>;
/**
* Gets a list of medical entity detection jobs that you have submitted.
*/
listEntitiesDetectionV2Jobs(callback?: (err: AWSError, data: ComprehendMedical.Types.ListEntitiesDetectionV2JobsResponse) => void): Request<ComprehendMedical.Types.ListEntitiesDetectionV2JobsResponse, AWSError>;
/**
* Gets a list of InferICD10CM jobs that you have submitted.
*/
listICD10CMInferenceJobs(params: ComprehendMedical.Types.ListICD10CMInferenceJobsRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.ListICD10CMInferenceJobsResponse) => void): Request<ComprehendMedical.Types.ListICD10CMInferenceJobsResponse, AWSError>;
/**
* Gets a list of InferICD10CM jobs that you have submitted.
*/
listICD10CMInferenceJobs(callback?: (err: AWSError, data: ComprehendMedical.Types.ListICD10CMInferenceJobsResponse) => void): Request<ComprehendMedical.Types.ListICD10CMInferenceJobsResponse, AWSError>;
/**
* Gets a list of protected health information (PHI) detection jobs that you have submitted.
*/
listPHIDetectionJobs(params: ComprehendMedical.Types.ListPHIDetectionJobsRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.ListPHIDetectionJobsResponse) => void): Request<ComprehendMedical.Types.ListPHIDetectionJobsResponse, AWSError>;
/**
* Gets a list of protected health information (PHI) detection jobs that you have submitted.
*/
listPHIDetectionJobs(callback?: (err: AWSError, data: ComprehendMedical.Types.ListPHIDetectionJobsResponse) => void): Request<ComprehendMedical.Types.ListPHIDetectionJobsResponse, AWSError>;
/**
* Gets a list of InferRxNorm jobs that you have submitted.
*/
listRxNormInferenceJobs(params: ComprehendMedical.Types.ListRxNormInferenceJobsRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.ListRxNormInferenceJobsResponse) => void): Request<ComprehendMedical.Types.ListRxNormInferenceJobsResponse, AWSError>;
/**
* Gets a list of InferRxNorm jobs that you have submitted.
*/
listRxNormInferenceJobs(callback?: (err: AWSError, data: ComprehendMedical.Types.ListRxNormInferenceJobsResponse) => void): Request<ComprehendMedical.Types.ListRxNormInferenceJobsResponse, AWSError>;
/**
* Gets a list of InferSNOMEDCT jobs a user has submitted.
*/
listSNOMEDCTInferenceJobs(params: ComprehendMedical.Types.ListSNOMEDCTInferenceJobsRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.ListSNOMEDCTInferenceJobsResponse) => void): Request<ComprehendMedical.Types.ListSNOMEDCTInferenceJobsResponse, AWSError>;
/**
* Gets a list of InferSNOMEDCT jobs a user has submitted.
*/
listSNOMEDCTInferenceJobs(callback?: (err: AWSError, data: ComprehendMedical.Types.ListSNOMEDCTInferenceJobsResponse) => void): Request<ComprehendMedical.Types.ListSNOMEDCTInferenceJobsResponse, AWSError>;
/**
* Starts an asynchronous medical entity detection job for a collection of documents. Use the DescribeEntitiesDetectionV2Job operation to track the status of a job.
*/
startEntitiesDetectionV2Job(params: ComprehendMedical.Types.StartEntitiesDetectionV2JobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StartEntitiesDetectionV2JobResponse) => void): Request<ComprehendMedical.Types.StartEntitiesDetectionV2JobResponse, AWSError>;
/**
* Starts an asynchronous medical entity detection job for a collection of documents. Use the DescribeEntitiesDetectionV2Job operation to track the status of a job.
*/
startEntitiesDetectionV2Job(callback?: (err: AWSError, data: ComprehendMedical.Types.StartEntitiesDetectionV2JobResponse) => void): Request<ComprehendMedical.Types.StartEntitiesDetectionV2JobResponse, AWSError>;
/**
* Starts an asynchronous job to detect medical conditions and link them to the ICD-10-CM ontology. Use the DescribeICD10CMInferenceJob operation to track the status of a job.
*/
startICD10CMInferenceJob(params: ComprehendMedical.Types.StartICD10CMInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StartICD10CMInferenceJobResponse) => void): Request<ComprehendMedical.Types.StartICD10CMInferenceJobResponse, AWSError>;
/**
* Starts an asynchronous job to detect medical conditions and link them to the ICD-10-CM ontology. Use the DescribeICD10CMInferenceJob operation to track the status of a job.
*/
startICD10CMInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StartICD10CMInferenceJobResponse) => void): Request<ComprehendMedical.Types.StartICD10CMInferenceJobResponse, AWSError>;
/**
* Starts an asynchronous job to detect protected health information (PHI). Use the DescribePHIDetectionJob operation to track the status of a job.
*/
startPHIDetectionJob(params: ComprehendMedical.Types.StartPHIDetectionJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StartPHIDetectionJobResponse) => void): Request<ComprehendMedical.Types.StartPHIDetectionJobResponse, AWSError>;
/**
* Starts an asynchronous job to detect protected health information (PHI). Use the DescribePHIDetectionJob operation to track the status of a job.
*/
startPHIDetectionJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StartPHIDetectionJobResponse) => void): Request<ComprehendMedical.Types.StartPHIDetectionJobResponse, AWSError>;
/**
* Starts an asynchronous job to detect medication entities and link them to the RxNorm ontology. Use the DescribeRxNormInferenceJob operation to track the status of a job.
*/
startRxNormInferenceJob(params: ComprehendMedical.Types.StartRxNormInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StartRxNormInferenceJobResponse) => void): Request<ComprehendMedical.Types.StartRxNormInferenceJobResponse, AWSError>;
/**
* Starts an asynchronous job to detect medication entities and link them to the RxNorm ontology. Use the DescribeRxNormInferenceJob operation to track the status of a job.
*/
startRxNormInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StartRxNormInferenceJobResponse) => void): Request<ComprehendMedical.Types.StartRxNormInferenceJobResponse, AWSError>;
/**
* Starts an asynchronous job to detect medical concepts and link them to the SNOMED-CT ontology. Use the DescribeSNOMEDCTInferenceJob operation to track the status of a job.
*/
startSNOMEDCTInferenceJob(params: ComprehendMedical.Types.StartSNOMEDCTInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StartSNOMEDCTInferenceJobResponse) => void): Request<ComprehendMedical.Types.StartSNOMEDCTInferenceJobResponse, AWSError>;
/**
* Starts an asynchronous job to detect medical concepts and link them to the SNOMED-CT ontology. Use the DescribeSNOMEDCTInferenceJob operation to track the status of a job.
*/
startSNOMEDCTInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StartSNOMEDCTInferenceJobResponse) => void): Request<ComprehendMedical.Types.StartSNOMEDCTInferenceJobResponse, AWSError>;
/**
* Stops a medical entities detection job in progress.
*/
stopEntitiesDetectionV2Job(params: ComprehendMedical.Types.StopEntitiesDetectionV2JobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StopEntitiesDetectionV2JobResponse) => void): Request<ComprehendMedical.Types.StopEntitiesDetectionV2JobResponse, AWSError>;
/**
* Stops a medical entities detection job in progress.
*/
stopEntitiesDetectionV2Job(callback?: (err: AWSError, data: ComprehendMedical.Types.StopEntitiesDetectionV2JobResponse) => void): Request<ComprehendMedical.Types.StopEntitiesDetectionV2JobResponse, AWSError>;
/**
* Stops an InferICD10CM inference job in progress.
*/
stopICD10CMInferenceJob(params: ComprehendMedical.Types.StopICD10CMInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StopICD10CMInferenceJobResponse) => void): Request<ComprehendMedical.Types.StopICD10CMInferenceJobResponse, AWSError>;
/**
* Stops an InferICD10CM inference job in progress.
*/
stopICD10CMInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StopICD10CMInferenceJobResponse) => void): Request<ComprehendMedical.Types.StopICD10CMInferenceJobResponse, AWSError>;
/**
* Stops a protected health information (PHI) detection job in progress.
*/
stopPHIDetectionJob(params: ComprehendMedical.Types.StopPHIDetectionJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StopPHIDetectionJobResponse) => void): Request<ComprehendMedical.Types.StopPHIDetectionJobResponse, AWSError>;
/**
* Stops a protected health information (PHI) detection job in progress.
*/
stopPHIDetectionJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StopPHIDetectionJobResponse) => void): Request<ComprehendMedical.Types.StopPHIDetectionJobResponse, AWSError>;
/**
* Stops an InferRxNorm inference job in progress.
*/
stopRxNormInferenceJob(params: ComprehendMedical.Types.StopRxNormInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StopRxNormInferenceJobResponse) => void): Request<ComprehendMedical.Types.StopRxNormInferenceJobResponse, AWSError>;
/**
* Stops an InferRxNorm inference job in progress.
*/
stopRxNormInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StopRxNormInferenceJobResponse) => void): Request<ComprehendMedical.Types.StopRxNormInferenceJobResponse, AWSError>;
/**
* Stops an InferSNOMEDCT inference job in progress.
*/
stopSNOMEDCTInferenceJob(params: ComprehendMedical.Types.StopSNOMEDCTInferenceJobRequest, callback?: (err: AWSError, data: ComprehendMedical.Types.StopSNOMEDCTInferenceJobResponse) => void): Request<ComprehendMedical.Types.StopSNOMEDCTInferenceJobResponse, AWSError>;
/**
* Stops an InferSNOMEDCT inference job in progress.
*/
stopSNOMEDCTInferenceJob(callback?: (err: AWSError, data: ComprehendMedical.Types.StopSNOMEDCTInferenceJobResponse) => void): Request<ComprehendMedical.Types.StopSNOMEDCTInferenceJobResponse, AWSError>;
}
declare namespace ComprehendMedical {
export type AnyLengthString = string;
export interface Attribute {
/**
* The type of attribute.
*/
Type?: EntitySubType;
/**
* The level of confidence that Comprehend Medical; has that the segment of text is correctly recognized as an attribute.
*/
Score?: Float;
/**
* The level of confidence that Comprehend Medical; has that this attribute is correctly related to this entity.
*/
RelationshipScore?: Float;
/**
* The type of relationship between the entity and attribute. Type for the relationship is OVERLAP, indicating that the entity occurred at the same time as the Date_Expression.
*/
RelationshipType?: RelationshipType;
/**
* The numeric identifier for this attribute. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* The segment of input text extracted as this attribute.
*/
Text?: String;
/**
* The category of attribute.
*/
Category?: EntityType;
/**
* Contextual information for this attribute.
*/
Traits?: TraitList;
}
export type AttributeList = Attribute[];
export type AttributeName = "SIGN"|"SYMPTOM"|"DIAGNOSIS"|"NEGATION"|string;
export type BoundedLengthString = string;
export interface Characters {
/**
* The number of characters present in the input text document as processed by Comprehend Medical.
*/
OriginalTextCharacters?: Integer;
}
export type ClientRequestTokenString = string;
export interface ComprehendMedicalAsyncJobFilter {
/**
* Filters on the name of the job.
*/
JobName?: JobName;
/**
* Filters the list of jobs based on job status. Returns only jobs with the specified status.
*/
JobStatus?: JobStatus;
/**
* Filters the list of jobs based on the time that the job was submitted for processing. Returns only jobs submitted before the specified time. Jobs are returned in ascending order, oldest to newest.
*/
SubmitTimeBefore?: Timestamp;
/**
* Filters the list of jobs based on the time that the job was submitted for processing. Returns only jobs submitted after the specified time. Jobs are returned in descending order, newest to oldest.
*/
SubmitTimeAfter?: Timestamp;
}
export interface ComprehendMedicalAsyncJobProperties {
/**
* The identifier assigned to the detection job.
*/
JobId?: JobId;
/**
* The name that you assigned to the detection job.
*/
JobName?: JobName;
/**
* The current status of the detection job. If the status is FAILED, the Message field shows the reason for the failure.
*/
JobStatus?: JobStatus;
/**
* A description of the status of a job.
*/
Message?: AnyLengthString;
/**
* The time that the detection job was submitted for processing.
*/
SubmitTime?: Timestamp;
/**
* The time that the detection job completed.
*/
EndTime?: Timestamp;
/**
* The date and time that job metadata is deleted from the server. Output files in your S3 bucket will not be deleted. After the metadata is deleted, the job will no longer appear in the results of the ListEntitiesDetectionV2Job or the ListPHIDetectionJobs operation.
*/
ExpirationTime?: Timestamp;
/**
* The input data configuration that you supplied when you created the detection job.
*/
InputDataConfig?: InputDataConfig;
/**
* The output data configuration that you supplied when you created the detection job.
*/
OutputDataConfig?: OutputDataConfig;
/**
* The language code of the input documents.
*/
LanguageCode?: LanguageCode;
/**
* The Amazon Resource Name (ARN) that gives Comprehend Medical; read access to your input data.
*/
DataAccessRoleArn?: IamRoleArn;
/**
* The path to the file that describes the results of a batch job.
*/
ManifestFilePath?: ManifestFilePath;
/**
* The AWS Key Management Service key, if any, used to encrypt the output files.
*/
KMSKey?: KMSKey;
/**
* The version of the model used to analyze the documents. The version number looks like X.X.X. You can use this information to track the model used for a particular batch of documents.
*/
ModelVersion?: ModelVersion;
}
export type ComprehendMedicalAsyncJobPropertiesList = ComprehendMedicalAsyncJobProperties[];
export interface DescribeEntitiesDetectionV2JobRequest {
/**
* The identifier that Comprehend Medical; generated for the job. The StartEntitiesDetectionV2Job operation returns this identifier in its response.
*/
JobId: JobId;
}
export interface DescribeEntitiesDetectionV2JobResponse {
/**
* An object that contains the properties associated with a detection job.
*/
ComprehendMedicalAsyncJobProperties?: ComprehendMedicalAsyncJobProperties;
}
export interface DescribeICD10CMInferenceJobRequest {
/**
* The identifier that Amazon Comprehend Medical generated for the job. The StartICD10CMInferenceJob operation returns this identifier in its response.
*/
JobId: JobId;
}
export interface DescribeICD10CMInferenceJobResponse {
/**
* An object that contains the properties associated with a detection job.
*/
ComprehendMedicalAsyncJobProperties?: ComprehendMedicalAsyncJobProperties;
}
export interface DescribePHIDetectionJobRequest {
/**
* The identifier that Comprehend Medical; generated for the job. The StartPHIDetectionJob operation returns this identifier in its response.
*/
JobId: JobId;
}
export interface DescribePHIDetectionJobResponse {
/**
* An object that contains the properties associated with a detection job.
*/
ComprehendMedicalAsyncJobProperties?: ComprehendMedicalAsyncJobProperties;
}
export interface DescribeRxNormInferenceJobRequest {
/**
* The identifier that Amazon Comprehend Medical generated for the job. The StartRxNormInferenceJob operation returns this identifier in its response.
*/
JobId: JobId;
}
export interface DescribeRxNormInferenceJobResponse {
/**
* An object that contains the properties associated with a detection job.
*/
ComprehendMedicalAsyncJobProperties?: ComprehendMedicalAsyncJobProperties;
}
export interface DescribeSNOMEDCTInferenceJobRequest {
/**
* The identifier that Amazon Comprehend Medical generated for the job. The StartSNOMEDCTInferenceJob operation returns this identifier in its response.
*/
JobId: JobId;
}
export interface DescribeSNOMEDCTInferenceJobResponse {
ComprehendMedicalAsyncJobProperties?: ComprehendMedicalAsyncJobProperties;
}
export interface DetectEntitiesRequest {
/**
* A UTF-8 text string containing the clinical content being examined for entities. Each string must contain fewer than 20,000 bytes of characters.
*/
Text: BoundedLengthString;
}
export interface DetectEntitiesResponse {
/**
* The collection of medical entities extracted from the input text and their associated information. For each entity, the response provides the entity text, the entity category, where the entity text begins and ends, and the level of confidence that Comprehend Medical; has in the detection and analysis. Attributes and traits of the entity are also returned.
*/
Entities: EntityList;
/**
* Attributes extracted from the input text that we were unable to relate to an entity.
*/
UnmappedAttributes?: UnmappedAttributeList;
/**
* If the result of the previous request to DetectEntities was truncated, include the PaginationToken to fetch the next page of entities.
*/
PaginationToken?: String;
/**
* The version of the model used to analyze the documents. The version number looks like X.X.X. You can use this information to track the model used for a particular batch of documents.
*/
ModelVersion: String;
}
export interface DetectEntitiesV2Request {
/**
* A UTF-8 string containing the clinical content being examined for entities. Each string must contain fewer than 20,000 bytes of characters.
*/
Text: BoundedLengthString;
}
export interface DetectEntitiesV2Response {
/**
* The collection of medical entities extracted from the input text and their associated information. For each entity, the response provides the entity text, the entity category, where the entity text begins and ends, and the level of confidence in the detection and analysis. Attributes and traits of the entity are also returned.
*/
Entities: EntityList;
/**
* Attributes extracted from the input text that couldn't be related to an entity.
*/
UnmappedAttributes?: UnmappedAttributeList;
/**
* If the result to the DetectEntitiesV2 operation was truncated, include the PaginationToken to fetch the next page of entities.
*/
PaginationToken?: String;
/**
* The version of the model used to analyze the documents. The version number looks like X.X.X. You can use this information to track the model used for a particular batch of documents.
*/
ModelVersion: String;
}
export interface DetectPHIRequest {
/**
* A UTF-8 text string containing the clinical content being examined for PHI entities. Each string must contain fewer than 20,000 bytes of characters.
*/
Text: BoundedLengthString;
}
export interface DetectPHIResponse {
/**
* The collection of PHI entities extracted from the input text and their associated information. For each entity, the response provides the entity text, the entity category, where the entity text begins and ends, and the level of confidence that Comprehend Medical; has in its detection.
*/
Entities: EntityList;
/**
* If the result of the previous request to DetectPHI was truncated, include the PaginationToken to fetch the next page of PHI entities.
*/
PaginationToken?: String;
/**
* The version of the model used to analyze the documents. The version number looks like X.X.X. You can use this information to track the model used for a particular batch of documents.
*/
ModelVersion: String;
}
export interface Entity {
/**
* The numeric identifier for the entity. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The 0-based character offset in the input text that shows where the entity begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the entity ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* The level of confidence that Comprehend Medical; has in the accuracy of the detection.
*/
Score?: Float;
/**
* The segment of input text extracted as this entity.
*/
Text?: String;
/**
* The category of the entity.
*/
Category?: EntityType;
/**
* Describes the specific type of entity with category of entities.
*/
Type?: EntitySubType;
/**
* Contextual information for the entity.
*/
Traits?: TraitList;
/**
* The extracted attributes that relate to this entity.
*/
Attributes?: AttributeList;
}
export type EntityList = Entity[];
export type EntitySubType = "NAME"|"DX_NAME"|"DOSAGE"|"ROUTE_OR_MODE"|"FORM"|"FREQUENCY"|"DURATION"|"GENERIC_NAME"|"BRAND_NAME"|"STRENGTH"|"RATE"|"ACUITY"|"TEST_NAME"|"TEST_VALUE"|"TEST_UNITS"|"TEST_UNIT"|"PROCEDURE_NAME"|"TREATMENT_NAME"|"DATE"|"AGE"|"CONTACT_POINT"|"PHONE_OR_FAX"|"EMAIL"|"IDENTIFIER"|"ID"|"URL"|"ADDRESS"|"PROFESSION"|"SYSTEM_ORGAN_SITE"|"DIRECTION"|"QUALITY"|"QUANTITY"|"TIME_EXPRESSION"|"TIME_TO_MEDICATION_NAME"|"TIME_TO_DX_NAME"|"TIME_TO_TEST_NAME"|"TIME_TO_PROCEDURE_NAME"|"TIME_TO_TREATMENT_NAME"|string;
export type EntityType = "MEDICATION"|"MEDICAL_CONDITION"|"PROTECTED_HEALTH_INFORMATION"|"TEST_TREATMENT_PROCEDURE"|"ANATOMY"|"TIME_EXPRESSION"|string;
export type Float = number;
export interface ICD10CMAttribute {
/**
* The type of attribute. InferICD10CM detects entities of the type DX_NAME.
*/
Type?: ICD10CMAttributeType;
/**
* The level of confidence that Amazon Comprehend Medical has that the segment of text is correctly recognized as an attribute.
*/
Score?: Float;
/**
* The level of confidence that Amazon Comprehend Medical has that this attribute is correctly related to this entity.
*/
RelationshipScore?: Float;
/**
* The numeric identifier for this attribute. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* The segment of input text which contains the detected attribute.
*/
Text?: String;
/**
* The contextual information for the attribute. The traits recognized by InferICD10CM are DIAGNOSIS, SIGN, SYMPTOM, and NEGATION.
*/
Traits?: ICD10CMTraitList;
/**
* The category of attribute. Can be either of DX_NAME or TIME_EXPRESSION.
*/
Category?: ICD10CMEntityType;
/**
* The type of relationship between the entity and attribute. Type for the relationship can be either of OVERLAP or SYSTEM_ORGAN_SITE.
*/
RelationshipType?: ICD10CMRelationshipType;
}
export type ICD10CMAttributeList = ICD10CMAttribute[];
export type ICD10CMAttributeType = "ACUITY"|"DIRECTION"|"SYSTEM_ORGAN_SITE"|"QUALITY"|"QUANTITY"|"TIME_TO_DX_NAME"|"TIME_EXPRESSION"|string;
export interface ICD10CMConcept {
/**
* The long description of the ICD-10-CM code in the ontology.
*/
Description?: String;
/**
* The ICD-10-CM code that identifies the concept found in the knowledge base from the Centers for Disease Control.
*/
Code?: String;
/**
* The level of confidence that Amazon Comprehend Medical has that the entity is accurately linked to an ICD-10-CM concept.
*/
Score?: Float;
}
export type ICD10CMConceptList = ICD10CMConcept[];
export interface ICD10CMEntity {
/**
* The numeric identifier for the entity. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The segment of input text that is matched to the detected entity.
*/
Text?: OntologyLinkingBoundedLengthString;
/**
* The category of the entity. InferICD10CM detects entities in the MEDICAL_CONDITION category.
*/
Category?: ICD10CMEntityCategory;
/**
* Describes the specific type of entity with category of entities. InferICD10CM detects entities of the type DX_NAME and TIME_EXPRESSION.
*/
Type?: ICD10CMEntityType;
/**
* The level of confidence that Amazon Comprehend Medical has in the accuracy of the detection.
*/
Score?: Float;
/**
* The 0-based character offset in the input text that shows where the entity begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the entity ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* The detected attributes that relate to the entity. An extracted segment of the text that is an attribute of an entity, or otherwise related to an entity, such as the nature of a medical condition.
*/
Attributes?: ICD10CMAttributeList;
/**
* Provides Contextual information for the entity. The traits recognized by InferICD10CM are DIAGNOSIS, SIGN, SYMPTOM, and NEGATION.
*/
Traits?: ICD10CMTraitList;
/**
* The ICD-10-CM concepts that the entity could refer to, along with a score indicating the likelihood of the match.
*/
ICD10CMConcepts?: ICD10CMConceptList;
}
export type ICD10CMEntityCategory = "MEDICAL_CONDITION"|string;
export type ICD10CMEntityList = ICD10CMEntity[];
export type ICD10CMEntityType = "DX_NAME"|"TIME_EXPRESSION"|string;
export type ICD10CMRelationshipType = "OVERLAP"|"SYSTEM_ORGAN_SITE"|string;
export interface ICD10CMTrait {
/**
* Provides a name or contextual description about the trait.
*/
Name?: ICD10CMTraitName;
/**
* The level of confidence that Comprehend Medical; has that the segment of text is correctly recognized as a trait.
*/
Score?: Float;
}
export type ICD10CMTraitList = ICD10CMTrait[];
export type ICD10CMTraitName = "NEGATION"|"DIAGNOSIS"|"SIGN"|"SYMPTOM"|string;
export type IamRoleArn = string;
export interface InferICD10CMRequest {
/**
* The input text used for analysis. The input for InferICD10CM is a string from 1 to 10000 characters.
*/
Text: OntologyLinkingBoundedLengthString;
}
export interface InferICD10CMResponse {
/**
* The medical conditions detected in the text linked to ICD-10-CM concepts. If the action is successful, the service sends back an HTTP 200 response, as well as the entities detected.
*/
Entities: ICD10CMEntityList;
/**
* If the result of the previous request to InferICD10CM was truncated, include the PaginationToken to fetch the next page of medical condition entities.
*/
PaginationToken?: String;
/**
* The version of the model used to analyze the documents, in the format n.n.n You can use this information to track the model used for a particular batch of documents.
*/
ModelVersion?: String;
}
export interface InferRxNormRequest {
/**
* The input text used for analysis. The input for InferRxNorm is a string from 1 to 10000 characters.
*/
Text: OntologyLinkingBoundedLengthString;
}
export interface InferRxNormResponse {
/**
* The medication entities detected in the text linked to RxNorm concepts. If the action is successful, the service sends back an HTTP 200 response, as well as the entities detected.
*/
Entities: RxNormEntityList;
/**
* If the result of the previous request to InferRxNorm was truncated, include the PaginationToken to fetch the next page of medication entities.
*/
PaginationToken?: String;
/**
* The version of the model used to analyze the documents, in the format n.n.n You can use this information to track the model used for a particular batch of documents.
*/
ModelVersion?: String;
}
export interface InferSNOMEDCTRequest {
/**
* The input text to be analyzed using InferSNOMEDCT. The text should be a string with 1 to 10000 characters.
*/
Text: OntologyLinkingBoundedLengthString;
}
export interface InferSNOMEDCTResponse {
/**
* The collection of medical concept entities extracted from the input text and their associated information. For each entity, the response provides the entity text, the entity category, where the entity text begins and ends, and the level of confidence that Comprehend Medical has in the detection and analysis. Attributes and traits of the entity are also returned.
*/
Entities: SNOMEDCTEntityList;
/**
* If the result of the request is truncated, the pagination token can be used to fetch the next page of entities.
*/
PaginationToken?: String;
/**
* The version of the model used to analyze the documents, in the format n.n.n You can use this information to track the model used for a particular batch of documents.
*/
ModelVersion?: String;
/**
* The details of the SNOMED-CT revision, including the edition, language, and version date.
*/
SNOMEDCTDetails?: SNOMEDCTDetails;
/**
* The number of characters in the input request documentation.
*/
Characters?: Characters;
}
export interface InputDataConfig {
/**
* The URI of the S3 bucket that contains the input data. The bucket must be in the same region as the API endpoint that you are calling. Each file in the document collection must be less than 40 KB. You can store a maximum of 30 GB in the bucket.
*/
S3Bucket: S3Bucket;
/**
* The path to the input data files in the S3 bucket.
*/
S3Key?: S3Key;
}
export type Integer = number;
export type JobId = string;
export type JobName = string;
export type JobStatus = "SUBMITTED"|"IN_PROGRESS"|"COMPLETED"|"PARTIAL_SUCCESS"|"FAILED"|"STOP_REQUESTED"|"STOPPED"|string;
export type KMSKey = string;
export type LanguageCode = "en"|string;
export interface ListEntitiesDetectionV2JobsRequest {
/**
* Filters the jobs that are returned. You can filter jobs based on their names, status, or the date and time that they were submitted. You can only set one filter at a time.
*/
Filter?: ComprehendMedicalAsyncJobFilter;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
/**
* The maximum number of results to return in each page. The default is 100.
*/
MaxResults?: MaxResultsInteger;
}
export interface ListEntitiesDetectionV2JobsResponse {
/**
* A list containing the properties of each job returned.
*/
ComprehendMedicalAsyncJobPropertiesList?: ComprehendMedicalAsyncJobPropertiesList;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
}
export interface ListICD10CMInferenceJobsRequest {
/**
* Filters the jobs that are returned. You can filter jobs based on their names, status, or the date and time that they were submitted. You can only set one filter at a time.
*/
Filter?: ComprehendMedicalAsyncJobFilter;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
/**
* The maximum number of results to return in each page. The default is 100.
*/
MaxResults?: MaxResultsInteger;
}
export interface ListICD10CMInferenceJobsResponse {
/**
* A list containing the properties of each job that is returned.
*/
ComprehendMedicalAsyncJobPropertiesList?: ComprehendMedicalAsyncJobPropertiesList;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
}
export interface ListPHIDetectionJobsRequest {
/**
* Filters the jobs that are returned. You can filter jobs based on their names, status, or the date and time that they were submitted. You can only set one filter at a time.
*/
Filter?: ComprehendMedicalAsyncJobFilter;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
/**
* The maximum number of results to return in each page. The default is 100.
*/
MaxResults?: MaxResultsInteger;
}
export interface ListPHIDetectionJobsResponse {
/**
* A list containing the properties of each job returned.
*/
ComprehendMedicalAsyncJobPropertiesList?: ComprehendMedicalAsyncJobPropertiesList;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
}
export interface ListRxNormInferenceJobsRequest {
/**
* Filters the jobs that are returned. You can filter jobs based on their names, status, or the date and time that they were submitted. You can only set one filter at a time.
*/
Filter?: ComprehendMedicalAsyncJobFilter;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
/**
* Identifies the next page of results to return.
*/
MaxResults?: MaxResultsInteger;
}
export interface ListRxNormInferenceJobsResponse {
/**
* The maximum number of results to return in each page. The default is 100.
*/
ComprehendMedicalAsyncJobPropertiesList?: ComprehendMedicalAsyncJobPropertiesList;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
}
export interface ListSNOMEDCTInferenceJobsRequest {
Filter?: ComprehendMedicalAsyncJobFilter;
/**
* Identifies the next page of InferSNOMEDCT results to return.
*/
NextToken?: String;
/**
* The maximum number of results to return in each page. The default is 100.
*/
MaxResults?: MaxResultsInteger;
}
export interface ListSNOMEDCTInferenceJobsResponse {
/**
* A list containing the properties of each job that is returned.
*/
ComprehendMedicalAsyncJobPropertiesList?: ComprehendMedicalAsyncJobPropertiesList;
/**
* Identifies the next page of results to return.
*/
NextToken?: String;
}
export type ManifestFilePath = string;
export type MaxResultsInteger = number;
export type ModelVersion = string;
export type OntologyLinkingBoundedLengthString = string;
export interface OutputDataConfig {
/**
* When you use the OutputDataConfig object with asynchronous operations, you specify the Amazon S3 location where you want to write the output data. The URI must be in the same region as the API endpoint that you are calling. The location is used as the prefix for the actual location of the output.
*/
S3Bucket: S3Bucket;
/**
* The path to the output data files in the S3 bucket. Comprehend Medical; creates an output directory using the job ID so that the output from one job does not overwrite the output of another.
*/
S3Key?: S3Key;
}
export type RelationshipType = "EVERY"|"WITH_DOSAGE"|"ADMINISTERED_VIA"|"FOR"|"NEGATIVE"|"OVERLAP"|"DOSAGE"|"ROUTE_OR_MODE"|"FORM"|"FREQUENCY"|"DURATION"|"STRENGTH"|"RATE"|"ACUITY"|"TEST_VALUE"|"TEST_UNITS"|"TEST_UNIT"|"DIRECTION"|"SYSTEM_ORGAN_SITE"|string;
export interface RxNormAttribute {
/**
* The type of attribute. The types of attributes recognized by InferRxNorm are BRAND_NAME and GENERIC_NAME.
*/
Type?: RxNormAttributeType;
/**
* The level of confidence that Comprehend Medical has that the segment of text is correctly recognized as an attribute.
*/
Score?: Float;
/**
* The level of confidence that Amazon Comprehend Medical has that the attribute is accurately linked to an entity.
*/
RelationshipScore?: Float;
/**
* The numeric identifier for this attribute. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* The segment of input text which corresponds to the detected attribute.
*/
Text?: String;
/**
* Contextual information for the attribute. InferRxNorm recognizes the trait NEGATION for attributes, i.e. that the patient is not taking a specific dose or form of a medication.
*/
Traits?: RxNormTraitList;
}
export type RxNormAttributeList = RxNormAttribute[];
export type RxNormAttributeType = "DOSAGE"|"DURATION"|"FORM"|"FREQUENCY"|"RATE"|"ROUTE_OR_MODE"|"STRENGTH"|string;
export interface RxNormConcept {
/**
* The description of the RxNorm concept.
*/
Description?: String;
/**
* RxNorm concept ID, also known as the RxCUI.
*/
Code?: String;
/**
* The level of confidence that Amazon Comprehend Medical has that the entity is accurately linked to the reported RxNorm concept.
*/
Score?: Float;
}
export type RxNormConceptList = RxNormConcept[];
export interface RxNormEntity {
/**
* The numeric identifier for the entity. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The segment of input text extracted from which the entity was detected.
*/
Text?: OntologyLinkingBoundedLengthString;
/**
* The category of the entity. The recognized categories are GENERIC or BRAND_NAME.
*/
Category?: RxNormEntityCategory;
/**
* Describes the specific type of entity. For InferRxNorm, the recognized entity type is MEDICATION.
*/
Type?: RxNormEntityType;
/**
* The level of confidence that Amazon Comprehend Medical has in the accuracy of the detected entity.
*/
Score?: Float;
/**
* The 0-based character offset in the input text that shows where the entity begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the entity ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* The extracted attributes that relate to the entity. The attributes recognized by InferRxNorm are DOSAGE, DURATION, FORM, FREQUENCY, RATE, ROUTE_OR_MODE, and STRENGTH.
*/
Attributes?: RxNormAttributeList;
/**
* Contextual information for the entity.
*/
Traits?: RxNormTraitList;
/**
* The RxNorm concepts that the entity could refer to, along with a score indicating the likelihood of the match.
*/
RxNormConcepts?: RxNormConceptList;
}
export type RxNormEntityCategory = "MEDICATION"|string;
export type RxNormEntityList = RxNormEntity[];
export type RxNormEntityType = "BRAND_NAME"|"GENERIC_NAME"|string;
export interface RxNormTrait {
/**
* Provides a name or contextual description about the trait.
*/
Name?: RxNormTraitName;
/**
* The level of confidence that Amazon Comprehend Medical has in the accuracy of the detected trait.
*/
Score?: Float;
}
export type RxNormTraitList = RxNormTrait[];
export type RxNormTraitName = "NEGATION"|string;
export type S3Bucket = string;
export type S3Key = string;
export interface SNOMEDCTAttribute {
/**
* The category of the detected attribute. Possible categories include MEDICAL_CONDITION, ANATOMY, and TEST_TREATMENT_PROCEDURE.
*/
Category?: SNOMEDCTEntityCategory;
/**
* The type of attribute. Possible types include DX_NAME, ACUITY, DIRECTION, SYSTEM_ORGAN_SITE,TEST_NAME, TEST_VALUE, TEST_UNIT, PROCEDURE_NAME, and TREATMENT_NAME.
*/
Type?: SNOMEDCTAttributeType;
/**
* The level of confidence that Comprehend Medical has that the segment of text is correctly recognized as an attribute.
*/
Score?: Float;
/**
* The level of confidence that Comprehend Medical has that this attribute is correctly related to this entity.
*/
RelationshipScore?: Float;
/**
* The type of relationship that exists between the entity and the related attribute.
*/
RelationshipType?: SNOMEDCTRelationshipType;
/**
* The numeric identifier for this attribute. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the attribute ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* The segment of input text extracted as this attribute.
*/
Text?: String;
/**
* Contextual information for an attribute. Examples include signs, symptoms, diagnosis, and negation.
*/
Traits?: SNOMEDCTTraitList;
/**
* The SNOMED-CT concepts specific to an attribute, along with a score indicating the likelihood of the match.
*/
SNOMEDCTConcepts?: SNOMEDCTConceptList;
}
export type SNOMEDCTAttributeList = SNOMEDCTAttribute[];
export type SNOMEDCTAttributeType = "ACUITY"|"QUALITY"|"DIRECTION"|"SYSTEM_ORGAN_SITE"|"TEST_VALUE"|"TEST_UNIT"|string;
export interface SNOMEDCTConcept {
/**
* The description of the SNOMED-CT concept.
*/
Description?: String;
/**
* The numeric ID for the SNOMED-CT concept.
*/
Code?: String;
/**
* The level of confidence Comprehend Medical has that the entity should be linked to the identified SNOMED-CT concept.
*/
Score?: Float;
}
export type SNOMEDCTConceptList = SNOMEDCTConcept[];
export interface SNOMEDCTDetails {
/**
* The edition of SNOMED-CT used. The edition used for the InferSNOMEDCT editions is the US edition.
*/
Edition?: String;
/**
* The language used in the SNOMED-CT ontology. All Amazon Comprehend Medical operations are US English (en).
*/
Language?: String;
/**
* The version date of the SNOMED-CT ontology used.
*/
VersionDate?: String;
}
export interface SNOMEDCTEntity {
/**
* The numeric identifier for the entity. This is a monotonically increasing id unique within this response rather than a global unique identifier.
*/
Id?: Integer;
/**
* The segment of input text extracted as this entity.
*/
Text?: OntologyLinkingBoundedLengthString;
/**
* The category of the detected entity. Possible categories are MEDICAL_CONDITION, ANATOMY, or TEST_TREATMENT_PROCEDURE.
*/
Category?: SNOMEDCTEntityCategory;
/**
* Describes the specific type of entity with category of entities. Possible types include DX_NAME, ACUITY, DIRECTION, SYSTEM_ORGAN_SITE, TEST_NAME, TEST_VALUE, TEST_UNIT, PROCEDURE_NAME, or TREATMENT_NAME.
*/
Type?: SNOMEDCTEntityType;
/**
* The level of confidence that Comprehend Medical has in the accuracy of the detected entity.
*/
Score?: Float;
/**
* The 0-based character offset in the input text that shows where the entity begins. The offset returns the UTF-8 code point in the string.
*/
BeginOffset?: Integer;
/**
* The 0-based character offset in the input text that shows where the entity ends. The offset returns the UTF-8 code point in the string.
*/
EndOffset?: Integer;
/**
* An extracted segment of the text that is an attribute of an entity, or otherwise related to an entity, such as the dosage of a medication taken.
*/
Attributes?: SNOMEDCTAttributeList;
/**
* Contextual information for the entity.
*/
Traits?: SNOMEDCTTraitList;
/**
* The SNOMED concepts that the entity could refer to, along with a score indicating the likelihood of the match.
*/
SNOMEDCTConcepts?: SNOMEDCTConceptList;
}
export type SNOMEDCTEntityCategory = "MEDICAL_CONDITION"|"ANATOMY"|"TEST_TREATMENT_PROCEDURE"|string;
export type SNOMEDCTEntityList = SNOMEDCTEntity[];
export type SNOMEDCTEntityType = "DX_NAME"|"TEST_NAME"|"PROCEDURE_NAME"|"TREATMENT_NAME"|string;
export type SNOMEDCTRelationshipType = "ACUITY"|"QUALITY"|"TEST_VALUE"|"TEST_UNITS"|"DIRECTION"|"SYSTEM_ORGAN_SITE"|string;
export interface SNOMEDCTTrait {
/**
* The name or contextual description of a detected trait.
*/
Name?: SNOMEDCTTraitName;
/**
* The level of confidence that Comprehend Medical has in the accuracy of a detected trait.
*/
Score?: Float;
}
export type SNOMEDCTTraitList = SNOMEDCTTrait[];
export type SNOMEDCTTraitName = "NEGATION"|"DIAGNOSIS"|"SIGN"|"SYMPTOM"|string;
export interface StartEntitiesDetectionV2JobRequest {
/**
* The input configuration that specifies the format and location of the input data for the job.
*/
InputDataConfig: InputDataConfig;
/**
* The output configuration that specifies where to send the output files.
*/
OutputDataConfig: OutputDataConfig;
/**
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Comprehend Medical; read access to your input data. For more information, see Role-Based Permissions Required for Asynchronous Operations.
*/
DataAccessRoleArn: IamRoleArn;
/**
* The identifier of the job.
*/
JobName?: JobName;
/**
* A unique identifier for the request. If you don't set the client request token, Comprehend Medical; generates one for you.
*/
ClientRequestToken?: ClientRequestTokenString;
/**
* An AWS Key Management Service key to encrypt your output files. If you do not specify a key, the files are written in plain text.
*/
KMSKey?: KMSKey;
/**
* The language of the input documents. All documents must be in the same language. Comprehend Medical; processes files in US English (en).
*/
LanguageCode: LanguageCode;
}
export interface StartEntitiesDetectionV2JobResponse {
/**
* The identifier generated for the job. To get the status of a job, use this identifier with the DescribeEntitiesDetectionV2Job operation.
*/
JobId?: JobId;
}
export interface StartICD10CMInferenceJobRequest {
/**
* Specifies the format and location of the input data for the job.
*/
InputDataConfig: InputDataConfig;
/**
* Specifies where to send the output files.
*/
OutputDataConfig: OutputDataConfig;
/**
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Comprehend Medical; read access to your input data. For more information, see Role-Based Permissions Required for Asynchronous Operations.
*/
DataAccessRoleArn: IamRoleArn;
/**
* The identifier of the job.
*/
JobName?: JobName;
/**
* A unique identifier for the request. If you don't set the client request token, Comprehend Medical; generates one.
*/
ClientRequestToken?: ClientRequestTokenString;
/**
* An AWS Key Management Service key to encrypt your output files. If you do not specify a key, the files are written in plain text.
*/
KMSKey?: KMSKey;
/**
* The language of the input documents. All documents must be in the same language.
*/
LanguageCode: LanguageCode;
}
export interface StartICD10CMInferenceJobResponse {
/**
* The identifier generated for the job. To get the status of a job, use this identifier with the StartICD10CMInferenceJob operation.
*/
JobId?: JobId;
}
export interface StartPHIDetectionJobRequest {
/**
* Specifies the format and location of the input data for the job.
*/
InputDataConfig: InputDataConfig;
/**
* Specifies where to send the output files.
*/
OutputDataConfig: OutputDataConfig;
/**
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Comprehend Medical; read access to your input data. For more information, see Role-Based Permissions Required for Asynchronous Operations.
*/
DataAccessRoleArn: IamRoleArn;
/**
* The identifier of the job.
*/
JobName?: JobName;
/**
* A unique identifier for the request. If you don't set the client request token, Comprehend Medical; generates one.
*/
ClientRequestToken?: ClientRequestTokenString;
/**
* An AWS Key Management Service key to encrypt your output files. If you do not specify a key, the files are written in plain text.
*/
KMSKey?: KMSKey;
/**
* The language of the input documents. All documents must be in the same language.
*/
LanguageCode: LanguageCode;
}
export interface StartPHIDetectionJobResponse {
/**
* The identifier generated for the job. To get the status of a job, use this identifier with the DescribePHIDetectionJob operation.
*/
JobId?: JobId;
}
export interface StartRxNormInferenceJobRequest {
/**
* Specifies the format and location of the input data for the job.
*/
InputDataConfig: InputDataConfig;
/**
* Specifies where to send the output files.
*/
OutputDataConfig: OutputDataConfig;
/**
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Comprehend Medical; read access to your input data. For more information, see Role-Based Permissions Required for Asynchronous Operations.
*/
DataAccessRoleArn: IamRoleArn;
/**
* The identifier of the job.
*/
JobName?: JobName;
/**
* A unique identifier for the request. If you don't set the client request token, Comprehend Medical; generates one.
*/
ClientRequestToken?: ClientRequestTokenString;
/**
* An AWS Key Management Service key to encrypt your output files. If you do not specify a key, the files are written in plain text.
*/
KMSKey?: KMSKey;
/**
* The language of the input documents. All documents must be in the same language.
*/
LanguageCode: LanguageCode;
}
export interface StartRxNormInferenceJobResponse {
/**
* The identifier of the job.
*/
JobId?: JobId;
}
export interface StartSNOMEDCTInferenceJobRequest {
InputDataConfig: InputDataConfig;
OutputDataConfig: OutputDataConfig;
/**
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend Medical read access to your input data.
*/
DataAccessRoleArn: IamRoleArn;
/**
* The user generated name the asynchronous InferSNOMEDCT job.
*/
JobName?: JobName;
/**
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend Medical generates one.
*/
ClientRequestToken?: ClientRequestTokenString;
/**
* An AWS Key Management Service key used to encrypt your output files. If you do not specify a key, the files are written in plain text.
*/
KMSKey?: KMSKey;
/**
* The language of the input documents. All documents must be in the same language.
*/
LanguageCode: LanguageCode;
}
export interface StartSNOMEDCTInferenceJobResponse {
/**
* The identifier generated for the job. To get the status of a job, use this identifier with the StartSNOMEDCTInferenceJob operation.
*/
JobId?: JobId;
}
export interface StopEntitiesDetectionV2JobRequest {
/**
* The identifier of the medical entities job to stop.
*/
JobId: JobId;
}
export interface StopEntitiesDetectionV2JobResponse {
/**
* The identifier of the medical entities detection job that was stopped.
*/
JobId?: JobId;
}
export interface StopICD10CMInferenceJobRequest {
/**
* The identifier of the job.
*/
JobId: JobId;
}
export interface StopICD10CMInferenceJobResponse {
/**
* The identifier generated for the job. To get the status of job, use this identifier with the DescribeICD10CMInferenceJob operation.
*/
JobId?: JobId;
}
export interface StopPHIDetectionJobRequest {
/**
* The identifier of the PHI detection job to stop.
*/
JobId: JobId;
}
export interface StopPHIDetectionJobResponse {
/**
* The identifier of the PHI detection job that was stopped.
*/
JobId?: JobId;
}
export interface StopRxNormInferenceJobRequest {
/**
* The identifier of the job.
*/
JobId: JobId;
}
export interface StopRxNormInferenceJobResponse {
/**
* The identifier generated for the job. To get the status of job, use this identifier with the DescribeRxNormInferenceJob operation.
*/
JobId?: JobId;
}
export interface StopSNOMEDCTInferenceJobRequest {
/**
* The job id of the asynchronous InferSNOMEDCT job to be stopped.
*/
JobId: JobId;
}
export interface StopSNOMEDCTInferenceJobResponse {
/**
* The identifier generated for the job. To get the status of job, use this identifier with the DescribeSNOMEDCTInferenceJob operation.
*/
JobId?: JobId;
}
export type String = string;
export type Timestamp = Date;
export interface Trait {
/**
* Provides a name or contextual description about the trait.
*/
Name?: AttributeName;
/**
* The level of confidence that Comprehend Medical; has in the accuracy of this trait.
*/
Score?: Float;
}
export type TraitList = Trait[];
export interface UnmappedAttribute {
/**
* The type of the unmapped attribute, could be one of the following values: "MEDICATION", "MEDICAL_CONDITION", "ANATOMY", "TEST_AND_TREATMENT_PROCEDURE" or "PROTECTED_HEALTH_INFORMATION".
*/
Type?: EntityType;
/**
* The specific attribute that has been extracted but not mapped to an entity.
*/
Attribute?: Attribute;
}
export type UnmappedAttributeList = UnmappedAttribute[];
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2018-10-30"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the ComprehendMedical client.
*/
export import Types = ComprehendMedical;
}
export = ComprehendMedical; | the_stack |
import path from "path";
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import { defineAppModule, PulumiApp, PulumiAppModule } from "@webiny/pulumi-sdk";
import { createLambdaRole, getCommonLambdaEnvVariables } from "../lambdaUtils";
import { StorageOutput, VpcConfig } from "../common";
import { getAwsAccountId, getAwsRegion } from "../awsUtils";
interface GraphqlParams {
env: Record<string, any>;
apwSchedulerEventRule: pulumi.Output<aws.cloudwatch.EventRule>;
apwSchedulerEventTarget: pulumi.Output<aws.cloudwatch.EventTarget>;
}
export type ApiGraphql = PulumiAppModule<typeof ApiGraphql>;
export const ApiGraphql = defineAppModule({
name: "ApiGraphql",
config(app: PulumiApp, params: GraphqlParams) {
const storage = app.getModule(StorageOutput);
const policy = createGraphqlLambdaPolicy(app);
const role = createLambdaRole(app, {
name: "api-lambda-role",
policy: policy.output
});
const graphql = app.addResource(aws.lambda.Function, {
name: "graphql",
config: {
runtime: "nodejs14.x",
handler: "handler.handler",
role: role.output.arn,
timeout: 30,
memorySize: 512,
code: new pulumi.asset.AssetArchive({
".": new pulumi.asset.FileArchive(
path.join(app.ctx.appDir, "code/graphql/build")
)
}),
environment: {
variables: {
...getCommonLambdaEnvVariables(app),
...params.env,
AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",
WCP_ENVIRONMENT_API_KEY: String(process.env["WCP_ENVIRONMENT_API_KEY"])
}
},
vpcConfig: app.getModule(VpcConfig).functionVpcConfig
}
});
/**
* Store meta information like "mainGraphqlFunctionArn" in APW settings at deploy time.
*
* Note: We can't pass "mainGraphqlFunctionArn" as env variable due to circular dependency between
* "graphql" lambda and "api-apw-scheduler-execute-action" lambda.
*/
app.addResource(aws.dynamodb.TableItem, {
name: "apwSettings",
config: {
tableName: storage.primaryDynamodbTableName,
hashKey: storage.primaryDynamodbTableHashKey,
rangeKey: pulumi
.output(storage.primaryDynamodbTableRangeKey)
.apply(key => key || "SK"),
item: pulumi.interpolate`{
"PK": {"S": "APW#SETTINGS"},
"SK": {"S": "${app.ctx.variant || "A"}"},
"mainGraphqlFunctionArn": {"S": "${graphql.output.arn}"},
"eventRuleName": {"S": "${params.apwSchedulerEventRule.name}"},
"eventTargetId": {"S": "${params.apwSchedulerEventTarget.targetId}"}
}`
}
});
return {
role,
policy,
functions: {
graphql
}
};
}
});
function createGraphqlLambdaPolicy(app: PulumiApp) {
const storageOutput = app.getModule(StorageOutput);
const awsAccountId = getAwsAccountId(app);
const awsRegion = getAwsRegion(app);
return app.addResource(aws.iam.Policy, {
name: "ApiGraphqlLambdaPolicy",
config: {
description: "This policy enables access to Dynamodb, S3, Lambda and Cognito IDP",
// Storage is pulumi.Output, so we need to run apply() to resolve policy based on it
policy: storageOutput.apply(storage => {
const policy: aws.iam.PolicyDocument = {
Version: "2012-10-17",
Statement: [
{
Sid: "PermissionForDynamodb",
Effect: "Allow",
Action: [
"dynamodb:BatchGetItem",
"dynamodb:BatchWriteItem",
"dynamodb:ConditionCheckItem",
"dynamodb:CreateBackup",
"dynamodb:CreateTable",
"dynamodb:CreateTableReplica",
"dynamodb:DeleteBackup",
"dynamodb:DeleteItem",
"dynamodb:DeleteTable",
"dynamodb:DeleteTableReplica",
"dynamodb:DescribeBackup",
"dynamodb:DescribeContinuousBackups",
"dynamodb:DescribeContributorInsights",
"dynamodb:DescribeExport",
"dynamodb:DescribeKinesisStreamingDestination",
"dynamodb:DescribeLimits",
"dynamodb:DescribeReservedCapacity",
"dynamodb:DescribeReservedCapacityOfferings",
"dynamodb:DescribeStream",
"dynamodb:DescribeTable",
"dynamodb:DescribeTableReplicaAutoScaling",
"dynamodb:DescribeTimeToLive",
"dynamodb:DisableKinesisStreamingDestination",
"dynamodb:EnableKinesisStreamingDestination",
"dynamodb:ExportTableToPointInTime",
"dynamodb:GetItem",
"dynamodb:GetRecords",
"dynamodb:GetShardIterator",
"dynamodb:ListBackups",
"dynamodb:ListContributorInsights",
"dynamodb:ListExports",
"dynamodb:ListStreams",
"dynamodb:ListTables",
"dynamodb:ListTagsOfResource",
"dynamodb:PartiQLDelete",
"dynamodb:PartiQLInsert",
"dynamodb:PartiQLSelect",
"dynamodb:PartiQLUpdate",
"dynamodb:PurchaseReservedCapacityOfferings",
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:RestoreTableFromBackup",
"dynamodb:RestoreTableToPointInTime",
"dynamodb:Scan",
"dynamodb:UpdateContinuousBackups",
"dynamodb:UpdateContributorInsights",
"dynamodb:UpdateItem",
"dynamodb:UpdateTable",
"dynamodb:UpdateTableReplicaAutoScaling",
"dynamodb:UpdateTimeToLive"
],
Resource: [
`${storage.primaryDynamodbTableArn}`,
`${storage.primaryDynamodbTableArn}/*`,
// Attach permissions for elastic search dynamo as well (if ES is enabled).
...(storage.elasticsearchDynamodbTableArn
? [
`${storage.elasticsearchDynamodbTableArn}`,
`${storage.elasticsearchDynamodbTableArn}/*`
]
: [])
]
},
{
Sid: "PermissionForS3",
Effect: "Allow",
Action: [
"s3:GetObjectAcl",
"s3:DeleteObject",
"s3:PutObjectAcl",
"s3:PutObject",
"s3:GetObject"
],
Resource: `arn:aws:s3:::${storage.fileManagerBucketId}/*`
},
{
Sid: "PermissionForLambda",
Effect: "Allow",
Action: ["lambda:InvokeFunction"],
Resource: pulumi.interpolate`arn:aws:lambda:${awsRegion}:${awsAccountId}:function:*`
},
{
Sid: "PermissionForCognitoIdp",
Effect: "Allow",
Action: "cognito-idp:*",
Resource: `${storage.cognitoUserPoolArn}`
},
{
Sid: "PermissionForEventBus",
Effect: "Allow",
Action: "events:PutEvents",
Resource: storage.eventBusArn
},
// Attach permissions for elastic search domain as well (if ES is enabled).
...(storage.elasticsearchDomainArn
? [
{
Sid: "PermissionForES",
Effect: "Allow" as const,
Action: "es:*",
Resource: [
`${storage.elasticsearchDomainArn}`,
`${storage.elasticsearchDomainArn}/*`
]
}
]
: [])
]
};
return policy;
})
}
});
} | the_stack |
import { Canvas, CanvasRenderingContext2D, createCanvas, Image, loadImage } from "canvas";
import { decompressFrames, parseGIF } from "./gifuct-js";
import { QRCodeModel, QRErrorCorrectLevel, QRUtil } from "./qrcode";
import GIFEncoder from "./gif.js/GIFEncoder";
const defaultScale = 0.4;
export type ComponentOptions = {
/**
* Component options for data/ECC.
*/
data?: {
/**
* Scale factor for data/ECC dots.
* @default 1
*/
scale?: number;
};
/**
* Component options for timing patterns.
*/
timing?: {
/**
* Scale factor for timing patterns.
* @default 1
*/
scale?: number;
/**
* Protector for timing patterns.
* @default false
*/
protectors?: boolean;
};
/**
* Component options for alignment patterns.
*/
alignment?: {
/**
* Scale factor for alignment patterns.
* @default 1
*/
scale?: number;
/**
* Protector for alignment patterns.
* @default false
*/
protectors?: boolean;
};
/**
* Component options for alignment pattern on the bottom-right corner.
*/
cornerAlignment?: {
/**
* Scale factor for alignment pattern on the bottom-right corner.
* @default 1
*/
scale?: number;
/**
* Protector for alignment pattern on the bottom-right corner.
* @default true
*/
protectors?: boolean;
};
};
export type Options = {
/**
* Text to be encoded in the QR code.
*/
text: string;
/**
* Size of the QR code in pixel.
*
* @defaultValue 400
*/
size?: number;
/**
* Size of margins around the QR code body in pixel.
*
* @defaultValue 20
*/
margin?: number;
/**
* Error correction level of the QR code.
*
* Accepts a value provided by _QRErrorCorrectLevel_.
*
* For more information, please refer to [https://www.qrcode.com/en/about/error_correction.html](https://www.qrcode.com/en/about/error_correction.html).
*
* @defaultValue 0
*/
correctLevel?: number;
/**
* **This is an advanced option.**
*
* Specify the mask pattern to be used in QR code encoding.
*
* Accepts a value provided by _QRMaskPattern_.
*
* To find out all eight mask patterns, please refer to [https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg](https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg)
*
* For more information, please refer to [https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking](https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking).
*/
maskPattern?: number;
/**
* **This is an advanced option.**
*
* Specify the version to be used in QR code encoding.
*
* Accepts an integer in range [1, 40].
*
* For more information, please refer to [https://www.qrcode.com/en/about/version.html](https://www.qrcode.com/en/about/version.html).
*/
version?: number;
/**
* Options to control components in the QR code.
*
* @deafultValue undefined
*/
components?: ComponentOptions;
/**
* Color of the blocks on the QR code.
*
* Accepts a CSS <color>.
*
* For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
*
* @defaultValue "#000000"
*/
colorDark?: string;
/**
* Color of the empty areas on the QR code.
*
* Accepts a CSS <color>.
*
* For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
*
* @defaultValue "#ffffff"
*/
colorLight?: string;
/**
* Automatically calculate the _colorLight_ value from the QR code's background.
*
* @defaultValue true
*/
autoColor?: boolean;
/**
* Background image to be used in the QR code.
*
* Accepts a `data:` string in web browsers or a Buffer in Node.js.
*
* @defaultValue undefined
*/
backgroundImage?: string | Buffer;
/**
* Color of the dimming mask above the background image.
*
* Accepts a CSS <color>.
*
* For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
*
* @defaultValue "rgba(0, 0, 0, 0)"
*/
backgroundDimming?: string;
/**
* GIF background image to be used in the QR code.
*
* @defaultValue undefined
*/
gifBackground?: ArrayBuffer;
/**
* Use a white margin instead of a transparent one which reveals the background of the QR code on margins.
*
* @defaultValue true
*/
whiteMargin?: boolean;
/**
* Logo image to be displayed at the center of the QR code.
*
* Accepts a `data:` string in web browsers or a Buffer in Node.js.
*
* When set to `undefined` or `null`, the logo is disabled.
*
* @defaultValue undefined
*/
logoImage?: string | Buffer;
/**
* Ratio of the logo size to the QR code size.
*
* @defaultValue 0.2
*/
logoScale?: number;
/**
* Size of margins around the logo image in pixels.
*
* @defaultValue 6
*/
logoMargin?: number;
/**
* Corner radius of the logo image in pixels.
*
* @defaultValue 8
*/
logoCornerRadius?: number;
/**
* @deprecated
*
* Ratio of the real size to the full size of the blocks.
*
* This can be helpful when you want to make more parts of the background visible.
*
* @deafultValue 0.4
*/
dotScale?: number;
};
export class AwesomeQR {
private canvas: Canvas;
private canvasContext: CanvasRenderingContext2D;
private qrCode?: QRCodeModel;
private options: Options;
static CorrectLevel = QRErrorCorrectLevel;
private static defaultComponentOptions: ComponentOptions = {
data: {
scale: 1,
},
timing: {
scale: 1,
protectors: false,
},
alignment: {
scale: 1,
protectors: false,
},
cornerAlignment: {
scale: 1,
protectors: true,
},
};
static defaultOptions: Options = {
text: "",
size: 400,
margin: 20,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRErrorCorrectLevel.M,
backgroundImage: undefined,
backgroundDimming: "rgba(0,0,0,0)",
logoImage: undefined,
logoScale: 0.2,
logoMargin: 4,
logoCornerRadius: 8,
whiteMargin: true,
components: AwesomeQR.defaultComponentOptions,
autoColor: true,
};
constructor(options: Partial<Options>) {
const _options = Object.assign({}, options);
(Object.keys(AwesomeQR.defaultOptions) as (keyof Options)[]).forEach((k) => {
if (!(k in _options)) {
Object.defineProperty(_options, k, { value: AwesomeQR.defaultOptions[k], enumerable: true, writable: true });
}
});
if (!_options.components) {
_options.components = AwesomeQR.defaultComponentOptions;
} else if (typeof _options.components === "object") {
(Object.keys(AwesomeQR.defaultComponentOptions) as (keyof ComponentOptions)[]).forEach((k) => {
if (!(k in _options.components!)) {
Object.defineProperty(_options.components!, k, {
value: AwesomeQR.defaultComponentOptions[k],
enumerable: true,
writable: true,
});
} else {
Object.defineProperty(_options.components!, k, {
value: { ...AwesomeQR.defaultComponentOptions[k], ..._options.components![k] },
enumerable: true,
writable: true,
});
}
});
}
if (_options.dotScale !== null && _options.dotScale !== undefined) {
if (_options.dotScale! <= 0 || _options.dotScale! > 1) {
throw new Error("dotScale should be in range (0, 1].");
}
_options.components.data!.scale = _options.dotScale;
_options.components.timing!.scale = _options.dotScale;
_options.components.alignment!.scale = _options.dotScale;
}
this.options = _options as Options;
this.canvas = createCanvas(options.size!, options.size!);
this.canvasContext = this.canvas.getContext("2d")!;
this.qrCode = new QRCodeModel(-1, this.options.correctLevel!);
if (Number.isInteger(this.options.maskPattern)) {
this.qrCode.maskPattern = this.options.maskPattern!;
}
if (Number.isInteger(this.options.version)) {
this.qrCode.typeNumber = this.options.version!;
}
this.qrCode.addData(this.options.text);
this.qrCode.make();
}
draw(): Promise<Buffer | ArrayBuffer | string | undefined> {
return new Promise((resolve) => this._draw().then(resolve));
}
private _clear() {
this.canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
private static _prepareRoundedCornerClip(
canvasContext: CanvasRenderingContext2D,
x: number,
y: number,
w: number,
h: number,
r: number
) {
canvasContext.beginPath();
canvasContext.moveTo(x, y);
canvasContext.arcTo(x + w, y, x + w, y + h, r);
canvasContext.arcTo(x + w, y + h, x, y + h, r);
canvasContext.arcTo(x, y + h, x, y, r);
canvasContext.arcTo(x, y, x + w, y, r);
canvasContext.closePath();
}
private static _getAverageRGB(image: Image) {
const blockSize = 5;
const defaultRGB = {
r: 0,
g: 0,
b: 0,
};
let width, height;
let i = -4;
const rgb = {
r: 0,
g: 0,
b: 0,
};
let count = 0;
height = image.naturalHeight || image.height;
width = image.naturalWidth || image.width;
const canvas = createCanvas(width, height);
const context = canvas.getContext("2d");
if (!context) {
return defaultRGB;
}
context.drawImage(image, 0, 0);
let data;
try {
data = context.getImageData(0, 0, width, height);
} catch (e) {
return defaultRGB;
}
while ((i += blockSize * 4) < data.data.length) {
if (data.data[i] > 200 || data.data[i + 1] > 200 || data.data[i + 2] > 200) continue;
++count;
rgb.r += data.data[i];
rgb.g += data.data[i + 1];
rgb.b += data.data[i + 2];
}
rgb.r = ~~(rgb.r / count);
rgb.g = ~~(rgb.g / count);
rgb.b = ~~(rgb.b / count);
return rgb;
}
private static _drawDot(
canvasContext: CanvasRenderingContext2D,
centerX: number,
centerY: number,
nSize: number,
xyOffset: number = 0,
dotScale: number = 1
) {
canvasContext.fillRect(
(centerX + xyOffset) * nSize,
(centerY + xyOffset) * nSize,
dotScale * nSize,
dotScale * nSize
);
}
private static _drawAlignProtector(
canvasContext: CanvasRenderingContext2D,
centerX: number,
centerY: number,
nSize: number
) {
canvasContext.clearRect((centerX - 2) * nSize, (centerY - 2) * nSize, 5 * nSize, 5 * nSize);
canvasContext.fillRect((centerX - 2) * nSize, (centerY - 2) * nSize, 5 * nSize, 5 * nSize);
}
private static _drawAlign(
canvasContext: CanvasRenderingContext2D,
centerX: number,
centerY: number,
nSize: number,
xyOffset: number = 0,
dotScale: number = 1,
colorDark: string,
hasProtector: boolean
) {
const oldFillStyle = canvasContext.fillStyle;
canvasContext.fillStyle = colorDark;
new Array(4).fill(0).map((_, i) => {
AwesomeQR._drawDot(canvasContext, centerX - 2 + i, centerY - 2, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 2, centerY - 2 + i, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 2 - i, centerY + 2, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX - 2, centerY + 2 - i, nSize, xyOffset, dotScale);
});
AwesomeQR._drawDot(canvasContext, centerX, centerY, nSize, xyOffset, dotScale);
if (!hasProtector) {
canvasContext.fillStyle = "rgba(255, 255, 255, 0.6)";
new Array(2).fill(0).map((_, i) => {
AwesomeQR._drawDot(canvasContext, centerX - 1 + i, centerY - 1, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 1, centerY - 1 + i, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 1 - i, centerY + 1, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX - 1, centerY + 1 - i, nSize, xyOffset, dotScale);
});
}
canvasContext.fillStyle = oldFillStyle;
}
private async _draw(): Promise<Buffer | Uint8Array | string | undefined> {
const nCount = this.qrCode?.moduleCount!;
const rawSize = this.options.size!;
let rawMargin = this.options.margin!;
if (rawMargin < 0 || rawMargin * 2 >= rawSize) {
rawMargin = 0;
}
const margin = Math.ceil(rawMargin);
const rawViewportSize = rawSize - 2 * rawMargin;
const whiteMargin = this.options.whiteMargin!;
const backgroundDimming = this.options.backgroundDimming!;
const nSize = Math.ceil(rawViewportSize / nCount);
const viewportSize = nSize * nCount;
const size = viewportSize + 2 * margin;
const mainCanvas = createCanvas(size, size);
const mainCanvasContext = mainCanvas.getContext("2d");
this._clear();
// Translate to make the top and left margins off the viewport
mainCanvasContext.save();
mainCanvasContext.translate(margin, margin);
const backgroundCanvas = createCanvas(size, size);
const backgroundCanvasContext = backgroundCanvas.getContext("2d");
let parsedGIFBackground = null;
let gifFrames: any[] = [];
if (!!this.options.gifBackground) {
const gif = parseGIF(this.options.gifBackground);
parsedGIFBackground = gif;
gifFrames = decompressFrames(gif, true);
if (this.options.autoColor) {
let r = 0,
g = 0,
b = 0;
let count = 0;
for (let i = 0; i < gifFrames[0].colorTable.length; i++) {
const c = gifFrames[0].colorTable[i];
if (c[0] > 200 || c[1] > 200 || c[2] > 200) continue;
if (c[0] === 0 && c[1] === 0 && c[2] === 0) continue;
count++;
r += c[0];
g += c[1];
b += c[2];
}
r = ~~(r / count);
g = ~~(g / count);
b = ~~(b / count);
this.options.colorDark = `rgb(${r},${g},${b})`;
}
} else if (!!this.options.backgroundImage) {
const backgroundImage = await loadImage(this.options.backgroundImage!);
if (this.options.autoColor) {
const avgRGB = AwesomeQR._getAverageRGB(backgroundImage);
this.options.colorDark = `rgb(${avgRGB.r},${avgRGB.g},${avgRGB.b})`;
}
backgroundCanvasContext.drawImage(
backgroundImage,
0,
0,
backgroundImage.width,
backgroundImage.height,
0,
0,
size,
size
);
backgroundCanvasContext.rect(0, 0, size, size);
backgroundCanvasContext.fillStyle = backgroundDimming;
backgroundCanvasContext.fill();
} else {
backgroundCanvasContext.rect(0, 0, size, size);
backgroundCanvasContext.fillStyle = this.options.colorLight!;
backgroundCanvasContext.fill();
}
const alignmentPatternCenters = QRUtil.getPatternPosition(this.qrCode!.typeNumber);
const dataScale = this.options.components?.data?.scale || defaultScale;
const dataXyOffset = (1 - dataScale) * 0.5;
for (let row = 0; row < nCount; row++) {
for (let col = 0; col < nCount; col++) {
const bIsDark = this.qrCode!.isDark(row, col);
const isBlkPosCtr = (col < 8 && (row < 8 || row >= nCount - 8)) || (col >= nCount - 8 && row < 8);
const isTiming = (row == 6 && col >= 8 && col <= nCount - 8) || (col == 6 && row >= 8 && row <= nCount - 8);
let isProtected = isBlkPosCtr || isTiming;
for (let i = 1; i < alignmentPatternCenters.length - 1; i++) {
isProtected =
isProtected ||
(row >= alignmentPatternCenters[i] - 2 &&
row <= alignmentPatternCenters[i] + 2 &&
col >= alignmentPatternCenters[i] - 2 &&
col <= alignmentPatternCenters[i] + 2);
}
const nLeft = col * nSize + (isProtected ? 0 : dataXyOffset * nSize);
const nTop = row * nSize + (isProtected ? 0 : dataXyOffset * nSize);
mainCanvasContext.strokeStyle = bIsDark ? this.options.colorDark! : this.options.colorLight!;
mainCanvasContext.lineWidth = 0.5;
mainCanvasContext.fillStyle = bIsDark ? this.options.colorDark! : "rgba(255, 255, 255, 0.6)";
if (alignmentPatternCenters.length === 0) {
if (!isProtected) {
mainCanvasContext.fillRect(
nLeft,
nTop,
(isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize,
(isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize
);
}
} else {
const inAgnRange = col < nCount - 4 && col >= nCount - 4 - 5 && row < nCount - 4 && row >= nCount - 4 - 5;
if (!isProtected && !inAgnRange) {
// if align pattern list is empty, then it means that we don't need to leave room for the align patterns
mainCanvasContext.fillRect(
nLeft,
nTop,
(isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize,
(isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize
);
}
}
}
}
const cornerAlignmentCenter = alignmentPatternCenters[alignmentPatternCenters.length - 1];
// - PROTECTORS
const protectorStyle = "rgba(255, 255, 255, 0.6)";
// - FINDER PROTECTORS
mainCanvasContext.fillStyle = protectorStyle;
mainCanvasContext.fillRect(0, 0, 8 * nSize, 8 * nSize);
mainCanvasContext.fillRect(0, (nCount - 8) * nSize, 8 * nSize, 8 * nSize);
mainCanvasContext.fillRect((nCount - 8) * nSize, 0, 8 * nSize, 8 * nSize);
// - TIMING PROTECTORS
if (this.options.components?.timing?.protectors) {
mainCanvasContext.fillRect(8 * nSize, 6 * nSize, (nCount - 8 - 8) * nSize, nSize);
mainCanvasContext.fillRect(6 * nSize, 8 * nSize, nSize, (nCount - 8 - 8) * nSize);
}
// - CORNER ALIGNMENT PROTECTORS
if (this.options.components?.cornerAlignment?.protectors) {
AwesomeQR._drawAlignProtector(mainCanvasContext, cornerAlignmentCenter, cornerAlignmentCenter, nSize);
}
// - ALIGNMENT PROTECTORS
if (this.options.components?.alignment?.protectors) {
for (let i = 0; i < alignmentPatternCenters.length; i++) {
for (let j = 0; j < alignmentPatternCenters.length; j++) {
const agnX = alignmentPatternCenters[j];
const agnY = alignmentPatternCenters[i];
if (agnX === 6 && (agnY === 6 || agnY === cornerAlignmentCenter)) {
continue;
} else if (agnY === 6 && (agnX === 6 || agnX === cornerAlignmentCenter)) {
continue;
} else if (agnX === cornerAlignmentCenter && agnY === cornerAlignmentCenter) {
continue;
} else {
AwesomeQR._drawAlignProtector(mainCanvasContext, agnX, agnY, nSize);
}
}
}
}
// - FINDER
mainCanvasContext.fillStyle = this.options.colorDark!;
mainCanvasContext.fillRect(0, 0, 7 * nSize, nSize);
mainCanvasContext.fillRect((nCount - 7) * nSize, 0, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, 6 * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect((nCount - 7) * nSize, 6 * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, (nCount - 7) * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, (nCount - 7 + 6) * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect(6 * nSize, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect((nCount - 7) * nSize, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect((nCount - 7 + 6) * nSize, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect(0, (nCount - 7) * nSize, nSize, 7 * nSize);
mainCanvasContext.fillRect(6 * nSize, (nCount - 7) * nSize, nSize, 7 * nSize);
mainCanvasContext.fillRect(2 * nSize, 2 * nSize, 3 * nSize, 3 * nSize);
mainCanvasContext.fillRect((nCount - 7 + 2) * nSize, 2 * nSize, 3 * nSize, 3 * nSize);
mainCanvasContext.fillRect(2 * nSize, (nCount - 7 + 2) * nSize, 3 * nSize, 3 * nSize);
// - TIMING
const timingScale = this.options.components?.timing?.scale || defaultScale;
const timingXyOffset = (1 - timingScale) * 0.5;
for (let i = 0; i < nCount - 8; i += 2) {
AwesomeQR._drawDot(mainCanvasContext, 8 + i, 6, nSize, timingXyOffset, timingScale);
AwesomeQR._drawDot(mainCanvasContext, 6, 8 + i, nSize, timingXyOffset, timingScale);
}
// - CORNER ALIGNMENT PROTECTORS
const cornerAlignmentScale = this.options.components?.cornerAlignment?.scale || defaultScale;
const cornerAlignmentXyOffset = (1 - cornerAlignmentScale) * 0.5;
AwesomeQR._drawAlign(
mainCanvasContext,
cornerAlignmentCenter,
cornerAlignmentCenter,
nSize,
cornerAlignmentXyOffset,
cornerAlignmentScale,
this.options.colorDark!,
this.options.components?.cornerAlignment?.protectors || false
);
// - ALIGNEMNT
const alignmentScale = this.options.components?.alignment?.scale || defaultScale;
const alignmentXyOffset = (1 - alignmentScale) * 0.5;
for (let i = 0; i < alignmentPatternCenters.length; i++) {
for (let j = 0; j < alignmentPatternCenters.length; j++) {
const agnX = alignmentPatternCenters[j];
const agnY = alignmentPatternCenters[i];
if (agnX === 6 && (agnY === 6 || agnY === cornerAlignmentCenter)) {
continue;
} else if (agnY === 6 && (agnX === 6 || agnX === cornerAlignmentCenter)) {
continue;
} else if (agnX === cornerAlignmentCenter && agnY === cornerAlignmentCenter) {
continue;
} else {
AwesomeQR._drawAlign(
mainCanvasContext,
agnX,
agnY,
nSize,
alignmentXyOffset,
alignmentScale,
this.options.colorDark!,
this.options.components?.alignment?.protectors || false
);
}
}
}
// Fill the margin
if (whiteMargin) {
mainCanvasContext.fillStyle = "#FFFFFF";
mainCanvasContext.fillRect(-margin, -margin, size, margin);
mainCanvasContext.fillRect(-margin, viewportSize, size, margin);
mainCanvasContext.fillRect(viewportSize, -margin, margin, size);
mainCanvasContext.fillRect(-margin, -margin, margin, size);
}
if (!!this.options.logoImage) {
const logoImage = await loadImage(this.options.logoImage!);
let logoScale = this.options.logoScale!;
let logoMargin = this.options.logoMargin!;
let logoCornerRadius = this.options.logoCornerRadius!;
if (logoScale <= 0 || logoScale >= 1.0) {
logoScale = 0.2;
}
if (logoMargin < 0) {
logoMargin = 0;
}
if (logoCornerRadius < 0) {
logoCornerRadius = 0;
}
const logoSize = viewportSize * logoScale;
const x = 0.5 * (size - logoSize);
const y = x;
// Restore the canvas
// After restoring, the top and left margins should be taken into account
mainCanvasContext.restore();
// Clean the area that the logo covers (including margins)
mainCanvasContext.fillStyle = "#FFFFFF";
mainCanvasContext.save();
AwesomeQR._prepareRoundedCornerClip(
mainCanvasContext,
x - logoMargin,
y - logoMargin,
logoSize + 2 * logoMargin,
logoSize + 2 * logoMargin,
logoCornerRadius + logoMargin
);
mainCanvasContext.clip();
const oldGlobalCompositeOperation = mainCanvasContext.globalCompositeOperation;
mainCanvasContext.globalCompositeOperation = "destination-out";
mainCanvasContext.fill();
mainCanvasContext.globalCompositeOperation = oldGlobalCompositeOperation;
mainCanvasContext.restore();
// Draw logo image
mainCanvasContext.save();
AwesomeQR._prepareRoundedCornerClip(mainCanvasContext, x, y, logoSize, logoSize, logoCornerRadius);
mainCanvasContext.clip();
mainCanvasContext.drawImage(logoImage, x, y, logoSize, logoSize);
mainCanvasContext.restore();
// Re-translate the canvas to translate the top and left margins into invisible area
mainCanvasContext.save();
mainCanvasContext.translate(margin, margin);
}
if (!!parsedGIFBackground) {
let gifOutput: any;
// Reuse in order to apply the patch
let backgroundCanvas: Canvas;
let backgroundCanvasContext: CanvasRenderingContext2D;
let patchCanvas: Canvas;
let patchCanvasContext: CanvasRenderingContext2D;
let patchData: any;
gifFrames.forEach(function (frame: any) {
if (!gifOutput) {
gifOutput = new GIFEncoder(rawSize, rawSize);
gifOutput.setDelay(frame.delay);
gifOutput.setRepeat(0);
}
const { width, height } = frame.dims;
if (!backgroundCanvas) {
backgroundCanvas = createCanvas(width, height);
backgroundCanvasContext = backgroundCanvas.getContext("2d");
backgroundCanvasContext.rect(0, 0, backgroundCanvas.width, backgroundCanvas.height);
backgroundCanvasContext.fillStyle = "#ffffff";
backgroundCanvasContext.fill();
}
if (!patchCanvas || !patchData || width !== patchCanvas.width || height !== patchCanvas.height) {
patchCanvas = createCanvas(width, height);
patchCanvasContext = patchCanvas.getContext("2d");
patchData = patchCanvasContext.createImageData(width, height);
}
patchData.data.set(frame.patch);
patchCanvasContext.putImageData(patchData, 0, 0);
backgroundCanvasContext.drawImage(patchCanvas, frame.dims.left, frame.dims.top);
const unscaledCanvas = createCanvas(size, size);
const unscaledCanvasContext = unscaledCanvas.getContext("2d");
unscaledCanvasContext.drawImage(backgroundCanvas, 0, 0, size, size);
unscaledCanvasContext.rect(0, 0, size, size);
unscaledCanvasContext.fillStyle = backgroundDimming;
unscaledCanvasContext.fill();
unscaledCanvasContext.drawImage(mainCanvas, 0, 0, size, size);
// Scale the final image
const outCanvas = createCanvas(rawSize, rawSize);
const outCanvasContext = outCanvas.getContext("2d");
outCanvasContext.drawImage(unscaledCanvas, 0, 0, rawSize, rawSize);
gifOutput.addFrame(outCanvasContext.getImageData(0, 0, outCanvas.width, outCanvas.height).data);
});
if (!gifOutput) {
throw new Error("No frames.");
}
gifOutput.finish();
if (isElement(this.canvas)) {
const u8array = gifOutput.stream().toFlattenUint8Array();
const binary = u8array.reduce((bin: string, u8: number) => bin + String.fromCharCode(u8), "");
return Promise.resolve(`data:image/gif;base64,${window.btoa(binary)}`);
}
return Promise.resolve(Buffer.from(gifOutput.stream().toFlattenUint8Array()));
} else {
// Swap and merge the foreground and the background
backgroundCanvasContext.drawImage(mainCanvas, 0, 0, size, size);
mainCanvasContext.drawImage(backgroundCanvas, -margin, -margin, size, size);
// Scale the final image
const outCanvas = createCanvas(rawSize, rawSize); //document.createElement("canvas");
const outCanvasContext = outCanvas.getContext("2d");
outCanvasContext.drawImage(mainCanvas, 0, 0, rawSize, rawSize);
this.canvas = outCanvas;
if (isElement(this.canvas)) {
return Promise.resolve(this.canvas.toDataURL());
}
return Promise.resolve(this.canvas.toBuffer());
}
}
}
function isElement(obj: any): boolean {
try {
//Using W3 DOM2 (works for FF, Opera and Chrome)
return obj instanceof HTMLElement;
} catch (e) {
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have (works on IE7)
return (
typeof obj === "object" &&
obj.nodeType === 1 &&
typeof obj.style === "object" &&
typeof obj.ownerDocument === "object"
);
}
} | the_stack |
import { LayoutUtil } from "./layout_utils"
import { ListViewItem } from "./listviewitem";
import { TimerMgr } from "../timer/timer_mgr";
import { gen_handler } from "../util";
export class ListView
{
private scrollview:cc.ScrollView;
private mask:cc.Mask;
private content:cc.Node;
private item_tpl:cc.Node;
private item_pool:ListViewItem[];
private dir:number;
private width:number;
private height:number;
private original_width:number;
private original_height:number;
private gap_x:number;
private gap_y:number;
private padding_left:number;
private padding_right:number;
private padding_top:number;
private padding_bottom:number;
private item_anchorX:number;
private item_anchorY:number;
private row:number;
private col:number;
private item_width:number;
private item_height:number;
private content_width:number;
private content_height:number;
private item_class:new() => ListViewItem;
private cb_host:any;
private scroll_to_end_cb:()=>void;
private auto_scrolling:boolean;
private packItems:PackItem[];
private start_index:number;
private stop_index:number;
private _selected_index:number = -1;
private renderDirty:boolean;
private timer:number;
constructor(params:ListViewParams)
{
this.scrollview = params.scrollview;
this.mask = params.mask;
this.content = params.content;
this.item_tpl = params.item_tpl;
this.item_tpl.active = false;
this.item_width = this.item_tpl.width;
this.item_height = this.item_tpl.height;
this.dir = params.direction || ListViewDir.Vertical;
this.width = params.width || this.scrollview.node.width;
this.height = params.height || this.scrollview.node.height;
this.gap_x = params.gap_x || 0;
this.gap_y = params.gap_y || 0;
this.padding_left = params.padding_left || 0;
this.padding_right = params.padding_right || 0;
this.padding_top = params.padding_top || 0;
this.padding_bottom = params.padding_bottom || 0;
this.item_anchorX = params.item_anchorX != null ? params.item_anchorX : 0;
this.item_anchorY = params.item_anchorY != null ? params.item_anchorY : 1;
this.row = params.row || 1;
this.col = params.column || 1;
this.cb_host = params.cb_host;
this.scroll_to_end_cb = params.scroll_to_end_cb;
this.item_class = params.item_class;
this.auto_scrolling = params.auto_scrolling || false;
this.item_pool = [];
if(this.dir == ListViewDir.Vertical)
{
const content_width = (this.item_width + this.gap_x) * this.col - this.gap_x + this.padding_left + this.padding_right;
if(content_width > this.width)
{
cc.log("content_width > width, resize listview to content_width,", this.width, "->", content_width);
this.width = content_width;
}
this.set_content_size(this.width, 0);
}
else
{
const content_height = (this.item_height + this.gap_y) * this.row - this.gap_y + this.padding_top + this.padding_bottom;
if(content_height > this.height)
{
cc.log("content_height > height, resize listview to content_height,", this.height, "->", content_height);
this.height = content_height;
}
this.set_content_size(0, this.height);
}
this.original_width = this.width;
this.original_height = this.height;
this.mask.node.setContentSize(this.width, this.height);
this.scrollview.node.setContentSize(this.width, this.height);
this.scrollview.vertical = this.dir == ListViewDir.Vertical;
this.scrollview.horizontal = this.dir == ListViewDir.Horizontal;
this.scrollview.inertia = true;
this.scrollview.node.on("scrolling", this.on_scrolling, this);
this.scrollview.node.on("scroll-to-bottom", this.on_scroll_to_end, this);
this.scrollview.node.on("scroll-to-right", this.on_scroll_to_end, this);
this.scrollview.node.on(cc.Node.EventType.TOUCH_START, this.on_scroll_touch_start, this);
this.scrollview.node.on(cc.Node.EventType.TOUCH_END, this.on_scroll_touch_end, this);
this.scrollview.node.on(cc.Node.EventType.TOUCH_CANCEL, this.on_scroll_touch_cancel, this);
this.timer = TimerMgr.getInst().add_updater(gen_handler(this.onUpdate, this), "listView render timer");
// cc.log("constructor", this.mask.width, this.mask.height, this.scrollview.node.width, this.scrollview.node.height, this.content.width, this.content.height);
}
private _touchBeganPosition:cc.Vec2;
private _touchEndPosition:cc.Vec2;
private on_scroll_touch_start(event:cc.Event.EventTouch)
{
this._touchBeganPosition = event.touch.getLocation();
}
private on_scroll_touch_cancel(event:cc.Event.EventTouch)
{
this._touchEndPosition = event.touch.getLocation();
this.handle_release_logic();
}
private on_scroll_touch_end(event:cc.Event.EventTouch)
{
this._touchEndPosition = event.touch.getLocation();
this.handle_release_logic();
}
private handle_release_logic()
{
const touchPos = this._touchEndPosition;
const moveOffset = this._touchBeganPosition.sub(this._touchEndPosition);
const dragDirection = this.get_drag_direction(moveOffset);
if(dragDirection != 0)
{
return;
}
if(!this.packItems || !this.packItems.length)
{
return;
}
//无滑动的情况下点击
const touchPosInContent = this.content.convertToNodeSpaceAR(touchPos);
for(let i = this.start_index; i <= this.stop_index; i++)
{
const packItem = this.packItems[i];
if(packItem && packItem.item && packItem.item.node.getBoundingBox().contains(touchPosInContent))
{
packItem.item.onTouchEnd(packItem.item.node.convertToNodeSpaceAR(touchPos), packItem.data, i);
break;
}
}
}
private get_drag_direction(moveOffset:cc.Vec2) {
if (this.dir === ListViewDir.Horizontal)
{
if (Math.abs(moveOffset.x) < 3) { return 0; }
return (moveOffset.x > 0 ? 1 : -1);
}
else if (this.dir === ListViewDir.Vertical)
{
// 由于滚动 Y 轴的原点在在右上角所以应该是小于 0
if (Math.abs(moveOffset.y) < 3) { return 0; }
return (moveOffset.y < 0 ? 1 : -1);
}
}
private on_scroll_to_end()
{
if(this.scroll_to_end_cb)
{
this.scroll_to_end_cb.call(this.cb_host);
}
}
private last_content_pos:number;
private on_scrolling()
{
let pos:number;
let threshold:number;
if(this.dir == ListViewDir.Vertical)
{
pos = this.content.y;
threshold = this.item_height;
}
else
{
pos = this.content.x;
threshold = this.item_width;
}
if(this.last_content_pos != null && Math.abs(pos - this.last_content_pos) < threshold)
{
return;
}
this.last_content_pos = pos;
this.render();
}
private render()
{
if(!this.packItems || !this.packItems.length)
{
return;
}
if(this.dir == ListViewDir.Vertical)
{
let posy = this.content.y;
// cc.log("onscrolling, content posy=", posy);
if(posy < 0)
{
posy = 0;
}
else if(posy > this.content_height - this.height)
{
posy = this.content_height - this.height;
}
let viewport_start = -posy;
let viewport_stop = viewport_start - this.height;
// while(this.packItems[start].y - this.item_height > viewport_start)
// {
// start++;
// }
// while(this.packItems[stop].y < viewport_stop)
// {
// stop--;
// }
let start = this.indexFromOffset(viewport_start);
let stop = this.indexFromOffset(viewport_stop);
//expand viewport for better experience
start = Math.max(start - this.col, 0);
stop = Math.min(this.packItems.length - 1, stop + this.col);
if(start != this.start_index)
{
this.start_index = start;
this.renderDirty = true;
}
if(stop != this.stop_index)
{
this.stop_index = stop;
this.renderDirty = true;
}
}
else
{
let posx = this.content.x;
// cc.log("onscrolling, content posx=", posx);
if(posx > 0)
{
posx = 0;
}
else if(posx < this.width - this.content_width)
{
posx = this.width - this.content_width;
}
let viewport_start = -posx;
let viewport_stop = viewport_start + this.width;
let start = this.indexFromOffset(viewport_start);
let stop = this.indexFromOffset(viewport_stop);
//expand viewport for better experience
start = Math.max(start - this.row, 0);
stop = Math.min(this.packItems.length - 1, stop + this.row);
if(start != this.start_index)
{
this.start_index = start;
this.renderDirty = true;
}
if(stop != this.stop_index)
{
this.stop_index = stop;
this.renderDirty = true;
}
}
}
onUpdate()
{
if(this.renderDirty && cc.isValid(this.scrollview.node))
{
cc.log("listView, render_from:", this.start_index, this.stop_index);
this.render_items();
this.renderDirty = false;
}
}
//不支持多行多列
private indexFromOffset(offset:number)
{
let low = 0;
let high = 0;
let max_idx = 0;
high = max_idx = this.packItems.length - 1;
if(this.dir == ListViewDir.Vertical)
{
while(high >= low)
{
const index = low + Math.floor((high - low) / 2);
const itemStart = this.packItems[index].y;
const itemStop = index < max_idx ? this.packItems[index + 1].y : -this.content_height;
if(offset <= itemStart && offset >= itemStop)
{
return index;
}
else if(offset > itemStart)
{
high = index - 1;
}
else
{
low = index + 1;
}
}
}
else
{
while(high >= low)
{
const index = low + Math.floor((high - low) / 2);
const itemStart = this.packItems[index].x;
const itemStop = index < max_idx ? this.packItems[index + 1].x : this.content_width;
if(offset >= itemStart && offset <= itemStop)
{
return index;
}
else if(offset > itemStart)
{
low = index + 1;
}
else
{
high = index - 1;
}
}
}
return -1;
}
select_data(data)
{
const idx = this.packItems.findIndex(item => item.data == data);
if(idx != -1)
{
this.select_item(idx);
}
}
select_item(index:number)
{
if(index == this._selected_index)
{
return;
}
if(this._selected_index != -1)
{
this.inner_select_item(this._selected_index, false);
}
this._selected_index = index;
this.inner_select_item(index, true);
}
private inner_select_item(index:number, is_select:boolean)
{
let packItem:PackItem = this.packItems[index];
if(!packItem)
{
cc.warn("inner_select_item index is out of range{", 0, this.packItems.length - 1, "}", index);
return;
}
packItem.is_select = is_select;
if(packItem.item)
{
packItem.item.onSetSelect(is_select, index);
if(is_select)
{
packItem.item.onSelected(packItem.data, index);
}
}
}
private spawn_item(index:number):ListViewItem
{
let item:ListViewItem = this.item_pool.pop();
if(!item)
{
item = cc.instantiate(this.item_tpl).addComponent(this.item_class) as ListViewItem;
item.node.active = true;
//仅仅改变父节点锚点,子元素位置不会随之变化
// item.node.setAnchorPoint(this.item_anchorX, this.item_anchorY);
LayoutUtil.set_pivot_smart(item.node, this.item_anchorX, this.item_anchorY);
item.onInit();
// cc.log("spawn_item", index);
}
item.node.parent = this.content;
return item;
}
private recycle_item(packItem:PackItem)
{
const item = packItem.item;
if(item && cc.isValid(item.node))
{
item.onRecycle(packItem.data);
item.node.removeFromParent();
this.item_pool.push(item);
packItem.item = null;
}
}
private clear_items()
{
if(this.packItems)
{
this.packItems.forEach(packItem => {
this.recycle_item(packItem);
});
}
}
private render_items()
{
let packItem:PackItem;
for(let i = 0; i < this.start_index; i++)
{
packItem = this.packItems[i];
if(packItem.item)
{
// cc.log("recycle_item", i);
this.recycle_item(packItem);
}
}
for(let i = this.packItems.length - 1; i > this.stop_index; i--)
{
packItem = this.packItems[i];
if(packItem.item)
{
// cc.log("recycle_item", i);
this.recycle_item(packItem);
}
}
for(let i = this.start_index; i <= this.stop_index; i++)
{
packItem = this.packItems[i];
if(!packItem.item)
{
// cc.log("render_item", i);
packItem.item = this.spawn_item(i);
packItem.item.onSetData(packItem.data, i);
packItem.item.onSetSelect(packItem.is_select, i);
if(packItem.is_select)
{
packItem.item.onSelected(packItem.data, i);
}
}
//列表添加与删除时item位置会变化,因此每次render_items都要执行
// packItem.item.node.setPosition(packItem.x, packItem.y);
packItem.item.setLeftTop(packItem.x, packItem.y);
}
}
private pack_item(data:any):PackItem
{
return {x:0, y:0, data:data, item:null, is_select:false};
}
private layout_items(start:number)
{
// cc.log("layout_items, start=", start);
for(let index = start, stop = this.packItems.length; index < stop; index++)
{
const packItem = this.packItems[index];
if(this.dir == ListViewDir.Vertical)
{
[packItem.x, packItem.y] = LayoutUtil.vertical_layout(index, this.item_width, this.item_height, this.col, this.gap_x, this.gap_y, this.padding_left, this.padding_top);
}
else
{
[packItem.x, packItem.y] = LayoutUtil.horizontal_layout(index, this.item_width, this.item_height, this.row, this.gap_x, this.gap_y, this.padding_left, this.padding_top);
}
}
}
private adjust_content()
{
if(this.packItems.length <= 0) {
this.set_content_size(0, 0);
return;
}
const last_packItem = this.packItems[this.packItems.length - 1];
if(this.dir == ListViewDir.Vertical) {
const height = Math.max(this.height, this.item_height - last_packItem.y + this.padding_bottom);
this.set_content_size(this.content_width, height);
}
else {
const width = Math.max(this.width, last_packItem.x + this.item_width + this.padding_right);
this.set_content_size(width, this.content_height);
}
}
private set_content_size(width:number, height:number)
{
if(this.content_width != width)
{
this.content_width = width;
this.content.width = width;
}
if(this.content_height != height)
{
this.content_height = height;
this.content.height = height;
}
// cc.log("ListView, set_content_size", width, height, this.content.width, this.content.height);
}
set_viewport(width?:number, height?:number)
{
if(width == null)
{
width = this.width;
}
else if(width > this.content_width)
{
width = this.content_width;
}
if(height == null)
{
height = this.height;
}
else if(height > this.content_height)
{
height = this.content_height;
}
//设置遮罩区域尺寸
this.width = width;
this.height = height;
this.mask.node.setContentSize(width, height);
this.scrollview.node.setContentSize(width, height);
this.render();
}
renderAll(value:boolean)
{
let width:number;
let height:number;
if(value)
{
width = this.content_width;
height = this.content_height;
}
else
{
width = this.original_width;
height = this.original_height;
}
this.set_viewport(width, height);
}
set_data(datas:any[])
{
if(this.packItems)
{
this.clear_items();
this.packItems.length = 0;
}
else
{
this.packItems = [];
}
datas.forEach(data => {
let packItem = this.pack_item(data);
this.packItems.push(packItem);
});
this.layout_items(0);
this.adjust_content();
this.start_index = -1;
this.stop_index = -1;
if(this.dir == ListViewDir.Vertical)
{
this.content.y = 0;
}
else
{
this.content.x = 0;
}
if(this.packItems.length > 0)
{
this.render();
}
}
insert_data(index:number, ...datas:any[])
{
if(datas.length == 0 )
{
cc.log("nothing to insert");
return;
}
if(!this.packItems)
{
this.packItems = [];
}
if(index < 0 || index > this.packItems.length)
{
cc.warn("insert_data, invalid index", index);
return;
}
let is_append = index == this.packItems.length;
let packItems:PackItem[] = [];
datas.forEach(data => {
let packItem = this.pack_item(data);
packItems.push(packItem);
});
this.packItems.splice(index, 0, ...packItems);
this.layout_items(index);
this.adjust_content();
this.start_index = -1;
this.stop_index = -1;
if(this.auto_scrolling && is_append)
{
this.scroll_to_end();
}
this.render();
}
remove_data(index:number, count:number = 1)
{
if(!this.packItems)
{
cc.log("call set_data before call this method");
return;
}
if(index < 0 || index >= this.packItems.length)
{
cc.warn("remove_data, invalid index", index);
return;
}
if(count < 1)
{
cc.log("nothing to remove");
return;
}
let old_length = this.packItems.length;
let del_items = this.packItems.splice(index, count);
//回收node
del_items.forEach(packItem => {
this.recycle_item(packItem);
});
//重新排序index后面的
if(index + count < old_length)
{
this.layout_items(index);
}
this.adjust_content();
if(this.packItems.length > 0)
{
this.start_index = -1;
this.stop_index = -1;
this.render();
}
}
append_data(...datas:any[])
{
if(!this.packItems)
{
this.packItems = [];
}
this.insert_data(this.packItems.length, ...datas);
}
scroll_to(index:number, time = 0)
{
if(!this.packItems)
{
return;
}
const packItem = this.packItems[index];
if(!packItem)
{
cc.log("scroll_to, index out of range");
return;
}
if(this.dir == ListViewDir.Vertical)
{
const min_y = this.height - this.content_height;
if(min_y >= 0)
{
cc.log("no need to scroll");
return;
}
let y = packItem.y;
if(y < min_y)
{
y = min_y;
cc.log("content reach bottom");
}
const x = this.content.x;
if(time == 0)
{
this.scrollview.setContentPosition(cc.v2(x, -y));
}
else
{
this.scrollview.scrollToOffset(cc.v2(x, -y), time);
}
this.render();
}
else
{
const max_x = this.content_width - this.width;
if(max_x <= 0)
{
cc.log("no need to scroll");
return;
}
let x = packItem.x;
if(x > max_x)
{
x = max_x;
cc.log("content reach right");
}
const y = this.content.y;
if(time == 0)
{
this.scrollview.setContentPosition(cc.v2(-x, y));
}
else
{
this.scrollview.scrollToOffset(cc.v2(-x, y), time);
}
this.render();
}
}
get_scroll_offset()
{
const offset = this.scrollview.getScrollOffset();
if(this.dir == ListViewDir.Vertical)
{
return offset.y;
}
else
{
return offset.x;
}
}
scroll_to_offset(value:number, time = 0)
{
if(this.dir == ListViewDir.Vertical)
{
const x = this.content.x;
if(time == 0)
{
this.scrollview.setContentPosition(cc.v2(x, value));
}
else
{
this.scrollview.scrollToOffset(cc.v2(x, value), time);
}
this.render();
}
else
{
const y = this.content.y;
if(time == 0)
{
this.scrollview.setContentPosition(cc.v2(value, y));
}
else
{
this.scrollview.scrollToOffset(cc.v2(value, y), time);
}
this.render();
}
}
scroll_to_end()
{
if(this.dir == ListViewDir.Vertical)
{
this.scrollview.scrollToBottom();
}
else
{
this.scrollview.scrollToRight();
}
}
refresh_item(index:number, data:any)
{
const packItem = this.get_pack_item(index);
if(!packItem)
{
return;
}
const oldData = packItem.data;
packItem.data = data;
if(packItem.item)
{
packItem.item.onRecycle(oldData);
packItem.item.onSetData(data, index);
}
}
reload_item(index:number)
{
const packItem = this.get_pack_item(index);
if(packItem && packItem.item)
{
packItem.item.onRecycle(packItem.data);
packItem.item.onSetData(packItem.data, index);
}
}
private get_pack_item(index:number)
{
if(!this.packItems)
{
cc.log("call set_data before call this method");
return null;
}
if(index < 0 || index >= this.packItems.length)
{
cc.warn("get_pack_item, invalid index", index);
return null;
}
return this.packItems[index];
}
get_item(index:number)
{
const packItem = this.get_pack_item(index);
return packItem ? packItem.item : null;
}
get_data(index:number)
{
const packItem = this.get_pack_item(index);
return packItem ? packItem.data : null;
}
find_item(predicate:(data:any) => boolean)
{
if(!this.packItems || !this.packItems.length)
{
cc.log("call set_data before call this method");
return null;
}
for(let i = this.start_index; i <= this.stop_index; i++)
{
const packItem = this.packItems[i];
if(predicate(packItem.data))
{
return packItem.item;
}
}
return null;
}
find_index(predicate:(data:any) => boolean)
{
if(!this.packItems || !this.packItems.length)
{
cc.log("call set_data before call this method");
return -1;
}
return this.packItems.findIndex(packItem => {
return predicate(packItem.data);
});
}
get renderedItems()
{
const items:ListViewItem[] = [];
for(let i = this.start_index; i <= this.stop_index; i++)
{
const packItem = this.packItems[i];
if(packItem && packItem.item)
{
items.push(packItem.item);
}
}
return items;
}
get length()
{
if(!this.packItems)
{
cc.log("call set_data before call this method");
return 0;
}
return this.packItems.length;
}
destroy()
{
this.clear_items();
this.item_pool.forEach(item => {
item.onUnInit();
item.node.destroy();
});
this.item_pool = null;
this.packItems = null;
if(this.timer)
{
TimerMgr.getInst().remove(this.timer);
this.timer = null;
}
this.renderDirty = null;
if(cc.isValid(this.scrollview.node))
{
this.scrollview.node.off("scrolling", this.on_scrolling, this);
this.scrollview.node.off("scroll-to-bottom", this.on_scroll_to_end, this);
this.scrollview.node.off("scroll-to-right", this.on_scroll_to_end, this);
this.scrollview.node.off(cc.Node.EventType.TOUCH_START, this.on_scroll_touch_start, this);
this.scrollview.node.off(cc.Node.EventType.TOUCH_END, this.on_scroll_touch_end, this);
this.scrollview.node.off(cc.Node.EventType.TOUCH_CANCEL, this.on_scroll_touch_cancel, this);
}
}
get selected_index():number
{
return this._selected_index;
}
get selected_data():any
{
let packItem:PackItem = this.packItems[this._selected_index];
if(packItem)
{
return packItem.data;
}
return null;
}
set scrollable(value:boolean)
{
if(this.dir == ListViewDir.Vertical)
{
this.scrollview.vertical = value;
}
else
{
this.scrollview.horizontal = value;
}
}
get startIndex()
{
return this.start_index;
}
get stopIndex()
{
return this.stop_index;
}
}
export enum ListViewDir
{
Vertical = 1,
Horizontal = 2,
}
type ListViewParams = {
scrollview:cc.ScrollView;
mask:cc.Mask;
content:cc.Node;
item_tpl:cc.Node;
item_class:new() => ListViewItem; //item对应的类型
direction?:ListViewDir;
width?:number;
height?:number;
gap_x?:number;
gap_y?:number;
padding_left?:number;
padding_right?:number;
padding_top?:number;
padding_bottom?:number;
item_anchorX?:number;
item_anchorY?:number;
row?:number; //水平方向排版时,垂直方向上的行数
column?:number; //垂直方向排版时,水平方向上的列数
cb_host?:any; //回调函数host
scroll_to_end_cb?:()=>void; //滚动到尽头的回调
auto_scrolling?:boolean; //append时自动滚动到尽头
}
type PackItem = {
x:number;
y:number;
data:any;
is_select:boolean;
item:ListViewItem;
} | the_stack |
import { expect } from 'chai';
import { SinonStub, stub } from 'sinon';
import '../testing/setup';
import { DataLayer, Gtag, DynamicConfig } from './types';
import {
getOrCreateDataLayer,
insertScriptTag,
wrapOrCreateGtag,
findGtagScriptOnPage,
promiseAllSettled
} from './helpers';
import { GtagCommand } from './constants';
import { Deferred } from '@firebase/util';
const fakeMeasurementId = 'abcd-efgh-ijkl';
const fakeAppId = 'my-test-app-1234';
const fakeDynamicConfig: DynamicConfig = {
projectId: '---',
appId: fakeAppId,
databaseURL: '---',
storageBucket: '---',
locationId: '---',
apiKey: '---',
authDomain: '---',
messagingSenderId: '---',
measurementId: fakeMeasurementId
};
const fakeDynamicConfigPromises = [Promise.resolve(fakeDynamicConfig)];
describe('Gtag wrapping functions', () => {
it('getOrCreateDataLayer is able to create a new data layer if none exists', () => {
delete window['dataLayer'];
expect(getOrCreateDataLayer('dataLayer')).to.deep.equal([]);
});
it('getOrCreateDataLayer is able to correctly identify an existing data layer', () => {
const existingDataLayer = (window['dataLayer'] = []);
expect(getOrCreateDataLayer('dataLayer')).to.equal(existingDataLayer);
});
it('insertScriptIfNeeded inserts script tag', () => {
expect(findGtagScriptOnPage()).to.be.null;
insertScriptTag('customDataLayerName', fakeMeasurementId);
const scriptTag = findGtagScriptOnPage();
expect(scriptTag).to.not.be.null;
expect(scriptTag!.src).to.contain(`l=customDataLayerName`);
expect(scriptTag!.src).to.contain(`id=${fakeMeasurementId}`);
});
describe('wrapOrCreateGtag() when user has not previously inserted a gtag script tag on this page', () => {
afterEach(() => {
delete window['gtag'];
delete window['dataLayer'];
});
it('wrapOrCreateGtag creates new gtag function if needed', () => {
expect(window['gtag']).to.not.exist;
wrapOrCreateGtag({}, fakeDynamicConfigPromises, {}, 'dataLayer', 'gtag');
expect(window['gtag']).to.exist;
});
it('new window.gtag function waits for all initialization promises before sending group events', async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{},
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123',
'send_to': 'some_group'
});
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise1.resolve(fakeMeasurementId); // Resolves first initialization promise.
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise2.resolve('other-measurement-id'); // Resolves second initialization promise.
await Promise.all([initPromise1, initPromise2]); // Wait for resolution of Promise.all()
await promiseAllSettled(fakeDynamicConfigPromises);
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
});
it(
'new window.gtag function waits for all initialization promises before sending ' +
'event with at least one unknown send_to ID',
async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{ [fakeMeasurementId]: fakeAppId },
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123',
'send_to': [fakeMeasurementId, 'some_group']
});
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise1.resolve(); // Resolves first initialization promise.
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise2.resolve(); // Resolves second initialization promise.
await Promise.all([initPromise1, initPromise2]); // Wait for resolution of Promise.all()
await promiseAllSettled(fakeDynamicConfigPromises);
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
}
);
it(
'new window.gtag function waits for all initialization promises before sending ' +
'events with no send_to field',
async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{ [fakeMeasurementId]: fakeAppId },
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123'
});
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise1.resolve(); // Resolves first initialization promise.
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise2.resolve(); // Resolves second initialization promise.
await Promise.all([initPromise1, initPromise2]); // Wait for resolution of Promise.all()
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
}
);
it(
'new window.gtag function only waits for firebase initialization promise ' +
'before sending event only targeted to Firebase instance GA ID',
async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{ [fakeMeasurementId]: fakeAppId },
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123',
'send_to': fakeMeasurementId
});
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise1.resolve(); // Resolves first initialization promise.
await promiseAllSettled(fakeDynamicConfigPromises);
await Promise.all([initPromise1]); // Wait for resolution of Promise.all()
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
}
);
it('new window.gtag function does not wait before sending events if there are no pending initialization promises', async () => {
wrapOrCreateGtag({}, fakeDynamicConfigPromises, {}, 'dataLayer', 'gtag');
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123'
});
await Promise.all([]); // Promise.all() always runs before event call, even if empty.
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
});
it('new window.gtag function does not wait when sending "set" calls', async () => {
wrapOrCreateGtag(
{ [fakeAppId]: Promise.resolve(fakeMeasurementId) },
fakeDynamicConfigPromises,
{},
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.SET, { 'language': 'en' });
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
});
it('new window.gtag function waits for initialization promise when sending "config" calls', async () => {
const initPromise1 = new Deferred<string>();
wrapOrCreateGtag(
{ [fakeAppId]: initPromise1.promise },
fakeDynamicConfigPromises,
{},
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.CONFIG, fakeMeasurementId, {
'language': 'en'
});
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
initPromise1.resolve(fakeMeasurementId);
await promiseAllSettled(fakeDynamicConfigPromises); // Resolves dynamic config fetches.
expect((window['dataLayer'] as DataLayer).length).to.equal(0);
await Promise.all([initPromise1]); // Wait for resolution of Promise.all()
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
});
it('new window.gtag function does not wait when sending "config" calls if there are no pending initialization promises', async () => {
wrapOrCreateGtag({}, fakeDynamicConfigPromises, {}, 'dataLayer', 'gtag');
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.CONFIG, fakeMeasurementId, {
'transaction_id': 'abcd123'
});
await promiseAllSettled(fakeDynamicConfigPromises);
await Promise.resolve(); // Config call is always chained onto initialization promise list, even if empty.
expect((window['dataLayer'] as DataLayer).length).to.equal(1);
});
});
describe('wrapOrCreateGtag() when user has previously inserted gtag script tag on this page', () => {
const existingGtagStub: SinonStub = stub();
beforeEach(() => {
window['gtag'] = existingGtagStub;
});
afterEach(() => {
existingGtagStub.reset();
});
it('new window.gtag function waits for all initialization promises before sending group events', async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{ [fakeMeasurementId]: fakeAppId },
'dataLayer',
'gtag'
);
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123',
'send_to': 'some_group'
});
expect(existingGtagStub).to.not.be.called;
initPromise1.resolve(); // Resolves first initialization promise.
expect(existingGtagStub).to.not.be.called;
initPromise2.resolve(); // Resolves second initialization promise.
await promiseAllSettled(fakeDynamicConfigPromises); // Resolves dynamic config fetches.
expect(existingGtagStub).to.not.be.called;
await Promise.all([initPromise1, initPromise2]); // Wait for resolution of Promise.all()
expect(existingGtagStub).to.be.calledWith(GtagCommand.EVENT, 'purchase', {
'send_to': 'some_group',
'transaction_id': 'abcd123'
});
});
it(
'new window.gtag function waits for all initialization promises before sending ' +
'event with at least one unknown send_to ID',
async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{ [fakeMeasurementId]: fakeAppId },
'dataLayer',
'gtag'
);
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123',
'send_to': [fakeMeasurementId, 'some_group']
});
expect(existingGtagStub).to.not.be.called;
initPromise1.resolve(); // Resolves first initialization promise.
expect(existingGtagStub).to.not.be.called;
initPromise2.resolve(); // Resolves second initialization promise.
await promiseAllSettled(fakeDynamicConfigPromises); // Resolves dynamic config fetches.
expect(existingGtagStub).to.not.be.called;
await Promise.all([initPromise1, initPromise2]); // Wait for resolution of Promise.all()
expect(existingGtagStub).to.be.calledWith(
GtagCommand.EVENT,
'purchase',
{
'send_to': [fakeMeasurementId, 'some_group'],
'transaction_id': 'abcd123'
}
);
}
);
it(
'new window.gtag function waits for all initialization promises before sending ' +
'events with no send_to field',
async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{ [fakeMeasurementId]: fakeAppId },
'dataLayer',
'gtag'
);
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123'
});
expect(existingGtagStub).to.not.be.called;
initPromise1.resolve(); // Resolves first initialization promise.
expect(existingGtagStub).to.not.be.called;
initPromise2.resolve(); // Resolves second initialization promise.
await Promise.all([initPromise1, initPromise2]); // Wait for resolution of Promise.all()
expect(existingGtagStub).to.be.calledWith(
GtagCommand.EVENT,
'purchase',
{ 'transaction_id': 'abcd123' }
);
}
);
it(
'new window.gtag function only waits for firebase initialization promise ' +
'before sending event only targeted to Firebase instance GA ID',
async () => {
const initPromise1 = new Deferred<string>();
const initPromise2 = new Deferred<string>();
wrapOrCreateGtag(
{
[fakeAppId]: initPromise1.promise,
otherId: initPromise2.promise
},
fakeDynamicConfigPromises,
{ [fakeMeasurementId]: fakeAppId },
'dataLayer',
'gtag'
);
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd123',
'send_to': fakeMeasurementId
});
expect(existingGtagStub).to.not.be.called;
initPromise1.resolve(); // Resolves first initialization promise.
await promiseAllSettled(fakeDynamicConfigPromises); // Resolves dynamic config fetches.
expect(existingGtagStub).to.not.be.called;
await Promise.all([initPromise1]); // Wait for resolution of Promise.all()
expect(existingGtagStub).to.be.calledWith(
GtagCommand.EVENT,
'purchase',
{ 'send_to': fakeMeasurementId, 'transaction_id': 'abcd123' }
);
}
);
it('wrapped window.gtag function does not wait if there are no pending initialization promises', async () => {
wrapOrCreateGtag({}, fakeDynamicConfigPromises, {}, 'dataLayer', 'gtag');
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd321'
});
await Promise.all([]); // Promise.all() always runs before event call, even if empty.
expect(existingGtagStub).to.be.calledWith(GtagCommand.EVENT, 'purchase', {
'transaction_id': 'abcd321'
});
});
it('wrapped window.gtag function does not wait when sending "set" calls', async () => {
wrapOrCreateGtag(
{ [fakeAppId]: Promise.resolve(fakeMeasurementId) },
fakeDynamicConfigPromises,
{},
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.SET, { 'language': 'en' });
expect(existingGtagStub).to.be.calledWith(GtagCommand.SET, {
'language': 'en'
});
});
it('new window.gtag function waits for initialization promise when sending "config" calls', async () => {
const initPromise1 = new Deferred<string>();
wrapOrCreateGtag(
{ [fakeAppId]: initPromise1.promise },
fakeDynamicConfigPromises,
{},
'dataLayer',
'gtag'
);
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.CONFIG, fakeMeasurementId, {
'language': 'en'
});
expect(existingGtagStub).to.not.be.called;
initPromise1.resolve(fakeMeasurementId);
await promiseAllSettled(fakeDynamicConfigPromises); // Resolves dynamic config fetches.
expect(existingGtagStub).to.not.be.called;
await Promise.all([initPromise1]); // Wait for resolution of Promise.all()
expect(existingGtagStub).to.be.calledWith(
GtagCommand.CONFIG,
fakeMeasurementId,
{
'language': 'en'
}
);
});
it('new window.gtag function does not wait when sending "config" calls if there are no pending initialization promises', async () => {
wrapOrCreateGtag({}, fakeDynamicConfigPromises, {}, 'dataLayer', 'gtag');
window['dataLayer'] = [];
(window['gtag'] as Gtag)(GtagCommand.CONFIG, fakeMeasurementId, {
'transaction_id': 'abcd123'
});
await promiseAllSettled(fakeDynamicConfigPromises); // Resolves dynamic config fetches.
expect(existingGtagStub).to.not.be.called;
await Promise.resolve(); // Config call is always chained onto initialization promise list, even if empty.
expect(existingGtagStub).to.be.calledWith(
GtagCommand.CONFIG,
fakeMeasurementId,
{
'transaction_id': 'abcd123'
}
);
});
});
}); | the_stack |
import { ContactDetails, ContactGroup } from '@reach4help/model/lib/markers';
import {
isMarkerType,
isService,
MARKER_TYPE_STRINGS,
MarkerType,
Service,
SERVICE_STRINGS,
} from '@reach4help/model/lib/markers/type';
import firebase from 'firebase/app';
import cloneDeep from 'lodash/cloneDeep';
import merge from 'lodash/merge';
import React from 'react';
import {
MdAdd,
MdChevronLeft,
MdChevronRight,
MdDelete,
MdExplore,
MdRefresh,
} from 'react-icons/md';
import Search from 'src/components/search';
import { Location, MarkerInfo, submitInformation } from 'src/data/firebase';
import { format, Language, t } from 'src/i18n';
import { AddInfoStep, Page } from 'src/state';
import { isDefined, RecursivePartial } from 'src/util';
import { trackEvent } from 'src/util/tracking';
import styled, { LARGE_DEVICES, Z_INDICES } from '../styling';
import {
button,
buttonPrimary,
iconButton,
iconButtonSmall,
} from '../styling/mixins';
import { AppContext } from './context';
import { haversineDistance } from './map-utils/google-maps';
enum FORM_INPUT_NAMES {
type = 'type',
services = 'services',
name = 'name',
description = 'description',
locationName = 'locationName',
}
interface Validation {
errors: ((lang: Language) => string | JSX.Element[])[];
invalidInputs: (FORM_INPUT_NAMES | string)[];
}
interface MarkerInputInfo {
circle: google.maps.Circle;
radiusInfoWindow: google.maps.InfoWindow;
updateRadiusFromCircle: () => void;
}
interface Props {
className?: string;
lang: Language;
map: google.maps.Map | null;
addInfoStep: AddInfoStep;
setPage: (page: Page) => void;
setAddInfoMapClickedListener: (
listener: ((evt: google.maps.MouseEvent) => void) | null,
) => void;
}
interface State {
info: RecursivePartial<MarkerInfo>;
/**
* Store URLs in state separately as it's easier to manipulate as an array
*/
urls: {
[key in ContactType]: Array<{
label: string;
url: string;
}>;
};
validation?: Validation;
submissionResult?:
| { state: 'success' }
| { state: 'error'; error: (lang: Language) => string | JSX.Element[] };
}
const INITIAL_STATE: State = {
info: {},
urls: {
general: [],
getHelp: [],
volunteers: [],
},
submissionResult: undefined,
validation: undefined,
};
const isCompleteMarkerType = (
type: RecursivePartial<MarkerType> | undefined,
): type is MarkerType => {
if (!type) {
return false;
}
if (type.type === 'org') {
return !!type.services;
}
return !!type.type;
};
const isCompleteMarkerLocation = (
loc: RecursivePartial<Location> | undefined,
): loc is Location =>
!!loc &&
loc.description !== undefined &&
loc.latlng?.latitude !== undefined &&
loc.latlng.longitude !== undefined &&
loc.serviceRadius !== undefined;
const displayKm = (lang: Language, meters: number): string =>
format(lang, s => s.addInformation.screen.placeMarker.distance, {
kilometers: (meters / 1000).toFixed(2),
miles: ((meters / 1000) * 0.621371).toFixed(2),
});
type ContactType = keyof MarkerInfo['contact'];
const CONTACT_TYPES: ContactType[] = ['general', 'getHelp', 'volunteers'];
type ContactMethod = keyof (MarkerInfo['contact'][ContactType] & {});
const CONTACT_METHODS: ContactMethod[] = [
'email',
'facebookGroup',
'phone',
'web',
];
const isContactType = (type: string | undefined): type is ContactType =>
(type && CONTACT_TYPES.includes(type as ContactType)) || false;
const isContactMethod = (type: string | undefined): type is ContactMethod =>
(type && CONTACT_METHODS.includes(type as ContactMethod)) || false;
const contactInputId = (
type: ContactType,
method: ContactMethod,
index: number,
) => `${type}-${method}-${index}`;
const contactWebInputId = (
type: ContactType,
index: number,
part: 'url' | 'label',
) => `${contactInputId(type, 'web', index)}-${part}`;
const contactInputIdData = (
type: ContactType,
method: ContactMethod,
index: number,
) => ({
'data-type': type,
'data-method': method,
'data-index': index,
});
const extractContactInputIdData = (target: HTMLElement) => {
const { type, method, index } = target.dataset;
const i = parseInt(index || '', 10);
if (!isContactType(type) || !isContactMethod(method) || Number.isNaN(i)) {
return;
}
return { type, method, i };
};
type ContactInputIdData = ReturnType<typeof extractContactInputIdData>;
class AddInstructions extends React.Component<Props, State> {
private markerInfo: MarkerInputInfo | null = null;
private readonly mapsListeners = new Set<google.maps.MapsEventListener>();
constructor(props: Props) {
super(props);
this.state = INITIAL_STATE;
}
public componentDidMount() {
const { map, setAddInfoMapClickedListener } = this.props;
if (map) {
this.initializeMap(map);
}
setAddInfoMapClickedListener(this.mapClicked);
}
public componentDidUpdate(prevProps: Props) {
const { map, lang } = this.props;
// If the map updated, add required listeners
if (prevProps.map !== map) {
this.markerInfo = null;
if (prevProps.map) {
this.uninitializeMap(prevProps.map);
}
if (map) {
this.initializeMap(map);
}
}
// If the language has updated, change the radius info window (if applicaable)
if (prevProps.lang !== lang && this.markerInfo) {
this.markerInfo.updateRadiusFromCircle();
}
}
public componentWillUnmount() {
const { map, setAddInfoMapClickedListener } = this.props;
if (map) {
this.removeMarkers();
this.uninitializeMap(map);
}
setAddInfoMapClickedListener(null);
}
private setAddInfoStep = (step: AddInfoStep) => {
const { setPage } = this.props;
setPage({ page: 'add-information', step });
};
private removeMarkers = () => {
if (this.markerInfo) {
this.markerInfo.circle.setMap(null);
this.markerInfo.radiusInfoWindow.close();
this.markerInfo = null;
}
};
private initializeMap = (map: google.maps.Map) => {
this.mapsListeners.add(map.addListener('click', this.mapClicked));
map.setOptions({
draggableCursor: 'pointer',
});
};
private uninitializeMap = (map: google.maps.Map) => {
this.markerInfo = null;
this.mapsListeners.forEach(l => l.remove());
this.mapsListeners.clear();
map.setOptions({
draggableCursor: undefined,
});
};
private mapClicked = (evt: google.maps.MouseEvent) => {
const { map, addInfoStep } = this.props;
if (!map) {
return;
}
const updateLoc = (loc: google.maps.LatLng) =>
this.setInfoValues({
loc: { latlng: new firebase.firestore.GeoPoint(loc.lat(), loc.lng()) },
});
if (addInfoStep === 'place-marker') {
if (!this.markerInfo) {
const bounds = map.getBounds();
const radius = bounds
? haversineDistance(bounds.getNorthEast(), bounds.getCenter()) / 2
: 3000;
const circle = new google.maps.Circle({
map,
center: evt.latLng,
editable: true,
radius,
});
const { lang } = this.props;
const radiusInfoWindow = new google.maps.InfoWindow({
content: displayKm(lang, radius),
position: circle.getCenter(),
});
const updateRadiusFromCircle = () => {
const { lang: updatedLang } = this.props;
const serviceRadius = circle.getRadius();
this.setInfoValues({ loc: { serviceRadius } });
radiusInfoWindow.setContent(displayKm(updatedLang, serviceRadius));
radiusInfoWindow.open(map);
};
updateRadiusFromCircle();
circle.addListener('center_changed', () => {
updateLoc(circle.getCenter());
radiusInfoWindow.setPosition(circle.getCenter());
});
circle.addListener('radius_changed', updateRadiusFromCircle);
circle.addListener('click', this.mapClicked);
this.markerInfo = { circle, radiusInfoWindow, updateRadiusFromCircle };
} else {
this.markerInfo.circle.setCenter(evt.latLng);
}
updateLoc(evt.latLng);
}
};
private setInfoValues = (newInfo: RecursivePartial<MarkerInfo>) => {
this.setState(({ info }) => ({ info: merge({}, info, newInfo) }));
};
private setInfo = (mutate: (info: RecursivePartial<MarkerInfo>) => void) => {
this.setState(({ info }) => {
// eslint-disable-next-line no-param-reassign
info = cloneDeep(info);
mutate(info);
return { info };
});
};
private handleInputChange = (
event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => {
const { target } = event;
switch (target.name) {
case FORM_INPUT_NAMES.type:
if (isMarkerType(target.value)) {
this.setInfoValues({ type: { type: target.value } });
} else {
this.setInfo(info => {
// eslint-disable-next-line no-param-reassign
info.type = undefined;
});
}
break;
case FORM_INPUT_NAMES.name:
this.setInfoValues({ contentTitle: target.value });
break;
case FORM_INPUT_NAMES.locationName:
this.setInfoValues({ loc: { description: target.value } });
break;
case FORM_INPUT_NAMES.description:
this.setInfoValues({ contentBody: target.value });
break;
default:
throw new Error('Unexpected input element');
}
};
private handleCheckboxChange = (
event: React.ChangeEvent<HTMLInputElement>,
) => {
const { target } = event;
const { service } = target.dataset;
const { checked } = target;
if (isService(service)) {
this.setInfo(info => {
if (info.type?.type === 'org') {
if (!info.type.services) {
// eslint-disable-next-line no-param-reassign
info.type.services = [];
}
if (checked && !info.type.services.includes(service)) {
info.type.services.push(service);
} else if (!checked) {
// eslint-disable-next-line no-param-reassign
info.type.services = info.type.services.filter(s => s !== service);
}
}
});
}
};
private completeInformation = (event: React.FormEvent<unknown>) => {
event.preventDefault();
const { info } = this.state;
const validation: Validation = {
errors: [],
invalidInputs: [],
};
if (!info.type) {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.missingType),
);
validation.invalidInputs.push(FORM_INPUT_NAMES.type);
} else if (info.type.type === 'mutual-aid-group') {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.mutualAidGroupsNotAccepted, {
link: key => (
<a
key={key}
href="https://mutualaid.wiki/"
target="_blank"
rel="noopener noreferrer"
>
Mutual Aid Wiki
</a>
),
}),
);
} else {
if (info.type.type && (info.type.services || []).length === 0) {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.missingServices),
);
validation.invalidInputs.push(FORM_INPUT_NAMES.services);
}
if (!info.contentTitle) {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.missingTitle),
);
validation.invalidInputs.push(FORM_INPUT_NAMES.name);
}
if (!info.loc?.description) {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.missingLocationName),
);
validation.invalidInputs.push(FORM_INPUT_NAMES.locationName);
}
}
if (validation.errors.length > 0) {
this.setState({ validation });
trackEvent('data-entry', 'complete-info-error');
} else {
this.setAddInfoStep('place-marker');
this.setState({ validation: undefined });
trackEvent('data-entry', 'complete-info');
}
};
private completeMarkerPlacement = () => {
const { info } = this.state;
const validation: Validation = {
errors: [],
invalidInputs: [],
};
if (
!info.loc?.latlng?.latitude ||
!info.loc.latlng.longitude ||
!info.loc.serviceRadius
) {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.markerRequired),
);
}
if (validation.errors.length > 0) {
this.setState({ validation });
trackEvent('data-entry', 'complete-placement-error');
} else {
this.setAddInfoStep('contact-details');
this.setState({ validation: undefined });
trackEvent('data-entry', 'complete-placement');
}
};
private getCompleteInformation = (): MarkerInfo | null => {
const { info, urls } = this.state;
if (
!info.contentTitle ||
!isCompleteMarkerType(info.type) ||
!isCompleteMarkerLocation(info.loc) ||
!info.contact
) {
return null;
}
const contact: ContactGroup = {};
for (const type of CONTACT_TYPES) {
const completeTypeInfo: ContactDetails = {};
const typeInfo = info.contact[type];
if (typeInfo) {
if (typeInfo.email) {
completeTypeInfo.email = typeInfo.email.filter(isDefined);
}
if (typeInfo.phone) {
completeTypeInfo.phone = typeInfo.phone.filter(isDefined);
}
}
const typeUrls = urls[type];
if (typeUrls.length > 0) {
completeTypeInfo.web = {};
for (const { label, url } of typeUrls) {
completeTypeInfo.web[label] = url;
}
}
if (Object.keys(completeTypeInfo).length > 0) {
contact[type] = completeTypeInfo;
}
}
const completeInfo: MarkerInfo = {
contentTitle: info.contentTitle,
type: info.type,
loc: info.loc,
contact,
visible: false,
};
if (info.contentBody) {
completeInfo.contentBody = info.contentBody;
}
return completeInfo;
};
private completeContactInformation = (event: React.FormEvent<unknown>) => {
event.preventDefault();
// If we are currently focussed on an input, finalize it (in case it is empty)
if (document.activeElement instanceof HTMLInputElement) {
const inputId = extractContactInputIdData(document.activeElement);
if (inputId) {
this.finalizeContactInput(inputId, document.activeElement);
}
}
// Give time for state changes to apply after input blur
this.setState({}, () => {
const { info, urls } = this.state;
const validation: Validation = {
errors: [],
invalidInputs: [],
};
if (Object.keys(info.contact || {}).length === 0) {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.noContactDetails),
);
} else {
for (const type of CONTACT_TYPES) {
const typeInfo = info.contact?.[type];
const typeUrls = urls[type] || [];
const sectionLabel = (key: number, lang: Language) => (
<strong key={key}>
{t(lang, s => s.addInformation.screen.contactInfo.sections[type])}
</strong>
);
if (typeInfo) {
if (Object.keys(typeInfo).length === 0 && typeUrls.length === 0) {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.emptyContactSection, {
section: key => sectionLabel(key, lang),
}),
);
validation.invalidInputs.push(type);
} else {
// Check URLs:
typeUrls.forEach(({ label, url }, index) => {
if (label === '') {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.urlMissingLabel, {
section: key => sectionLabel(key, lang),
}),
);
validation.invalidInputs.push(
contactWebInputId(type, index, 'label'),
);
} else if (url === '') {
validation.errors.push(lang =>
t(lang, s => s.addInformation.errors.urlMissingURL, {
section: key => sectionLabel(key, lang),
}),
);
validation.invalidInputs.push(
contactWebInputId(type, index, 'url'),
);
}
});
}
}
}
}
if (validation.errors.length > 0) {
this.setState({ validation });
trackEvent('data-entry', 'complete-contact-info-error');
} else {
this.setAddInfoStep('submitted');
this.setState({ validation: undefined, submissionResult: undefined });
const completeInfo = this.getCompleteInformation();
if (!completeInfo) {
this.setState({
submissionResult: {
state: 'error',
error: lang => t(lang, s => s.addInformation.errors.dataError),
},
});
} else {
submitInformation(completeInfo).then(
() => this.setState({ submissionResult: { state: 'success' } }),
error =>
this.setState({
submissionResult: {
state: 'error',
error: lang =>
t(lang, s => s.addInformation.errors.submitError, {
error: key => <span key={key}>{String(error)}</span>,
}),
},
}),
);
}
trackEvent('data-entry', 'complete-contact-info');
}
});
};
private addMore = () => {
this.setState(INITIAL_STATE);
this.setAddInfoStep('information');
this.removeMarkers();
trackEvent('data-entry', 'add-more');
};
private validatedInput = (
input: FORM_INPUT_NAMES,
element: (valid: boolean) => JSX.Element | undefined,
) => {
const { validation } = this.state;
const valid = !(validation?.invalidInputs || []).includes(input);
return element(valid);
};
private formTextInput = (
input: FORM_INPUT_NAMES,
label: string,
value: string,
placeholder?: string,
) =>
this.validatedInput(input, valid => (
<>
<label className={valid ? '' : 'error'} htmlFor={input}>
{label}
</label>
<input
className={valid ? '' : 'error'}
type="text"
id={input}
name={input}
placeholder={placeholder}
onChange={this.handleInputChange}
value={value}
/>
</>
));
private actionButtons = (opts: {
previousScreen?: AddInfoStep;
nextScreen?: () => void;
nextLabel?: 'continue' | 'submit' | 'addMore';
}) => {
const { lang } = this.props;
const { previousScreen, nextScreen, nextLabel = 'continue' } = opts;
return (
<div className="actions">
{previousScreen && (
<>
<button
type="button"
className="prev-button"
onClick={() => this.setAddInfoStep(previousScreen)}
>
<MdChevronLeft className="icon icon-start" />
{t(lang, s => s.addInformation.prev)}
</button>
<div className="grow" />
</>
)}
<button type="submit" className="next-button" onClick={nextScreen}>
{t(lang, s => s.addInformation[nextLabel])}
<MdChevronRight className="icon icon-end" />
</button>
</div>
);
};
private contactInputChanged = (
event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => {
const { target } = event;
const idData = extractContactInputIdData(target);
if (!idData) {
return;
}
const { type, method, i } = idData;
if (method === 'phone' || method === 'email') {
this.setInfo(info => {
const arr = info.contact?.[type]?.[method] || [];
arr[i] = target.value;
const newInfo: RecursivePartial<MarkerInfo> = {
contact: { [type]: { [method]: arr } },
};
merge(info, newInfo);
});
} else if (method === 'web') {
const { part } = target.dataset;
if (part === 'url' || part === 'label') {
this.setState(state => {
const urls = cloneDeep(state.urls);
let entry = urls[type][i];
if (!entry) {
urls[type][i] = entry = { label: '', url: '' };
}
entry[part] = target.value;
return { urls };
});
}
}
};
private contactInputBlurred = (event: React.FocusEvent<HTMLInputElement>) => {
const { target } = event;
const idData = extractContactInputIdData(target);
this.finalizeContactInput(idData, target);
};
private finalizeContactInput = (
idData: ContactInputIdData,
target: HTMLInputElement,
) => {
if (idData && target.value === '') {
const { type, method, i } = idData;
if (method === 'phone' || method === 'email') {
this.setInfo(info => {
if (info.contact?.[type]) {
const arr: string[] | undefined = (
info.contact?.[type]?.[method] || []
).filter(isDefined);
arr.splice(i, 1);
// Remove array completely if empty
if (arr.length === 0) {
// eslint-disable-next-line no-param-reassign
delete info.contact[type][method];
} else {
// eslint-disable-next-line no-param-reassign
info.contact[type][method] = arr;
}
}
});
} else if (method === 'web') {
const { part } = target.dataset;
if (part === 'url' || part === 'label') {
this.setState(state => {
const urls = cloneDeep(state.urls);
const entry = urls[type][i];
if (entry && entry.label === '' && entry.url === '') {
urls[type].splice(i, 1);
}
return { urls };
});
}
}
}
};
private contactMethodGroup = (
type: ContactType,
method: 'phone' | 'email',
) => {
const { lang } = this.props;
const { info } = this.state;
const methodInfo = info.contact?.[type]?.[method]?.filter(isDefined) || [];
const fields = [...methodInfo, ''];
const lastId = contactInputId(type, method, fields.length - 1);
return (
<div className="contact-method-group">
<label htmlFor={lastId}>
{t(lang, s => s.addInformation.screen.contactInfo.method[method])}
</label>
<div className="inputs">
{fields.map((value, i) => (
<input
key={i}
type={method === 'phone' ? 'tel' : 'email'}
id={contactInputId(type, method, i)}
value={value}
placeholder={t(
lang,
s => s.addInformation.screen.contactInfo.placeholder[method],
)}
onChange={this.contactInputChanged}
onBlur={this.contactInputBlurred}
{...contactInputIdData(type, method, i)}
/>
))}
</div>
</div>
);
};
private contactUrlGroup = (type: ContactType) => {
const { lang } = this.props;
const { urls, validation } = this.state;
const fields = [...urls[type], { label: '', url: '' }];
const lastId = `${contactWebInputId(type, fields.length - 1, 'url')}`;
const errors = validation?.invalidInputs || [];
return (
<div className="contact-method-group">
<label htmlFor={lastId}>
{t(lang, s => s.addInformation.screen.contactInfo.method.web)}
</label>
<div className="inputs">
{fields.map(({ label, url }, i) => (
<div key={i} className="url">
<input
type="text"
id={`${contactWebInputId(type, i, 'label')}`}
className={
errors.includes(contactWebInputId(type, i, 'label'))
? 'error'
: ''
}
value={label}
placeholder={t(
lang,
s => s.addInformation.screen.contactInfo.placeholder.webLabel,
)}
onChange={this.contactInputChanged}
onBlur={this.contactInputBlurred}
{...contactInputIdData(type, 'web', i)}
data-part="label"
/>
<input
type="text"
id={contactWebInputId(type, i, 'url')}
className={
errors.includes(contactWebInputId(type, i, 'url'))
? 'error'
: ''
}
value={url}
placeholder={t(
lang,
s => s.addInformation.screen.contactInfo.placeholder.webURL,
)}
onChange={this.contactInputChanged}
onBlur={this.contactInputBlurred}
{...contactInputIdData(type, 'web', i)}
data-part="url"
/>
</div>
))}
</div>
</div>
);
};
private contactTypeGroup = (type: ContactType) => {
const { lang } = this.props;
const { info, validation } = this.state;
const error = (validation?.invalidInputs || []).includes(type);
return (
<div key={type} className="contact-type-group">
{info.contact?.[type] ? (
<div>
<div
className={`contact-type-group-header ${error ? 'error' : ''}`}
>
<strong>
{t(
lang,
s => s.addInformation.screen.contactInfo.sections[type],
)}
</strong>
<button
type="button"
onClick={() =>
this.setInfo(i => {
if (i.contact) {
// eslint-disable-next-line no-param-reassign
i.contact[type] = undefined;
}
})
}
>
<MdDelete className="icon icon-start" />
{t(lang, s => s.addInformation.screen.contactInfo.deleteInfo)}
</button>
</div>
{this.contactMethodGroup(type, 'phone')}
{this.contactMethodGroup(type, 'email')}
{this.contactUrlGroup(type)}
</div>
) : (
<button
type="button"
className="contact-button"
onClick={() => this.setInfoValues({ contact: { [type]: {} } })}
>
<MdAdd className="icon icon-start" />
{t(lang, s => s.addInformation.screen.contactInfo.addInfo[type])}
</button>
)}
</div>
);
};
public render = () => {
const { className, addInfoStep, setPage } = this.props;
const { info, validation, submissionResult } = this.state;
return (
<AppContext.Consumer>
{({ lang }) => (
<div className={className}>
{addInfoStep === 'information' && (
<div className="screen">
<h2>{t(lang, s => s.addInformation.screen.title)}</h2>
<p className="muted">
{t(
lang,
s =>
s.addInformation.screen.information.acceptedInformation,
)}
</p>
<p className="muted">
{t(
lang,
s => s.addInformation.screen.information.moreInformation,
{
contactEmail: key => (
<a key={key} href="mailto:support@reach4help.org">
support@reach4help.org
</a>
),
},
)}
</p>
<p>{t(lang, s => s.addInformation.screen.information.intro)}</p>
<form onSubmit={this.completeInformation}>
{this.validatedInput(FORM_INPUT_NAMES.type, valid => (
<>
<label
className={valid ? '' : 'error'}
htmlFor={FORM_INPUT_NAMES.type}
>
{t(
lang,
s => s.addInformation.screen.information.form.type,
)}
</label>
<select
className={valid ? '' : 'error'}
id={FORM_INPUT_NAMES.type}
name={FORM_INPUT_NAMES.type}
value={info?.type?.type || ''}
onChange={this.handleInputChange}
>
<option value="">
{t(
lang,
s =>
s.addInformation.screen.information.form
.typePleaseSelect,
)}
</option>
{MARKER_TYPE_STRINGS.map(type =>
// TEMP "FIX": https://github.com/reach4help/reach4help/issues/1290
type !== 'mutual-aid-group' &&
type !== 'individual' ? (
<option key={type} value={type}>
{t(lang, s => s.markerTypes[type])}
</option>
) : null,
)}
</select>
</>
))}
{this.validatedInput(FORM_INPUT_NAMES.services, valid => {
if (info.type?.type !== 'org') {
return;
}
const services: (Service | undefined)[] =
info.type.services || [];
return (
<>
<span className={`label ${valid ? '' : 'error'}`}>
{t(
lang,
s =>
s.addInformation.screen.information.form.services,
)}
</span>
<div className="checkbox-group">
{SERVICE_STRINGS.map(service => {
const description = t(
lang,
s => s.serviceDescriptions[service],
);
return (
<div key={service} className="option">
<input
type="checkbox"
name={`service-${service}`}
id={`service-${service}`}
checked={services.includes(service)}
onChange={this.handleCheckboxChange}
data-service={service}
/>
<label htmlFor={`service-${service}`}>
{t(lang, s => s.services[service])}
{description && (
<span>
-
{description}
</span>
)}
</label>
</div>
);
})}
</div>
</>
);
})}
{info.type?.type === 'mutual-aid-group' && (
<p className="info-box">
{t(
lang,
s =>
s.addInformation.screen.information.mutualAidInstead,
{
link: key => (
<a
key={key}
href="https://mutualaid.wiki/"
target="_blank"
rel="noopener noreferrer"
>
Mutual Aid Wiki
</a>
),
},
)}
</p>
)}
{info.type &&
info.type.type !== 'mutual-aid-group' &&
this.formTextInput(
FORM_INPUT_NAMES.name,
t(
lang,
s => s.addInformation.screen.information.form.name,
),
info.contentTitle || '',
t(
lang,
s =>
s.addInformation.screen.information.form
.namePlaceholder,
),
)}
{info.type &&
info.type.type !== 'mutual-aid-group' &&
this.formTextInput(
FORM_INPUT_NAMES.description,
t(
lang,
s =>
s.addInformation.screen.information.form.description,
),
info.contentBody || '',
t(
lang,
s =>
s.addInformation.screen.information.form
.namePlaceholder,
),
)}
{info.type &&
info.type.type !== 'mutual-aid-group' &&
this.formTextInput(
FORM_INPUT_NAMES.locationName,
t(
lang,
s =>
s.addInformation.screen.information.form.locationName,
),
info.loc?.description || '',
t(
lang,
s =>
s.addInformation.screen.information.form
.locationNamePlaceholder,
),
)}
{info.type && info.type.type !== 'mutual-aid-group' && (
<p>
{t(
lang,
s => s.addInformation.screen.information.form.continue,
)}
</p>
)}
{validation && (
<ul className="errors">
{validation.errors.map((error, i) => (
<li key={i}>{error(lang)}</li>
))}
</ul>
)}
{this.actionButtons({})}
</form>
</div>
)}
{addInfoStep === 'place-marker' && (
<div className="place-marker">
<div className="box">
<p>
{t(
lang,
s => s.addInformation.screen.placeMarker.instructions,
)}
</p>
<p>
{t(lang, s => s.addInformation.screen.placeMarker.continue)}
</p>
{validation &&
validation.errors.map((error, i) => (
<p key={i} className="error">
{error(lang)}
</p>
))}
{this.actionButtons({
previousScreen: 'information',
nextScreen: this.completeMarkerPlacement,
})}
</div>
<div className="search-wrapper">
<Search className="search" searchInputId="add-information" />
</div>
</div>
)}
{addInfoStep === 'contact-details' && (
<div className="screen">
<h2>
{t(lang, s => s.addInformation.screen.contactInfo.header, {
name: key => <span key={key}>{info.contentTitle}</span>,
})}
</h2>
<p>
{t(lang, s => s.addInformation.screen.contactInfo.info, {
name: key => <strong key={key}>{info.contentTitle}</strong>,
})}
</p>
<form onSubmit={this.completeContactInformation}>
{CONTACT_TYPES.map(type => this.contactTypeGroup(type))}
{validation && (
<ul className="errors">
{validation.errors.map((error, i) => (
<li key={i}>{error(lang)}</li>
))}
</ul>
)}
{this.actionButtons({
previousScreen: 'place-marker',
nextLabel: 'submit',
})}
</form>
</div>
)}
{addInfoStep === 'submitted' && (
<div className="screen">
{submissionResult ? (
submissionResult.state === 'error' ? (
<>
<h2>
{t(lang, s => s.addInformation.screen.submitted.error)}
</h2>
<p>{submissionResult.error(lang)}</p>
<div className="actions">
<button
type="button"
className="prev-button"
onClick={() => this.setAddInfoStep('contact-details')}
>
<MdChevronLeft className="icon icon-start" />
{t(lang, s => s.addInformation.prev)}
</button>
<div className="grow" />
<button
type="button"
className="next-button"
onClick={this.completeContactInformation}
>
<MdRefresh className="icon icon-start" />
{t(lang, s => s.addInformation.tryAgain)}
</button>
</div>
</>
) : (
<>
<h2>
{t(
lang,
s => s.addInformation.screen.submitted.success,
)}
</h2>
<p>
{t(
lang,
s => s.addInformation.screen.submitted.successExtra,
)}
</p>
<div className="actions">
<button
type="button"
className="prev-button"
onClick={() => setPage({ page: 'map' })}
>
<MdExplore className="icon icon-start" />
{t(lang, s => s.addInformation.backToMap)}
</button>
<div className="grow" />
<button
type="button"
className="next-button"
onClick={this.addMore}
>
<MdAdd className="icon icon-start" />
{t(lang, s => s.addInformation.addMore)}
</button>
</div>
</>
)
) : (
<>
<h2>
{t(lang, s => s.addInformation.screen.submitted.loading)}
</h2>
</>
)}
</div>
)}
</div>
)}
</AppContext.Consumer>
);
};
}
export default styled(AddInstructions)`
z-index: ${Z_INDICES.MAP_ADD_INFORMATION};
font-size: 1rem;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
display: flex;
align-items: flex-start;
justify-content: flex-start;
pointer-events: none;
${LARGE_DEVICES} {
top: ${p => p.theme.secondaryHeaderSizePx}px;
}
> .screen {
pointer-events: initial;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: #fff;
overflow-y: auto;
padding: ${p => p.theme.spacingPx}px;
> h2 {
margin-top: 0;
}
p.info-box {
background: rgba(0, 0, 0, 0.05);
border-radius: 5px;
padding: 20px 16px;
}
label,
.label {
display: block;
margin-top: ${p => p.theme.spacingPx}px;
font-weight: bold;
&.error {
color: ${p => p.theme.colors.red};
}
}
input:not([type='checkbox']) {
display: block;
width: 600px;
max-width: 90%;
}
input:not([type='checkbox']),
select {
padding: 7px 5px;
font-size: 1rem;
margin-top: ${p => p.theme.spacingPx}px;
border: 1px solid ${p => p.theme.colors.purpleLight};
border-radius: 3px;
outline: none;
color: ${p => p.theme.textColor};
background: #fff;
&:focus {
border-color: ${p => p.theme.colors.purple};
}
&::placeholder {
color: ${p => p.theme.textColorLight};
}
&.error {
border: 2px solid ${p => p.theme.colors.red};
}
}
.checkbox-group {
margin-top: ${p => p.theme.spacingPx}px;
> .option {
margin-top: ${p => p.theme.spacingPx / 2}px;
input {
cursor: pointer;
display: inline;
}
label {
cursor: pointer;
display: inline;
margin-left: ${p => p.theme.spacingPx}px;
span {
font-weight: normal;
}
}
}
}
.contact-button {
${button}
${iconButton}
}
.contact-type-group {
margin-top: ${p => p.theme.spacingPx}px;
.contact-type-group-header {
display: flex;
align-items: center;
&.error {
color: ${p => p.theme.colors.red};
}
button {
margin: 0 ${p => p.theme.spacingPx}px;
${button}
${iconButtonSmall}
}
}
.contact-method-group {
display: flex;
> label {
line-height: 34px;
}
> .inputs {
margin-left: ${p => p.theme.spacingPx}px;
width: 10%;
flex-grow: 1;
> .url {
display: flex;
flex-wrap: wrap;
margin: ${p => p.theme.spacingPx}px -${p => p.theme.spacingPx / 2}px
0;
input {
margin: 0 ${p => p.theme.spacingPx / 2}px;
&[data-part='label'] {
width: 200px;
}
&[data-part='url'] {
width: 300px;
}
}
}
}
}
}
.errors {
color: ${p => p.theme.colors.red};
}
}
> .place-marker,
.submitted {
width: 100%;
> .box {
padding: ${p => p.theme.spacingPx}px;
background: rgba(255, 255, 255, 0.9);
border-bottom: 1px solid ${p => p.theme.colors.grayLight2};
p:first-child {
margin-top: 0;
}
pointer-events: initial;
> .error {
color: ${p => p.theme.colors.red};
}
}
> .search-wrapper {
display: flex;
margin: ${p => p.theme.overlayPaddingPx}px;
background: #fff;
box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15);
border-radius: 4px;
padding: 18px 16px;
max-width: ${p => p.theme.overlayPanelWidthPx}px;
> .search {
flex-grow: 1;
pointer-events: initial;
}
}
}
.actions {
margin-top: ${p => p.theme.spacingPx}px;
display: flex;
> .next-button {
${buttonPrimary}
${iconButton}
}
> .grow {
flex-grow: 1;
}
> .prev-button {
${button}
${iconButton}
}
[dir='rtl'] & button svg {
transform: rotate(180deg);
}
}
`; | the_stack |
import * as ts from "typescript";
import * as Lint from "tslint";
/** KEEP IN SYNC WITH README.md
## ext-variable-name
This rule provides extensive support for customizing allowable variable names
for a wide variety of variable tags. The rule is configured by setting up a
list of sub-rules that specify the tags of variables to check and the checks
to perform on the variable's name. The sub-rules are checked in order
and the first one that matches the tags of variable being checked is the
only one that is used.
An example set of sub-rules for an example coding standard is shown below.
```json
"ext-variable-name": [
true,
["class", "pascal"],
["interface", "pascal", {"regex": "^I.*$"}],
["parameter", "camel"],
["property", "static", "camel", {"regex": "^s.*$"}],
["property", "private", "camel", "allow-leading-underscore"],
["property", "protected", "camel", "allow-leading-underscore"],
["variable", "local", "snake"],
["variable", "const", "upper"],
["variable", "camel", {"regex": "^g.*$"}],
["method", "private", "camel", "allow-leading-underscore"],
["method", "protected", "camel", "allow-leading-underscore"],
["function", "camel"],
["default", "camel"]
]
```
Allowed tags for variables:
* primary (choose one):
* class, interface, parameter, property,
method, function, variable
* modifiers (choose zero or more):
* local, const, static, public, protected, private
note: If any tags is added to a sub-rule then **all** must match the variable.
Checks allowed:
* One of:
* "camel": Require variables to use camelCaseVariables
* "snake": Require variables to use snake_case_variables
* "pascal": Require variables to use PascalCaseVariables
* "upper": Require variables to use UPPER_CASE_VARIABLES
* "allow-leading-underscore": permits the variable to have a leading underscore
* "allow-trailing-underscore": permits the variable to have a trailing underscore
* "require-leading-underscore": requires the variable to have a leading underscore
* "require-trailing-underscore": requires the variable to have a trailing underscore
* "ban-keywords": bans a list of language keywords from being used
* {"regex": "^.*$"}: checks the variable name against the given regex
*/
const CLASS_TAG = "class";
const INTERFACE_TAG = "interface";
const PARAMETER_TAG = "parameter";
const PROPERTY_TAG = "property";
const METHOD_TAG = "method";
const FUNCTION_TAG = "function";
const VARIABLE_TAG = "variable";
const LOCAL_TAG = "local";
const STATIC_TAG = "static";
const CONST_TAG = "const";
const PUBLIC_TAG = "public";
const PROTECTED_TAG = "protected";
const PRIVATE_TAG = "private";
const VALID_VAR_TAGS = [CLASS_TAG, INTERFACE_TAG, PARAMETER_TAG,
PROPERTY_TAG, METHOD_TAG, FUNCTION_TAG, VARIABLE_TAG,
LOCAL_TAG, STATIC_TAG, CONST_TAG,
PUBLIC_TAG, PROTECTED_TAG, PRIVATE_TAG];
const PASCAL_OPTION = "pascal";
const CAMEL_OPTION = "camel";
const SNAKE_OPTION = "snake";
const UPPER_OPTION = "upper";
const ALLOW_LEADING_UNDERSCORE_OPTION = "allow-leading-underscore";
const ALLOW_TRAILING_UNDERSCORE_OPTION = "allow-trailing-underscore";
const REQUIRE_LEADING_UNDERSCORE_OPTION = "require-leading-underscore";
const REQUIRE_TRAILING_UNDERSCORE_OPTION = "require-trailing-underscore";
const BAN_KEYWORDS_OPTION = "ban-keywords";
const CAMEL_FAIL = "must be in camel case";
const PASCAL_FAIL = "must be in pascal case";
const SNAKE_FAIL = "must be in snake case";
const UPPER_FAIL = "must be in uppercase";
const KEYWORD_FAIL = "name clashes with keyword/type";
const LEADING_FAIL = "name must not have leading underscore";
const TRAILING_FAIL = "name must not have trailing underscore";
const NO_LEADING_FAIL = "name must have leading underscore";
const NO_TRAILING_FAIL = "name must have trailing underscore";
const REGEX_FAIL = "name did not match required regex";
const BANNED_KEYWORDS = ["any", "Number", "number", "String", "string",
"Boolean", "boolean", "Undefined", "undefined"];
/**
* Configured with details needed to check a specific variable type.
*/
class VariableChecker {
public varTags: string[];
public caseCheck: string = "";
public allowLeadingUnderscore: boolean = false;
public allowTrailingUnderscore: boolean = false;
public requireLeadingUnderscore: boolean = false;
public requireTrailingUnderscore: boolean = false;
public banKeywords: boolean = false;
public regex: RegExp | null = null;
constructor(opts: any[]) {
this.varTags = opts.filter(v => contains(VALID_VAR_TAGS, v));
if (contains(opts, PASCAL_OPTION)) {
this.caseCheck = PASCAL_OPTION;
} else if (contains(opts, CAMEL_OPTION)) {
this.caseCheck = CAMEL_OPTION;
} else if (contains(opts, SNAKE_OPTION)) {
this.caseCheck = SNAKE_OPTION;
} else if (contains(opts, UPPER_OPTION)) {
this.caseCheck = UPPER_OPTION;
}
this.allowLeadingUnderscore = contains(opts, ALLOW_LEADING_UNDERSCORE_OPTION);
this.allowTrailingUnderscore = contains(opts, ALLOW_TRAILING_UNDERSCORE_OPTION);
this.requireLeadingUnderscore = contains(opts, REQUIRE_LEADING_UNDERSCORE_OPTION);
this.requireTrailingUnderscore = contains(opts, REQUIRE_TRAILING_UNDERSCORE_OPTION);
this.banKeywords = contains(opts, BAN_KEYWORDS_OPTION);
opts.forEach((opt) => {
if (opt.regex !== undefined) {
this.regex = new RegExp(opt.regex);
}
});
}
/**
* return true if all of our tags are all in the input tags
* (ie. we match if we dont have a tag that prevents it)
*/
public requiredTagsFound(proposedTags: string[]) {
let matches = true;
this.varTags.forEach((tag) => {
if (!contains(proposedTags, tag)) {
matches = false;
}
});
return matches;
}
protected failMessage(failMessage: string, tag: string) {
return tag[0].toUpperCase() + tag.substr(1) + " " + failMessage;
}
public checkName(name: ts.Identifier, walker: Lint.RuleWalker, tag: string) {
let variableName = name.text;
const firstCharacter = variableName[0];
const lastCharacter = variableName[variableName.length - 1];
// start with regex test before we potentially strip off underscores
if ((this.regex !== null) && !variableName.match(this.regex)) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(REGEX_FAIL, tag)));
}
// check banned words before we potentially strip off underscores
if (this.banKeywords && contains(BANNED_KEYWORDS, variableName)) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(KEYWORD_FAIL, tag)));
}
// check leading and trailing underscore
if ("_" === firstCharacter) {
if (!this.allowLeadingUnderscore && !this.requireLeadingUnderscore) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(LEADING_FAIL, tag)));
}
variableName = variableName.slice(1);
} else if (this.requireLeadingUnderscore) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(NO_LEADING_FAIL, tag)));
}
if (("_" === lastCharacter) && (variableName.length > 0)) {
if (!this.allowTrailingUnderscore && !this.requireTrailingUnderscore) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(TRAILING_FAIL, tag)));
}
variableName = variableName.slice(0, -1);
} else if (this.requireTrailingUnderscore) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(NO_TRAILING_FAIL, tag)));
}
// run case checks
if ((PASCAL_OPTION === this.caseCheck) && !isPascalCased(variableName)) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(PASCAL_FAIL, tag)));
} else if ((CAMEL_OPTION === this.caseCheck) && !isCamelCase(variableName)) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(CAMEL_FAIL, tag)));
} else if ((SNAKE_OPTION === this.caseCheck) && !isSnakeCase(variableName)) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(SNAKE_FAIL, tag)));
} else if ((UPPER_OPTION === this.caseCheck) && !isUpperCase(variableName)) {
walker.addFailure(walker.createFailure(name.getStart(), name.getWidth(),
this.failMessage(UPPER_FAIL, tag)));
}
}
}
class VariableNameWalker extends Lint.RuleWalker {
public checkers: VariableChecker[] = [];
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
super(sourceFile, options);
let sub_rules = options.ruleArguments;
sub_rules.forEach((rule_opts: any[]) => {
this.checkers.push(new VariableChecker(rule_opts));
});
}
public visitClassDeclaration(node: ts.ClassDeclaration) {
// classes declared as default exports will be unnamed
this.checkName(node, CLASS_TAG);
super.visitClassDeclaration(node);
}
public visitMethodDeclaration(node: ts.MethodDeclaration) {
this.checkName(node, METHOD_TAG);
super.visitMethodDeclaration(node);
}
public visitInterfaceDeclaration(node: ts.InterfaceDeclaration) {
this.checkName(node, INTERFACE_TAG);
super.visitInterfaceDeclaration(node);
}
// what is this?
public visitBindingElement(node: ts.BindingElement) {
this.checkName(node, VARIABLE_TAG);
super.visitBindingElement(node);
}
public visitParameterDeclaration(node: ts.ParameterDeclaration) {
const parameterProperty: boolean =
Lint.hasModifier(node.modifiers, ts.SyntaxKind.PublicKeyword) ||
Lint.hasModifier(node.modifiers, ts.SyntaxKind.ProtectedKeyword) ||
Lint.hasModifier(node.modifiers, ts.SyntaxKind.PrivateKeyword);
this.checkName(node, parameterProperty ? PROPERTY_TAG : PARAMETER_TAG);
super.visitParameterDeclaration(node);
}
public visitPropertyDeclaration(node: ts.PropertyDeclaration) {
this.checkName(node, PROPERTY_TAG);
super.visitPropertyDeclaration(node);
}
public visitSetAccessor(node: ts.SetAccessorDeclaration) {
this.checkName(node, PROPERTY_TAG);
super.visitSetAccessor(node);
}
public visitGetAccessor(node: ts.GetAccessorDeclaration) {
this.checkName(node, PROPERTY_TAG);
super.visitGetAccessor(node);
}
public visitVariableDeclaration(node: ts.VariableDeclaration) {
this.checkName(node, VARIABLE_TAG);
super.visitVariableDeclaration(node);
}
public visitVariableStatement(node: ts.VariableStatement) {
// skip 'declare' keywords
if (!Lint.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) {
super.visitVariableStatement(node);
}
}
public visitFunctionDeclaration(node: ts.FunctionDeclaration) {
this.checkName(node, FUNCTION_TAG);
super.visitFunctionDeclaration(node);
}
protected checkName(node: ts.NamedDeclaration, tag: string) {
if (node.name && node.name.kind === ts.SyntaxKind.Identifier) {
const matching_checker = this.getMatchingChecker(this.getNodeTags(node, tag));
if (matching_checker !== null) {
matching_checker.checkName(<ts.Identifier> node.name, this, tag);
}
}
}
protected getMatchingChecker(varTags: string[]): VariableChecker | null {
let matching_checkers = this.checkers.filter(checker => checker.requiredTagsFound(varTags));
if (matching_checkers.length > 0) {
return matching_checkers[0];
} else {
return null;
}
}
protected getNodeTags(node: ts.Node, primaryTag: string): string[] {
let tags = [primaryTag];
if (Lint.hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword)) {
tags.push(STATIC_TAG);
}
if (Lint.hasModifier(node.modifiers, ts.SyntaxKind.ConstKeyword)) {
tags.push(CONST_TAG);
}
if (primaryTag === PROPERTY_TAG || primaryTag === METHOD_TAG) {
if (Lint.hasModifier(node.modifiers, ts.SyntaxKind.PrivateKeyword)) {
tags.push(PRIVATE_TAG);
} else if (Lint.hasModifier(node.modifiers, ts.SyntaxKind.ProtectedKeyword)) {
tags.push(PROTECTED_TAG);
} else {
// xxx: should fix so only get public when it is a property
tags.push(PUBLIC_TAG);
}
}
let nearest_body = nearestBody(node);
if (!nearest_body.isSourceFile) {
tags.push(LOCAL_TAG);
}
if (node.kind === ts.SyntaxKind.VariableDeclaration) {
if (isConstVariable(<ts.VariableDeclaration>node)) {
tags.push(CONST_TAG);
}
}
return tags;
}
}
function nearestBody(node: ts.Node): {isSourceFile: boolean, containingBody: ts.Node | undefined} {
const VALID_PARENT_TYPES = [
ts.SyntaxKind.SourceFile,
ts.SyntaxKind.FunctionDeclaration,
ts.SyntaxKind.FunctionExpression,
ts.SyntaxKind.ArrowFunction,
ts.SyntaxKind.MethodDeclaration,
ts.SyntaxKind.Constructor,
];
let ancestor = node.parent;
while (ancestor && !contains(VALID_PARENT_TYPES, ancestor.kind)) {
ancestor = ancestor.parent;
}
return {
containingBody: ancestor,
isSourceFile: (ancestor && ancestor.kind === ts.SyntaxKind.SourceFile) || !ancestor,
};
}
function isConstVariable(node: ts.VariableDeclaration | ts.VariableStatement): boolean {
const parentNode = (node.kind === ts.SyntaxKind.VariableDeclaration)
? (<ts.VariableDeclaration> node).parent
: (<ts.VariableStatement> node).declarationList;
return !parentNode || Lint.isNodeFlagSet(parentNode, ts.NodeFlags.Const);
}
function isPascalCased(name: string) {
if (name.length <= 0) {
return true;
}
const firstCharacter = name.charAt(0);
return ((firstCharacter === firstCharacter.toUpperCase()) && name.indexOf("_") === -1);
}
function isCamelCase(name: string) {
const firstCharacter = name.charAt(0);
if (name.length <= 0) {
return true;
}
if (!isLowerCase(firstCharacter)) {
return false;
}
return name.indexOf("_") === -1;
}
function isSnakeCase(name: string) {
return isLowerCase(name);
}
function isLowerCase(name: string) {
return name === name.toLowerCase();
}
function isUpperCase(name: string) {
return name === name.toUpperCase();
}
function contains(arr: any[], value: any): boolean {
return arr.indexOf(value) !== -1;
}
export class Rule extends Lint.Rules.AbstractRule {
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const variableNameWalker = new VariableNameWalker(sourceFile, this.getOptions());
return this.applyWithWalker(variableNameWalker);
}
}
/**
* Original version based upon variable-name rule:
*
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | the_stack |
import { Template } from '../Templates/Template';
import { Component } from '../Base/Component';
import { IComponentBindings } from '../Base/ComponentBindings';
import { ComponentOptions } from '../Base/ComponentOptions';
import { DefaultFoldingTemplate } from './DefaultFoldingTemplate';
import { IQueryResult } from '../../rest/QueryResult';
import { Utils } from '../../utils/Utils';
import { QueryUtils } from '../../utils/QueryUtils';
import { Initialization } from '../Base/Initialization';
import { Assert } from '../../misc/Assert';
import { $$, Win } from '../../utils/Dom';
import { l } from '../../strings/Strings';
import { each, map } from 'underscore';
import { exportGlobally } from '../../GlobalExports';
import { analyticsActionCauseList, IAnalyticsDocumentViewMeta } from '../Analytics/AnalyticsActionListMeta';
import { Logger } from '../../misc/Logger';
import 'styling/_ResultFolding';
import { SVGIcons } from '../../utils/SVGIcons';
import { SVGDom } from '../../utils/SVGDom';
import { TemplateComponentOptions } from '../Base/TemplateComponentOptions';
import { AccessibleButton } from '../../utils/AccessibleButton';
export interface IResultFoldingOptions {
resultTemplate?: Template;
normalCaption?: string;
expandedCaption?: string;
moreCaption?: string;
lessCaption?: string;
oneResultCaption?: string;
}
/**
* The `ResultFolding` component renders folded result sets. It is usable inside a result template when there is an
* active [`Folding`]{@link Folding} component in the page. This component takes care of rendering the parent result and
* its child results in a coherent manner.
*
* This component is a result template component (see [Result Templates](https://docs.coveo.com/en/413/)).
*
* See [Folding Results](https://docs.coveo.com/en/428/).
*/
export class ResultFolding extends Component {
static ID = 'ResultFolding';
static doExport = () => {
exportGlobally({
ResultFolding: ResultFolding,
DefaultFoldingTemplate: DefaultFoldingTemplate
});
};
/**
* The options for the component
* @componentOptions
*/
static options: IResultFoldingOptions = {
/**
* Specifies the template to use to render each of the child results for a top result.
*
* You can specify a previously registered template to use either by referring to its HTML `id` attribute or to a
* CSS selector (see {@link TemplateCache}).
*
* **Example:**
*
* Specifying a previously registered template by referring to its HTML `id` attribute:
*
* ```html
* <span class="CoveoResultFolding" data-result-template-id="Foo"></span>
* ```
*
* Specifying a previously registered template by referring to a CSS selector:
*
* ```html
* <span class='CoveoResultFolding' data-result-template-selector="#Foo"></span>
* ```
*
* If you do not specify a custom folding template, the component uses the default result folding template.
*/
resultTemplate: TemplateComponentOptions.buildTemplateOption({ defaultFunction: () => new DefaultFoldingTemplate() }),
/**
* Specifies the caption to display at the top of the child results when the folding result set is not expanded.
*
* Default value is `undefined`, which displays no caption.
*/
normalCaption: ComponentOptions.buildLocalizedStringOption(),
/**
* Specifies the caption to display at the top of the child results when the folding result set is expanded.
*
* Default value is `undefined`, which displays no caption.
*/
expandedCaption: ComponentOptions.buildLocalizedStringOption(),
/**
* Specifies the caption to display on the link to expand / show child results.
*
* Default value is the localized string for `ShowMore`.
*/
moreCaption: ComponentOptions.buildLocalizedStringOption({ postProcessing: value => value || l('ShowMore') }),
/**
* Specifies the caption to display on the link to shrink the loaded folding result set back to only the top result.
*
* Default value is the localized string for `ShowLess`.
*/
lessCaption: ComponentOptions.buildLocalizedStringOption({ postProcessing: value => value || l('ShowLess') }),
/**
* Specifies the caption to display when there is only one result in a folding result set.
*
* Default value is the localized string for `DisplayingTheOnlyMessage`
*/
oneResultCaption: ComponentOptions.buildLocalizedStringOption({
postProcessing: value => value || l('DisplayingTheOnlyMessage')
})
};
private normalCaption: HTMLElement;
private expandedCaption: HTMLElement;
private oneResultCaption: HTMLElement;
private results: HTMLElement;
private showMore: HTMLElement;
private showLess: HTMLElement;
private waitAnimation: HTMLElement;
private moreResultsPromise: Promise<IQueryResult[]>;
private showingMoreResults = false;
public childResults: IQueryResult[];
/**
* Creates a new ResultFolding component.
* @param options The options for the ResultFolding component.
* @param bindings The bindings that the component requires to function normally. If not set, these will be
* automatically resolved (with a slower execution time).
* @param result The result to associate the component with.
*/
constructor(
public element: HTMLElement,
public options?: IResultFoldingOptions,
bindings?: IComponentBindings,
public result?: IQueryResult
) {
super(element, ResultFolding.ID, bindings);
this.options = ComponentOptions.initComponentOptions(this.element, ResultFolding, options);
Assert.exists(result);
this.buildElements();
this.renderElements();
}
/**
* Show more results by fetching additional results from the index, which match the current folded conversation.
* This is the equivalent of clicking "Show all conversation".
* @returns {Promise<IQueryResult[]>}
*/
public async showMoreResults() {
Assert.exists(this.result.moreResults);
this.cancelAnyPendingShowMore();
this.moreResultsPromise = this.result.moreResults();
this.waitAnimation = $$('div', { className: 'coveo-loading-spinner' }).el;
this.results.appendChild(this.waitAnimation);
this.updateElementVisibility();
const results = await this.moreResultsPromise;
this.childResults = results;
this.showingMoreResults = true;
this.usageAnalytics.logClickEvent<IAnalyticsDocumentViewMeta>(
analyticsActionCauseList.foldingShowMore,
this.getAnalyticsMetadata(),
this.result,
this.element
);
try {
await this.displayThoseResults(results);
this.updateElementVisibility(results.length);
} catch (e) {
const logger = new Logger(this);
logger.warn('An error occured when trying to display more results');
}
this.moreResultsPromise = undefined;
$$(this.waitAnimation).detach();
this.waitAnimation = undefined;
return results;
}
/**
* Show less results for a given conversation. This is the equivalent of clicking "Show less"
*/
public async showLessResults() {
this.cancelAnyPendingShowMore();
this.showingMoreResults = false;
this.usageAnalytics.logCustomEvent<IAnalyticsDocumentViewMeta>(
analyticsActionCauseList.foldingShowLess,
this.getAnalyticsMetadata(),
this.element
);
await this.displayThoseResults(this.result.childResults);
this.updateElementVisibility();
this.scrollToResultElement();
}
private buildElements() {
this.buildHeader();
this.buildResults();
this.buildFooter();
}
private async renderElements() {
await this.displayThoseResults(this.result.childResults);
this.updateElementVisibility();
if ($$(this.element.parentElement).hasClass('CoveoCardOverlay')) {
this.bindOverlayEvents();
}
if (this.result.childResults.length == 0 && !this.result.moreResults) {
$$(this.element).hide();
}
}
private buildHeader() {
let header = $$('div', { className: 'coveo-folding-header' }).el;
this.element.appendChild(header);
if (this.options.normalCaption != undefined && this.options.expandedCaption != undefined) {
this.normalCaption = $$('div', { className: 'coveo-folding-normal-caption' }, this.options.normalCaption).el;
header.appendChild(this.normalCaption);
this.expandedCaption = $$('div', { className: 'coveo-folding-expanded-caption' }, this.options.expandedCaption).el;
header.appendChild(this.expandedCaption);
}
this.oneResultCaption = $$('div', { className: 'coveo-folding-oneresult-caption' }, this.options.oneResultCaption).el;
header.appendChild(this.oneResultCaption);
}
private buildResults() {
this.results = $$('div', { className: 'coveo-folding-results' }).el;
this.element.appendChild(this.results);
}
private buildFooter() {
const footer = $$('div', { className: 'coveo-folding-footer' }).el;
this.element.parentElement.appendChild(footer);
if (this.result.moreResults) {
this.showMore = $$('div', { className: 'coveo-folding-footer-section-for-less' }).el;
footer.appendChild(this.showMore);
this.showLess = $$('div', { className: 'coveo-folding-footer-section-for-more' }).el;
footer.appendChild(this.showLess);
const footerIconShowMore = $$(
'div',
{ className: 'coveo-folding-more' },
$$('span', { className: 'coveo-folding-footer-icon' }, SVGIcons.icons.arrowDown).el
).el;
SVGDom.addClassToSVGInContainer(footerIconShowMore, 'coveo-folding-more-svg');
const footerIconShowLess = $$(
'div',
{ className: 'coveo-folding-less' },
$$('span', { className: 'coveo-folding-footer-icon' }, SVGIcons.icons.arrowUp).el
).el;
SVGDom.addClassToSVGInContainer(footerIconShowLess, 'coveo-folding-less-svg');
const showMoreLink = $$('a', { className: 'coveo-folding-show-more' }, this.options.moreCaption).el;
const showLessLink = $$('a', { className: 'coveo-folding-show-less' }, this.options.lessCaption).el;
new AccessibleButton()
.withElement(this.showMore)
.withLabel(this.options.moreCaption)
.withSelectAction(() => this.showMoreResults())
.build();
new AccessibleButton()
.withElement(this.showLess)
.withLabel(this.options.lessCaption)
.withSelectAction(() => this.showLessResults())
.build();
this.showMore.appendChild(showMoreLink);
this.showLess.appendChild(showLessLink);
this.showMore.appendChild(footerIconShowMore);
this.showLess.appendChild(footerIconShowLess);
}
}
private updateElementVisibility(subResultsLength?: number) {
if (this.normalCaption) {
$$(this.normalCaption).toggle(!this.showingMoreResults && this.result.childResults.length > 0);
}
if (this.expandedCaption) {
$$(this.expandedCaption).toggle(this.showingMoreResults);
}
$$(this.oneResultCaption).toggleClass('coveo-hidden', !(subResultsLength && subResultsLength == 1));
if (this.showMore) {
$$(this.showMore).toggleClass('coveo-visible', !this.showingMoreResults && !Utils.exists(this.moreResultsPromise));
$$(this.showLess).toggleClass('coveo-visible', this.showingMoreResults);
}
let showIfNormal = $$(this.element).find('.coveo-show-if-normal');
if (showIfNormal) {
$$(showIfNormal).toggle(!this.showingMoreResults);
}
let showIfExpanded = $$(this.element).find('.coveo-show-if-expanded');
if (showIfExpanded) {
$$(showIfExpanded).toggle(this.showingMoreResults);
}
}
private scrollToResultElement() {
let resultElem = $$(this.element).closest('CoveoResult');
window.scrollTo(0, new Win(window).scrollY() + resultElem.getBoundingClientRect().top);
}
private async displayThoseResults(results: IQueryResult[]): Promise<boolean> {
const childResultsPromises = map(results, result => {
return this.renderChildResult(result);
});
const childsToAppend: HTMLElement[] = await Promise.all(childResultsPromises);
$$(this.results).empty();
each(childsToAppend, oneChild => {
this.results.appendChild(oneChild);
});
return true;
}
private async renderChildResult(childResult: IQueryResult): Promise<HTMLElement> {
QueryUtils.setStateObjectOnQueryResult(this.queryStateModel.get(), childResult);
QueryUtils.setSearchInterfaceObjectOnQueryResult(this.searchInterface, childResult);
const oneChild: HTMLElement = await this.options.resultTemplate.instantiateToElement(childResult, {
wrapInDiv: false,
checkCondition: false,
responsiveComponents: this.searchInterface.responsiveComponents
});
$$(oneChild).addClass('coveo-result-folding-child-result');
$$(oneChild).toggleClass('coveo-normal-child-result', !this.showingMoreResults);
$$(oneChild).toggleClass('coveo-expanded-child-result', this.showingMoreResults);
await Initialization.automaticallyCreateComponentsInsideResult(oneChild, childResult).initResult;
return oneChild;
}
private cancelAnyPendingShowMore() {
if (this.moreResultsPromise) {
this.moreResultsPromise = undefined;
}
Assert.doesNotExists(this.moreResultsPromise);
Assert.doesNotExists(this.waitAnimation);
}
private bindOverlayEvents() {
this.bind.one(this.element.parentElement, 'openCardOverlay', () => {
if (this.result.moreResults) {
this.showMoreResults();
}
});
}
private getAnalyticsMetadata(): IAnalyticsDocumentViewMeta {
return {
documentURL: this.result.clickUri,
documentTitle: this.result.title,
author: Utils.getFieldValue(this.result, 'author')
};
}
}
Initialization.registerAutoCreateComponent(ResultFolding); | the_stack |
import { IonicNativePlugin } from "@ionic-native/core";
export declare enum AdParamErrorCodes {
AD_PARAM_INNER = 0,
AD_PARAM_INVALID_REQUEST = 1,
AD_PARAM_NETWORK_ERROR = 2,
AD_PARAM_NO_AD = 3,
AD_PARAM_AD_LOADING = 4,
AD_PARAM_LOW_API = 5,
AD_PARAM_BANNER_AD_EXPIRE = 6,
AD_PARAM_BANNER_AD_CANCEL = 7,
AD_PARAM_HMS_NOT_SUPPORT_SET_APP = 8
}
export declare enum RewardAdStatusErrorCodes {
REWARD_AD_STATUS_INTERNAL = 0,
REWARD_AD_STATUS_REUSED = 1,
REWARD_AD_STATUS_NOT_LOADED = 2,
REWARD_AD_STATUS_BACKGROUND = 3
}
export declare enum AdContentClassification {
AD_CONTENT_CLASSIFICATION_A = "A",
AD_CONTENT_CLASSIFICATION_PI = "PI",
AD_CONTENT_CLASSIFICATION_UNKNOWN = "",
AD_CONTENT_CLASSIFICATION_J = "J",
AD_CONTENT_CLASSIFICATION_W = "W"
}
export declare enum Gender {
FEMALE = 2,
MALE = 1,
UNKNOWN = 0
}
export declare enum NonPersonalizedAd {
ALLOW_ALL = 0,
ALLOW_NON_PERSONALIZED = 1
}
export declare enum ChildProtection {
TAG_FOR_CHILD_PROTECTION_UNSPECIFIED = -1,
TAG_FOR_CHILD_PROTECTION_FALSE = 0,
TAG_FOR_CHILD_PROTECTION_TRUE = 1
}
export declare enum UnderAgeOfPromise {
PROMISE_UNSPECIFIED = -1,
PROMISE_FALSE = 0,
PROMISE_TRUE = 1
}
export declare enum BannerAdSize {
BANNER_SIZE_360_57 = "BANNER_SIZE_360_57",
BANNER_SIZE_360_144 = "BANNER_SIZE_360_144",
BANNER_SIZE_160_600 = "BANNER_SIZE_160_600",
BANNER_SIZE_300_250 = "BANNER_SIZE_300_250",
BANNER_SIZE_320_100 = "BANNER_SIZE_320_100",
BANNER_SIZE_320_50 = "BANNER_SIZE_320_50",
BANNER_SIZE_468_60 = "BANNER_SIZE_468_60",
BANNER_SIZE_728_90 = "BANNER_SIZE_728_90",
BANNER_SIZE_DYNAMIC = "BANNER_SIZE_DYNAMIC",
BANNER_SIZE_INVALID = "BANNER_SIZE_INVALID",
BANNER_SIZE_SMART = "BANNER_SIZE_SMART"
}
export declare enum HMSScreenOrientation {
SCREEN_ORIENTATION_LANDSCAPE = 0,
SCREEN_ORIENTATION_UNSPECIFIED = -1,
SCREEN_ORIENTATION_PORTRAIT = 1,
SCREEN_ORIENTATION_USER = 2,
SCREEN_ORIENTATION_BEHIND = 3,
SCREEN_ORIENTATION_SENSOR = 4,
SCREEN_ORIENTATION_NOSENSOR = 5,
SCREEN_ORIENTATION_SENSOR_LANDSCAPE = 6,
SCREEN_ORIENTATION_SENSOR_PORTRAIT = 7,
SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8,
SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9,
SCREEN_ORIENTATION_FULL_SENSOR = 10,
SCREEN_ORIENTATION_USER_LANDSCAPE = 11,
SCREEN_ORIENTATION_USER_PORTRAIT = 12,
SCREEN_ORIENTATION_FULL_USER = 13,
SCREEN_ORIENTATION_LOCKED = 14
}
export declare enum DebugNeedConsent {
CONSENT_DEBUG_DISABLED = 0,
CONSENT_DEBUG_NEED_CONSENT = 1,
CONSENT_DEBUG_NOT_NEED_CONSENT = 2
}
export declare enum ConsentStatus {
CONSENT_PERSONALIZED = 0,
CONSENT_NON_PERSONALIZED = 1,
CONSENT_UNKNOWN = 2
}
export declare enum AudioFocusType {
GAIN_AUDIO_FOCUS_ALL = 0,
NOT_GAIN_AUDIO_FOCUS_WHEN_MUTE = 1,
NOT_GAIN_AUDIO_FOCUS_ALL = 2
}
export declare enum MediaAspect {
ASPECT_ANY = 1,
ASPECT_CUSTOM_SIZE = -1,
ASPECT_LANDSCAPE = 2,
ASPECT_PORTRAIT = 3,
ASPECT_SQUARE = 4,
ASPECT_UNKNOWN = 0
}
export declare enum ChoicesPosition {
BOTTOM_LEFT = 3,
BOTTOM_RIGHT = 2,
INVISIBLE = 4,
TOP_LEFT = 0,
TOP_RIGHT = 1
}
export declare enum MediaDirection {
ANY = 0,
LANDSCAPE = 2,
PORTRAIT = 1
}
export declare enum NativeAdTemplate {
NATIVE_AD_SMALL_TEMPLATE = "NATIVE_AD_SMALL_TEMPLATE",
NATIVE_AD_FULL_TEMPLATE = "NATIVE_AD_FULL_TEMPLATE",
NATIVE_AD_BANNER_TEMPLATE = "NATIVE_AD_BANNER_TEMPLATE",
NATIVE_AD_VIDEO_TEMPLATE = "NATIVE_AD_VIDEO_TEMPLATE"
}
export declare enum Color {
RED = "RED",
DKGRAY = "DKGRAY",
GRAY = "GRAY",
WHITE = "WHITE",
BLUE = "BLUE",
BLACK = "BLACK",
LTGRAY = "LTGRAY",
MAGENTA = "MAGENTA",
YELLOW = "YELLOW",
CYAN = "CYAN",
GREEN = "GREEN",
TRANSPARENT = "TRANSPARENT"
}
export declare enum InstallReferrerResponses {
SERVICE_DISCONNECTED = -1,
DEVELOPER_ERROR = 3,
SERVICE_UNAVAILABLE = 1,
OK = 0,
FEATURE_NOT_SUPPORTED = 2
}
export declare enum Anchor {
TOP = "top",
BOTTOM = "bottom",
INVISIBLE = "invisible"
}
export declare enum BannerAdEvents {
BANNER_AD_CLOSED = "banner_ad_closed",
BANNER_AD_FAILED = "banner_ad_failed",
BANNER_AD_LEAVE = "banner_ad_leave",
BANNER_AD_OPENED = "banner_ad_opened",
BANNER_AD_LOADED = "banner_ad_loaded",
BANNER_AD_CLICKED = "banner_ad_clicked",
BANNER_AD_IMPRESSION = "banner_ad_impression"
}
export declare enum InterstitialAdEvents {
INTERSTITIAL_AD_CLOSED = "interstitial_ad_closed",
INTERSTITIAL_AD_FAILED = "interstitial_ad_failed",
INTERSTITIAL_AD_LEAVE = "interstitial_ad_leave",
INTERSTITIAL_AD_OPENED = "interstitial_ad_opened",
INTERSTITIAL_AD_LOADED = "interstitial_ad_loaded",
INTERSTITIAL_AD_CLICKED = "interstitial_ad_clicked",
INTERSTITIAL_AD_IMPRESSION = "interstitial_ad_impression",
INTERSTITIAL_AD_REWARDED = "interstitial_ad_rewarded",
INTERSTITIAL_REWARD_AD_CLOSED = "interstitial_reward_ad_closed",
INTERSTITIAL_REWARD_AD_FAILED_TO_LOAD = "interstitial_reward_ad_failed_to_load",
INTERSTITIAL_REWARD_AD_LEFT_APP = "interstitial_reward_ad_left_app",
INTERSTITIAL_REWARD_AD_LOADED = "interstitial_reward_ad_loaded",
INTERSTITIAL_REWARD_AD_OPENED = "interstitial_reward_ad_opened",
INTERSTITIAL_REWARD_AD_COMPLETED = "interstitial_reward_ad_completed",
INTERSTITIAL_REWARD_AD_STARTED = "interstitial_reward_ad_started"
}
export declare enum SplashAdEvents {
SPLASH_AD_FAILED_TO_LOAD = "splash_ad_failed_to_load",
SPLASH_AD_LOADED = "splash_ad_loaded",
SPLASH_AD_DISMISSED = "splash_ad_dismissed",
SPLASH_AD_SHOWED = "splash_ad_showed",
SPLASH_AD_CLICK = "splash_ad_click"
}
export declare enum RollAdEvents {
ROLL_AD_LOAD_FAILED = "roll_ad_load_failed",
ROLL_AD_LOADED = "roll_ad_loaded",
ROLL_AD_MEDIA_CHANGED = "roll_ad_media_changed",
ROLL_AD_CLICKED = "roll_ad_clicked",
ROLL_AD_MEDIA_PROGRESS = "roll_ad_media_progress",
ROLL_AD_MEDIA_START = "roll_ad_media_start",
ROLL_AD_MEDIA_PAUSE = "roll_ad_media_pause",
ROLL_AD_MEDIA_STOP = "roll_ad_media_stop",
ROLL_AD_MEDIA_COMPLETION = "roll_ad_media_completion",
ROLL_AD_MEDIA_ERROR = "roll_ad_media_error",
ROLL_AD_MEDIA_UNMUTE = "roll_ad_media_unmute",
ROLL_AD_MEDIA_MUTE = "roll_ad_media_mute",
ROLL_AD_WHY_THIS_AD = "roll_ad_why_this_ad"
}
export declare enum RewardAdEvents {
REWARD_METADATA_CHANGED = "reward_metadata_changed",
REWARD_AD_FAILED_TO_LOAD_LOAD = "reward_ad_failed_to_load_load",
REWARDED_LOADED = "rewarded_loaded",
REWARDED_STATUS = "rewarded_status",
REWARD_AD_CLOSED_STATUS = "reward_ad_closed_status",
REWARD_AD_OPENED_STATUS = "reward_ad_opened_status",
REWARD_AD_FAILED_TO_SHOW = "reward_ad_failed_to_show",
REWARDED = "rewarded",
REWARD_AD_CLOSED = "reward_ad_closed",
REWARD_AD_FAILED_TO_LOAD = "reward_ad_failed_to_load",
REWARD_AD_LOADED = "reward_ad_loaded",
REWARD_AD_OPENED = "reward_ad_opened"
}
export declare enum DetailedCreativeType {
BIG_IMG = 901,
VIDEO = 903,
THREE_IMG = 904,
SMALL_IMG = 905,
SINGLE_IMG = 909,
SHORT_TEXT = 913,
LONG_TEXT = 914
}
export declare enum NativeAdEvents {
NATIVE_AD_DISLIKED = "native_ad_disliked",
NATIVE_AD_LOADED_LOAD = "native_ad_loaded_load",
NATIVE_AD_CLOSED = "native_ad_closed",
NATIVE_AD_FAILED = "native_ad_failed",
NATIVE_AD_LEAVE = "native_ad_leave",
NATIVE_AD_OPENED = "native_ad_opened",
NATIVE_AD_LOADED = "native_ad_loaded",
NATIVE_AD_CLICKED = "native_ad_clicked",
NATIVE_AD_IMPRESSION = "native_ad_impression",
VIDEO_OPERATOR_VIDEO_START = "video_operator_video_start",
VIDEO_OPERATOR_VIDEO_PLAY = "video_operator_video_play",
VIDEO_OPERATOR_VIDEO_PAUSE = "video_operator_video_pause",
VIDEO_OPERATOR_VIDEO_END = "video_operator_video_end",
VIDEO_OPERATOR_VIDEO_MUTE = "video_operator_video_mute"
}
export interface LayoutBounds {
marginLeft?: number;
marginRight?: number;
marginTop?: number;
marginBottom?: number;
}
export interface Props {
x: number;
y: number;
width: number;
height: number;
marginLeft?: number;
marginRight?: number;
marginTop?: number;
marginBottom?: number;
pageXOffset?: number;
pageYOffset?: number;
}
export interface AdParam {
gender?: Gender;
adContentClassification?: AdContentClassification;
tagForUnderAgeOfPromise?: UnderAgeOfPromise;
tagForChildProtection?: ChildProtection;
nonPersonalizedAd?: NonPersonalizedAd;
appCountry?: string;
appLang?: string;
countryCode?: string;
belongCountryCode?: string;
consent?: string;
requestLocation?: boolean;
detailedCreativeType?: DetailedCreativeType[];
}
export interface HMSRequestOptions {
adContentClassification?: AdContentClassification;
appLang?: string;
appCountry?: string;
tagForChildProtection?: ChildProtection;
tagForUnderAgeOfPromise?: UnderAgeOfPromise;
nonPersonalizedAd?: NonPersonalizedAd;
consent?: string;
requestLocation?: boolean;
}
export interface HMSReward {
rewardAmount: number;
rewardName: string;
}
export interface HMSRewardVerifyConfig {
data: string;
userId: string;
}
export interface OaidResult {
id: string;
isLimitAdTracingEnabled: boolean;
}
export interface Duration {
duration: number;
}
export interface RollAdLoaderParams {
adId: string;
totalDuration: number;
maxCount: number;
}
export interface VideoConfiguration {
audioFocusType?: AudioFocusType;
clickToFullScreenRequest?: boolean;
customizeOperateRequested?: boolean;
isStartMuted?: boolean;
}
export interface NativeAdConfiguration {
adSize: AdSize;
choicesPosition?: ChoicesPosition;
mediaAspect?: MediaAspect;
mediaDirection?: MediaDirection;
returnUrlsForImages?: boolean;
requestCustomDislikeThisAd?: boolean;
requestMultiImages?: boolean;
videoConfiguration?: VideoConfiguration;
}
export interface VideoOperatorAspectRatio {
videoOperatorGetAspectRatio: number;
}
export interface NativeAdLoadOptions {
adId?: string;
ad?: AdParam;
nativeAdOptions?: NativeAdConfiguration;
}
export interface AdSize {
width: number;
height: number;
}
export interface NativeAdOptions {
div: string;
template?: NativeAdTemplate;
bg?: Color;
}
export interface RollAdLoadOptions {
file?: string;
adParam?: AdParam;
}
export interface ReferrerDetails {
responseCode?: InstallReferrerResponses;
installReferrer?: string;
referrerClickTimestamp?: number;
installBeginTimestamp?: number;
}
export interface ConsentUpdateResult {
consentStatus?: ConsentStatus;
isNeedConsent?: boolean;
adProviders?: AdProvider[];
}
export interface AdProvider {
id?: string;
name?: string;
privacyPolicyUrl?: string;
serviceArea?: string;
}
export interface SplashAdLoadOptions {
adId: string;
orientation?: HMSScreenOrientation;
adParam?: AdParam;
logoAnchor?: Anchor;
}
export declare class HMSAds extends IonicNativePlugin {
HMSInterstitialAd: typeof HMSInterstitialAd;
HMSBannerAd: typeof HMSBannerAd;
HMSSplashAd: typeof HMSSplashAd;
HMSRewardAd: typeof HMSRewardAd;
HMSNativeAd: typeof HMSNativeAd;
HMSRollAd: typeof HMSRollAd;
on(event: string, callback: () => void): void;
init(): Promise<void>;
getSDKVersion(): Promise<string>;
getRequestOptions(): Promise<HMSRequestOptions>;
setRequestOptions(requestOptions: HMSRequestOptions): Promise<void>;
setConsent(consent: string): Promise<void>;
enableLogger(): Promise<any>;
disableLogger(): Promise<any>;
addTestDeviceId(testDeviceId: string): Promise<void>;
getTestDeviceId(): Promise<string>;
setUnderAgeOfPromise(underAgeOfPromise: boolean): Promise<void>;
setConsentStatus(consentStatus: ConsentStatus): Promise<void>;
setDebugNeedConsent(debugNeedConsent: DebugNeedConsent): Promise<any>;
requestConsentUpdate(): Promise<ConsentUpdateResult>;
verifyAdId(adId: string, isLimitAdTracking: boolean): Promise<boolean>;
getAdvertisingIdInfo(): Promise<OaidResult>;
referrerClientStartConnection(isTest?: boolean): Promise<number>;
referrerClientEndConnection(): Promise<void>;
referrerClientIsReady(): Promise<boolean>;
getInstallReferrer(): Promise<ReferrerDetails>;
}
export declare class HMSBannerAd extends IonicNativePlugin {
on(eventName: BannerAdEvents, callback: (result?: any) => void): void;
create(divId: string, bounds?: LayoutBounds): Promise<HMSBannerAd>;
scroll(): void;
getAdId(): Promise<string>;
setAdId(adId: string): Promise<void>;
getBannerAdSize(): Promise<AdSize>;
setBannerAdSize(bannerAdSize: BannerAdSize | AdSize): Promise<void>;
setBackgroundColor(bgColor: Color): Promise<void>;
setBannerRefresh(bannerRefresh: number): Promise<void>;
setAdListener(): Promise<void>;
isLoading(): Promise<boolean>;
loadAd(adParam?: AdParam): Promise<void>;
pause(): Promise<void>;
resume(): Promise<void>;
destroy(): Promise<void>;
getHeight(): Promise<number>;
getHeightPx(): Promise<number>;
getWidth(): Promise<number>;
getWidthPx(): Promise<number>;
isAutoHeightSize(): Promise<boolean>;
isDynamicSize(): Promise<boolean>;
isFullWidthSize(): Promise<boolean>;
getCurrentDirectionBannerSize(width: number): Promise<AdSize>;
getLandscapeBannerSize(width: number): Promise<AdSize>;
getPortraitBannerSize(width: number): Promise<AdSize>;
}
export declare class HMSInterstitialAd extends IonicNativePlugin {
on(eventName: InterstitialAdEvents, callback: (result?: any) => void): void;
create(useActivity: boolean): Promise<HMSInterstitialAd>;
scroll(): void;
show(): Promise<void>;
isLoaded(): Promise<boolean>;
isLoading(): Promise<boolean>;
loadAd(adParam?: AdParam): Promise<void>;
setAdId(adId: string): Promise<void>;
getAdId(): Promise<string>;
setAdListener(): Promise<void>;
setRewardAdListener(): Promise<void>;
videoOperatorGetAspectRatio(): Promise<VideoOperatorAspectRatio>;
videoOperatorHasVideo(): Promise<boolean>;
videoOperatorIsCustomizeOperateEnabled(): Promise<boolean>;
videoOperatorIsMuted(): Promise<boolean>;
videoOperatorMute(mute: boolean): Promise<void>;
videoOperatorPause(): Promise<void>;
videoOperatorPlay(): Promise<void>;
videoOperatorStop(): Promise<void>;
}
export declare class HMSNativeAd extends IonicNativePlugin {
on(eventName: NativeAdEvents, callback: (result?: any) => void): void;
create(options: NativeAdOptions, bounds?: LayoutBounds): Promise<HMSNativeAd>;
loadAd(options?: NativeAdLoadOptions): Promise<void>;
show(): Promise<void>;
isLoading(): Promise<boolean>;
destroy(): Promise<void>;
dislikeAd(dislikeReason: string): Promise<void>;
setAllowCustomClick(): Promise<void>;
getAdSource(): Promise<string>;
getDescription(): Promise<string>;
getCallToAction(): Promise<string>;
getDislikeAdReasons(): Promise<string[]>;
isCustomClickAllowed(): Promise<boolean>;
isCustomDislikeThisAdEnabled(): Promise<boolean>;
recordClickEvent(): Promise<void>;
recordImpressionEvent(impressionData: any): Promise<boolean>;
getUniqueId(): Promise<string>;
setDislikeAdListener(): Promise<void>;
gotoWhyThisAdPage(useView: boolean): Promise<void>;
getAdSign(): Promise<string>;
getTitle(): Promise<string>;
getWhyThisAd(): Promise<string>;
recordShowStartEvent(showStartData: any): Promise<boolean>;
onAdClose(keywords: string[]): Promise<void>;
getNativeAdConfiguration(): Promise<NativeAdConfiguration>;
}
export declare class HMSRewardAd extends IonicNativePlugin {
on(eventName: RewardAdEvents, callback: (result?: any) => void): void;
create(adId: string): Promise<HMSRewardAd>;
show(useActivity: boolean): Promise<void>;
resume(): Promise<void>;
pause(): Promise<void>;
destroy(): Promise<void>;
loadAdWithAdId(adId: string, adParam?: AdParam): Promise<void>;
loadAd(adParam?: AdParam): Promise<void>;
isLoaded(): Promise<boolean>;
getData(): Promise<string>;
getUserId(): Promise<string>;
getReward(): Promise<HMSReward>;
setData(data: string): Promise<void>;
setImmersive(immersive: boolean): Promise<void>;
setUserId(userId: string): Promise<void>;
setRewardVerifyConfig(config: HMSRewardVerifyConfig): Promise<void>;
getRewardVerifyConfig(): Promise<HMSRewardVerifyConfig>;
setOnMetadataChangedListener(): Promise<void>;
setRewardAdListener(): Promise<void>;
}
export declare class HMSRollAd extends IonicNativePlugin {
on(eventName: RollAdEvents, callback: (result?: any) => void): void;
create(params: RollAdLoaderParams, divId: string, bounds?: LayoutBounds): Promise<HMSRollAd>;
scroll(): void;
loadAd(options: RollAdLoadOptions): Promise<void>;
isLoading(): Promise<boolean>;
destroy(): Promise<void>;
pause(): Promise<void>;
isPlaying(): Promise<boolean>;
mute(): Promise<void>;
unmute(): Promise<void>;
onClose(): Promise<void>;
play(): Promise<void>;
stop(): Promise<void>;
removeInstreamMediaChangeListener(): Promise<void>;
removeMediaMuteListener(): Promise<void>;
removeInstreamMediaStateListener(): Promise<void>;
setInstreamAds(): Promise<void>;
setInstreamMediaChangeListener(): Promise<void>;
setMediaMuteListener(): Promise<void>;
setInstreamMediaStateListener(): Promise<void>;
setOnInstreamAdClickListener(): Promise<void>;
getAdSource(): Promise<string>;
getDuration(): Promise<Duration>;
getWhyThisAd(): Promise<string>;
getAdSign(): Promise<string>;
isClicked(): Promise<boolean>;
isExpired(): Promise<boolean>;
isImageAd(): Promise<boolean>;
isShown(): Promise<boolean>;
isVideoAd(): Promise<boolean>;
getCallToAction(): Promise<string>;
}
export declare class HMSSplashAd extends IonicNativePlugin {
on(eventName: SplashAdEvents, callback: (result?: any) => void): void;
create(): Promise<HMSSplashAd>;
setLogo(file: string): Promise<void>;
setWideSloganResId(wideSloganResId: string): Promise<void>;
setSloganResId(sloganResId: string): Promise<void>;
load(options: SplashAdLoadOptions): Promise<void>;
preloadAd(options: SplashAdLoadOptions): Promise<void>;
destroyView(): Promise<void>;
pauseView(): Promise<void>;
resumeView(): Promise<void>;
isLoading(): Promise<boolean>;
isLoaded(): Promise<boolean>;
setAdDisplayListener(): Promise<void>;
setAudioFocusType(audioFocusType: AudioFocusType): Promise<void>;
} | the_stack |
import { IExtractor, ExtractResult, RegExpUtility, StringUtility } from "@microsoft/recognizers-text";
import { BaseNumberParser, BaseNumberExtractor } from "@microsoft/recognizers-text-number";
import { ISetExtractorConfiguration, BaseSetExtractor, ISetParserConfiguration, BaseSetParser } from "../baseSet";
import { BaseDurationExtractor, BaseDurationParser } from "../baseDuration";
import { IDateTimeParser, DateTimeParseResult } from "../parsers";
import { Constants, TimeTypeConstants } from "../constants";
import { BaseDateExtractor, BaseDateParser } from "../baseDate";
import { BaseTimeExtractor, BaseTimeParser } from "../baseTime";
import { BaseDatePeriodExtractor, BaseDatePeriodParser } from "../baseDatePeriod";
import { BaseTimePeriodExtractor, BaseTimePeriodParser } from "../baseTimePeriod";
import { BaseDateTimeExtractor, BaseDateTimeParser, IDateTimeExtractor } from "../baseDateTime";
import { BaseDateTimePeriodExtractor, BaseDateTimePeriodParser } from "../baseDateTimePeriod";
import { ChineseDurationExtractor, ChineseDurationParser } from "./durationConfiguration";
import { ChineseTimeExtractor, ChineseTimeParser } from "./timeConfiguration";
import { ChineseDateExtractor, ChineseDateParser } from "./dateConfiguration";
import { ChineseDateTimeExtractor, ChineseDateTimeParser } from "./dateTimeConfiguration";
import { Token, IDateTimeUtilityConfiguration, DateTimeResolutionResult, StringMap } from "../utilities";
import { ChineseDateTime } from "../../resources/chineseDateTime";
class ChineseSetExtractorConfiguration implements ISetExtractorConfiguration {
readonly lastRegex: RegExp;
readonly eachPrefixRegex: RegExp;
readonly periodicRegex: RegExp;
readonly eachUnitRegex: RegExp;
readonly eachDayRegex: RegExp;
readonly beforeEachDayRegex: RegExp;
readonly setWeekDayRegex: RegExp;
readonly setEachRegex: RegExp;
readonly durationExtractor: ChineseDurationExtractor;
readonly timeExtractor: ChineseTimeExtractor;
readonly dateExtractor: ChineseDateExtractor;
readonly dateTimeExtractor: BaseDateTimeExtractor;
readonly datePeriodExtractor: BaseDatePeriodExtractor;
readonly timePeriodExtractor: BaseTimePeriodExtractor;
readonly dateTimePeriodExtractor: BaseDateTimePeriodExtractor;
constructor(dmyDateFormat: boolean) {
this.eachUnitRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetEachUnitRegex);
this.durationExtractor = new ChineseDurationExtractor();
this.lastRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetLastRegex);
this.eachPrefixRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetEachPrefixRegex);
this.timeExtractor = new ChineseTimeExtractor();
this.beforeEachDayRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetEachDayRegex);
this.eachDayRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetEachDayRegex);
this.dateExtractor = new ChineseDateExtractor(dmyDateFormat);
this.dateTimeExtractor = new ChineseDateTimeExtractor(dmyDateFormat);
}
}
export class ChineseSetExtractor extends BaseSetExtractor {
constructor(dmyDateFormat: boolean) {
super(new ChineseSetExtractorConfiguration(dmyDateFormat));
}
extract(source: string, refDate: Date): ExtractResult[] {
if (!refDate) {
refDate = new Date();
}
let referenceDate = refDate;
let tokens: Token[] = new Array<Token>()
.concat(super.matchEachUnit(source))
.concat(super.matchEachDuration(source, referenceDate))
.concat(this.matchEachSpecific(this.config.timeExtractor, this.config.eachDayRegex, source, referenceDate))
.concat(this.matchEachSpecific(this.config.dateExtractor, this.config.eachPrefixRegex, source, referenceDate))
.concat(this.matchEachSpecific(this.config.dateTimeExtractor, this.config.eachPrefixRegex, source, referenceDate));
let result = Token.mergeAllTokens(tokens, source, this.extractorName);
return result;
}
private matchEachSpecific(extractor: IDateTimeExtractor, eachRegex: RegExp, source: string, refDate: Date) {
let ret = [];
extractor.extract(source, refDate).forEach(er => {
let beforeStr = source.substr(0, er.start);
let beforeMatch = RegExpUtility.getMatches(eachRegex, beforeStr).pop();
if (beforeMatch) {
ret.push(new Token(beforeMatch.index, er.start + er.length));
}
});
return ret;
}
}
class ChineseSetParserConfiguration implements ISetParserConfiguration {
readonly durationExtractor: IDateTimeExtractor;
readonly durationParser: BaseDurationParser;
readonly timeExtractor: IDateTimeExtractor;
readonly timeParser: BaseTimeParser;
readonly dateExtractor: BaseDateExtractor;
readonly dateParser: BaseDateParser;
readonly dateTimeExtractor: BaseDateTimeExtractor;
readonly dateTimeParser: BaseDateTimeParser;
readonly datePeriodExtractor: BaseDatePeriodExtractor;
readonly datePeriodParser: BaseDatePeriodParser;
readonly timePeriodExtractor: BaseTimePeriodExtractor;
readonly timePeriodParser: BaseTimePeriodParser;
readonly dateTimePeriodExtractor: BaseDateTimePeriodExtractor;
readonly dateTimePeriodParser: BaseDateTimePeriodParser;
readonly unitMap: ReadonlyMap<string, string>;
readonly eachPrefixRegex: RegExp;
readonly periodicRegex: RegExp;
readonly eachUnitRegex: RegExp;
readonly eachDayRegex: RegExp;
readonly setWeekDayRegex: RegExp;
readonly setEachRegex: RegExp;
constructor(dmyDateFormat: boolean) {
this.dateExtractor = new ChineseDateExtractor(dmyDateFormat);
this.timeExtractor = new ChineseTimeExtractor();
this.durationExtractor = new ChineseDurationExtractor();
this.dateTimeExtractor = new ChineseDateTimeExtractor(dmyDateFormat);
this.dateParser = new ChineseDateParser(dmyDateFormat);
this.timeParser = new ChineseTimeParser();
this.durationParser = new ChineseDurationParser();
this.dateTimeParser = new ChineseDateTimeParser(dmyDateFormat);
this.unitMap = ChineseDateTime.ParserConfigurationUnitMap;
this.eachUnitRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetEachUnitRegex);
this.eachDayRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetEachDayRegex);
this.eachPrefixRegex = RegExpUtility.getSafeRegExp(ChineseDateTime.SetEachPrefixRegex);
}
public getMatchedDailyTimex(text: string): { matched: boolean, timex: string } {
return null;
}
public getMatchedUnitTimex(source: string): { matched: boolean, timex: string } {
let timex = '';
if (source === '天' || source === '日') {
timex = 'P1D';
}
else if (source === '周' || source === '星期') {
timex = 'P1W';
}
else if (source === '月') {
timex = 'P1M';
}
else if (source === '年') {
timex = 'P1Y';
}
return { matched: timex !== '', timex: timex };
}
}
export class ChineseSetParser extends BaseSetParser {
constructor(dmyDateFormat: boolean) {
let config = new ChineseSetParserConfiguration(dmyDateFormat);
super(config);
}
parse(er: ExtractResult, referenceDate?: Date): DateTimeParseResult | null {
if (!referenceDate) {
referenceDate = new Date();
}
let value = null;
if (er.type === BaseSetParser.ParserName) {
let innerResult = this.parseEachUnit(er.text);
if (!innerResult.success) {
innerResult = this.parseEachDuration(er.text, referenceDate);
}
if (!innerResult.success) {
innerResult = this.parserTimeEveryday(er.text, referenceDate);
}
if (!innerResult.success) {
innerResult = this.parseEach(this.config.dateTimeExtractor, this.config.dateTimeParser, er.text, referenceDate);
}
if (!innerResult.success) {
innerResult = this.parseEach(this.config.dateExtractor, this.config.dateParser, er.text, referenceDate);
}
if (innerResult.success) {
innerResult.futureResolution = {};
innerResult.futureResolution[TimeTypeConstants.SET] = innerResult.futureValue;
innerResult.pastResolution = {};
innerResult.pastResolution[TimeTypeConstants.SET] = innerResult.pastValue;
value = innerResult;
}
}
let ret = new DateTimeParseResult(er);
ret.value = value,
ret.timexStr = value === null ? "" : value.timex,
ret.resolutionStr = "";
return ret;
}
protected parseEachUnit(text: string): DateTimeResolutionResult {
let ret = new DateTimeResolutionResult();
// handle "each month"
let match = RegExpUtility.getMatches(this.config.eachUnitRegex, text).pop();
if (!match || match.length !== text.length) {
return ret;
}
let sourceUnit = match.groups("unit").value;
if (StringUtility.isNullOrEmpty(sourceUnit) || !this.config.unitMap.has(sourceUnit)) {
return ret;
}
let getMatchedUnitTimex = this.config.getMatchedUnitTimex(sourceUnit);
if (!getMatchedUnitTimex.matched) {
return ret;
}
ret.timex = getMatchedUnitTimex.timex;
ret.futureValue = "Set: " + ret.timex;
ret.pastValue = "Set: " + ret.timex;
ret.success = true;
return ret;
}
protected parserTimeEveryday(text: string, refDate: Date): DateTimeResolutionResult {
let result = new DateTimeResolutionResult();
let ers = this.config.timeExtractor.extract(text, refDate);
if (ers.length !== 1) {
return result;
}
let er = ers[0];
let beforeStr = text.substr(0, er.start);
let match = RegExpUtility.getMatches(this.config.eachDayRegex, beforeStr).pop();
if (!match) {
return result;
}
let pr = this.config.timeParser.parse(er);
result.timex = pr.timexStr;
result.futureValue = "Set: " + result.timex;
result.pastValue = "Set: " + result.timex;
result.success = true;
return result;
}
protected parseEach(extractor: IDateTimeExtractor, parser: IDateTimeParser, text: string, refDate: Date): DateTimeResolutionResult {
let result = new DateTimeResolutionResult();
let ers = extractor.extract(text, refDate);
if (ers.length !== 1) {
return result;
}
let er = ers[0];
let beforeStr = text.substr(0, er.start);
let match = RegExpUtility.getMatches(this.config.eachPrefixRegex, beforeStr).pop();
if (!match) {
return result;
}
let timex = parser.parse(er).timexStr;
result.timex = timex;
result.futureValue = `Set: ${timex}`;
result.pastValue = `Set: ${timex}`;
result.success = true;
return result;
}
} | the_stack |
import * as loggerTypes from '../../common/types';
import * as configTypes from '../config/types';
import { Propagation } from '../propagation/types';
import * as samplerTypes from '../sampler/types';
import { NodeJsEventEmitter } from '../../node/types';
/** Default type for functions */
// tslint:disable:no-any
export type Func<T> = (...args: any[]) => T;
/** Maps a label to a string, number or boolean. */
export interface Attributes {
[attributeKey: string]: string | number | boolean;
}
/**
* The status of a Span by providing a standard CanonicalCode in conjunction
* with an optional descriptive message.
*/
export interface Status {
/** The canonical code of this message. */
code: CanonicalCode;
/** A developer-facing error message. */
message?: string;
}
/** An enumeration of canonical status codes. */
export enum CanonicalCode {
/**
* Not an error; returned on success
*/
OK = 0,
/**
* The operation was cancelled (typically by the caller).
*/
CANCELLED = 1,
/**
* Unknown error. An example of where this error may be returned is
* if a status value received from another address space belongs to
* an error-space that is not known in this address space. Also
* errors raised by APIs that do not return enough error information
* may be converted to this error.
*/
UNKNOWN = 2,
/**
* Client specified an invalid argument. Note that this differs
* from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments
* that are problematic regardless of the state of the system
* (e.g., a malformed file name).
*/
INVALID_ARGUMENT = 3,
/**
* Deadline expired before operation could complete. For operations
* that change the state of the system, this error may be returned
* even if the operation has completed successfully. For example, a
* successful response from a server could have been delayed long
* enough for the deadline to expire.
*/
DEADLINE_EXCEEDED = 4,
/**
* Some requested entity (e.g., file or directory) was not found.
*/
NOT_FOUND = 5,
/**
* Some entity that we attempted to create (e.g., file or directory)
* already exists.
*/
ALREADY_EXISTS = 6,
/**
* The caller does not have permission to execute the specified
* operation. PERMISSION_DENIED must not be used for rejections
* caused by exhausting some resource (use RESOURCE_EXHAUSTED
* instead for those errors). PERMISSION_DENIED must not be
* used if the caller can not be identified (use UNAUTHENTICATED
* instead for those errors).
*/
PERMISSION_DENIED = 7,
/**
* Some resource has been exhausted, perhaps a per-user quota, or
* perhaps the entire file system is out of space.
*/
RESOURCE_EXHAUSTED = 8,
/**
* Operation was rejected because the system is not in a state
* required for the operation's execution. For example, directory
* to be deleted may be non-empty, an rmdir operation is applied to
* a non-directory, etc.
*
* A litmus test that may help a service implementor in deciding
* between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
*
* - Use UNAVAILABLE if the client can retry just the failing call.
* - Use ABORTED if the client should retry at a higher-level
* (e.g., restarting a read-modify-write sequence).
* - Use FAILED_PRECONDITION if the client should not retry until
* the system state has been explicitly fixed. E.g., if an "rmdir"
* fails because the directory is non-empty, FAILED_PRECONDITION
* should be returned since the client should not retry unless
* they have first fixed up the directory by deleting files from it.
* - Use FAILED_PRECONDITION if the client performs conditional
* REST Get/Update/Delete on a resource and the resource on the
* server does not match the condition. E.g., conflicting
* read-modify-write on the same resource.
*/
FAILED_PRECONDITION = 9,
/**
* The operation was aborted, typically due to a concurrency issue
* like sequencer check failures, transaction aborts, etc.
*
* See litmus test above for deciding between FAILED_PRECONDITION,
* ABORTED, and UNAVAILABLE.
*/
ABORTED = 10,
/**
* Operation was attempted past the valid range. E.g., seeking or
* reading past end of file.
*
* Unlike INVALID_ARGUMENT, this error indicates a problem that may
* be fixed if the system state changes. For example, a 32-bit file
* system will generate INVALID_ARGUMENT if asked to read at an
* offset that is not in the range [0,2^32-1], but it will generate
* OUT_OF_RANGE if asked to read from an offset past the current
* file size.
*
* There is a fair bit of overlap between FAILED_PRECONDITION and
* OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific
* error) when it applies so that callers who are iterating through
* a space can easily look for an OUT_OF_RANGE error to detect when
* they are done.
*/
OUT_OF_RANGE = 11,
/**
* Operation is not implemented or not supported/enabled in this service.
*/
UNIMPLEMENTED = 12,
/**
* Internal errors. Means some invariants expected by underlying
* system has been broken. If you see one of these errors,
* something is very broken.
*/
INTERNAL = 13,
/**
* The service is currently unavailable. This is a most likely a
* transient condition and may be corrected by retrying with
* a backoff.
*
* See litmus test above for deciding between FAILED_PRECONDITION,
* ABORTED, and UNAVAILABLE.
*/
UNAVAILABLE = 14,
/**
* Unrecoverable data loss or corruption.
*/
DATA_LOSS = 15,
/**
* The request does not have valid authentication credentials for the
* operation.
*/
UNAUTHENTICATED = 16,
}
/** A text annotation with a set of attributes. */
export interface Annotation {
/** A user-supplied message describing the event. */
description: string;
/** A timestamp for the event event. */
timestamp: number;
/** A set of attributes on the annotation. */
attributes: Attributes;
}
/** An event describing a message sent/received between Spans. */
export interface MessageEvent {
/** A timestamp for the event. */
timestamp: number;
/** Indicates whether the message was sent or received. */
type: MessageEventType;
/**
* An identifier for the MessageEvent's message that can be used to match
* SENT and RECEIVED MessageEvents. Message event ids should start with 1 for
* both sent and received messages and increment by 1 for each message
* sent/received.
*/
id: number;
/** The number of uncompressed bytes sent or received. */
uncompressedSize?: number;
/**
* The number of compressed bytes sent or received. If zero or
* undefined, assumed to be the same size as uncompressed.
*/
compressedSize?: number;
}
/**
* A pointer from the current span to another span in the same trace or in a
* different trace.
*/
export interface Link {
/** The trace ID for a trace within a project. */
traceId: string;
/** The span ID for a span within a trace. */
spanId: string;
/** The relationship of the current span relative to the linked. */
type: LinkType;
/** A set of attributes on the link. */
attributes: Attributes;
}
/** Defines the trace options */
export interface TraceOptions {
/** Root span name */
name: string;
/** Trace context */
spanContext?: SpanContext;
/** Span kind */
kind?: SpanKind;
/** Determines the sampling rate. Ranges from 0.0 to 1.0 */
samplingRate?: number;
}
/** Defines the span options */
export interface SpanOptions {
/** Span name */
name: string;
/** Span kind */
kind?: SpanKind;
/** The new span's parent */
childOf?: Span;
}
export type TraceState = string;
/** Defines the span context */
export interface SpanContext {
/** Trace ID */
traceId: string;
/** Span ID */
spanId: string;
/** Options */
options?: number;
/** TraceState */
traceState?: TraceState;
}
/** Defines an end span event listener */
export interface SpanEventListener {
/** Happens when a span is started */
onStartSpan(span: Span): void;
/** Happens when a span is ended */
onEndSpan(span: Span): void;
}
/** An event describing a message sent/received between Spans. */
export enum MessageEventType {
/** Unknown event type. */
UNSPECIFIED = 0,
/** Indicates a sent message. */
SENT = 1,
/** Indicates a received message. */
RECEIVED = 2,
}
/**
* Type of span. Can be used to specify additional relationships between spans
* in addition to a parent/child relationship.
*/
export enum SpanKind {
/** Unspecified */
UNSPECIFIED = 0,
/**
* Indicates that the span covers server-side handling of an RPC or other
* remote network request.
*/
SERVER = 1,
/**
* Indicates that the span covers the client-side wrapper around an RPC or
* other remote request.
*/
CLIENT = 2,
}
/**
* Type of link. The relationship of the current span relative to the linked
* span.
*/
export enum LinkType {
/**
* The relationship of the two spans is unknown, or known but other
* than parent-child.
*/
UNSPECIFIED = 0,
/** The linked span is a child of the current span. */
CHILD_LINKED_SPAN = 1,
/** The linked span is a parent of the current span. */
PARENT_LINKED_SPAN = 2,
}
/** Interface for Span */
export interface Span {
/** The Span ID of this span */
readonly id: string;
/** If the parent span is in another process. */
remoteParent: boolean;
/** The span ID of this span's parent. If it's a root span, must be empty */
parentSpanId: string;
/** The resource name of the span */
name: string;
/** Kind of span. */
kind: SpanKind;
/** An object to log information to */
logger: loggerTypes.Logger;
/** A final status for this span */
status: Status;
/** A set of attributes, each in the format [KEY]:[VALUE] */
attributes: Attributes;
/** A text annotation with a set of attributes. */
annotations: Annotation[];
/** An event describing a message sent/received between Spans. */
messageEvents: MessageEvent[];
/** Pointers from the current span to another span */
links: Link[];
/** Recursively gets the descendant spans. */
allDescendants(): Span[];
/** The list of immediate child spans. */
spans: Span[];
/** The number of direct children */
numberOfChildren: number;
/** Trace id asscoiated with span. */
readonly traceId: string;
/** Trace state associated with span */
readonly traceState?: TraceState;
/** Indicates if span was started. */
readonly started: boolean;
/** Indicates if span was ended. */
readonly ended: boolean;
/**
* Gives a timestap that indicates the span's start time in RFC3339 UTC
* "Zulu" format.
*/
readonly startTime: Date;
/**
* Gives a timestap that indicates the span's end time in RFC3339 UTC
* "Zulu" format.
*/
readonly endTime: Date;
/**
* Gives a timestap that indicates the span's duration in RFC3339 UTC
* "Zulu" format.
*/
readonly duration: number;
/** Gives the TraceContext of the span. */
readonly spanContext: SpanContext;
/** Trace Parameters */
activeTraceParams: configTypes.TraceParams;
/** The number of dropped attributes. */
droppedAttributesCount: number;
/** The number of dropped links. */
droppedLinksCount: number;
/** The number of dropped annotations. */
droppedAnnotationsCount: number;
/** The number of dropped message events. */
droppedMessageEventsCount: number;
/**
* Adds an atribute to the span.
* @param key Describes the value added.
* @param value The result of an operation.
*/
addAttribute(key: string, value: string | number | boolean | object): void;
/**
* Adds an annotation to the span.
* @param description Describes the event.
* @param attributes A set of attributes on the annotation.
* @param timestamp A timestamp for this event.
*/
addAnnotation(
description: string,
attributes?: Attributes,
timestamp?: number
): void;
/**
* Adds a link to the span.
* @param traceId The trace ID for a trace within a project.
* @param spanId The span ID for a span within a trace.
* @param type The relationship of the current span relative to the linked.
* @param attributes A set of attributes on the link.
*/
addLink(
traceId: string,
spanId: string,
type: LinkType,
attributes?: Attributes
): void;
/**
* Adds a message event to the span.
* @param type The type of message event.
* @param id An identifier for the message event.
* @param timestamp A timestamp for this event.
* @param uncompressedSize The number of uncompressed bytes sent or received.
* @param compressedSize The number of compressed bytes sent or received. If
* zero or undefined, assumed to be the same size as uncompressed.
*/
addMessageEvent(
type: MessageEventType,
id: number,
timestamp?: number,
uncompressedSize?: number,
compressedSize?: number
): void;
/**
* Sets a status to the span.
* @param code The canonical status code.
* @param message optional A developer-facing error message.
*/
setStatus(code: CanonicalCode, message?: string): void;
/** Starts a span. */
start(): void;
/** Ends a span and all of its children, recursively. */
end(): void;
/** Forces to end a span. */
truncate(): void;
/** Starts a new Span instance as a child of this instance */
startChildSpan(options?: SpanOptions): Span;
}
/** Interface for TracerBase */
export interface TracerBase extends SpanEventListener {
/** A sampler that will decide if the span will be sampled or not */
sampler: samplerTypes.Sampler;
/** A configuration for starting the tracer */
logger: loggerTypes.Logger;
/** A configuration object for trace parameters */
activeTraceParams: configTypes.TraceParams;
/** A propagation instance */
readonly propagation: Propagation;
/** Get the eventListeners from tracer instance */
readonly eventListeners: SpanEventListener[];
/** Get the active status from tracer instance */
readonly active: boolean;
/**
* Start a tracer instance
* @param config Configuration for tracer instace
* @returns A tracer instance started
*/
start(config: configTypes.TracerConfig): this;
/** Stop the tracer instance */
stop(): this;
/**
* Start a new RootSpan to currentRootSpan
* @param options Options for tracer instance
* @param fn Callback function
* @returns The callback return
*/
startRootSpan<T>(options: TraceOptions, fn: (root: Span) => T): T;
/**
* Register a OnEndSpanEventListener on the tracer instance
* @param listener An OnEndSpanEventListener instance
*/
registerSpanEventListener(listener: SpanEventListener): void;
/**
* Unregisters an end span event listener.
* @param listener The listener to unregister.
*/
unregisterSpanEventListener(listener: SpanEventListener): void;
/**
* Start a new Span instance to the currentRootSpan
* @param [options] A TraceOptions object to start a root span.
* @returns The new Span instance started
*/
startChildSpan(options?: SpanOptions): Span;
/** Sets the current root span. */
setCurrentRootSpan(root: Span): void;
}
/** Interface for Tracer */
export interface Tracer extends TracerBase {
/** Get and set the currentRootSpan to tracer instance */
currentRootSpan: Span;
/** Clear the currentRootSpan from tracer instance */
clearCurrentTrace(): void;
/**
* Binds the trace context to the given function.
* This is necessary in order to create child spans correctly in functions
* that are called asynchronously (for example, in a network response
* handler).
* @param fn A function to which to bind the trace context.
*/
wrap<T>(fn: Func<T>): Func<T>;
/**
* Binds the trace context to the given event emitter.
* This is necessary in order to create child spans correctly in event
* handlers.
* @param emitter An event emitter whose handlers should have
* the trace context binded to them.
*/
wrapEmitter(emitter: NodeJsEventEmitter): void;
} | the_stack |
* @module IModelHost
*/
import * as os from "os";
import * as path from "path";
import * as semver from "semver";
import { IModelJsNative, NativeLibrary } from "@bentley/imodeljs-native";
import { TelemetryManager } from "@itwin/core-telemetry";
import { AccessToken, assert, BeEvent, Guid, GuidString, IModelStatus, Logger, LogLevel, Mutable, ProcessDetector } from "@itwin/core-bentley";
import { AuthorizationClient, BentleyStatus, IModelError, LocalDirName, SessionProps } from "@itwin/core-common";
import { BackendHubAccess } from "./BackendHubAccess";
import { BackendLoggerCategory } from "./BackendLoggerCategory";
import { BisCoreSchema } from "./BisCoreSchema";
import { BriefcaseManager } from "./BriefcaseManager";
import { AzureBlobStorage, AzureBlobStorageCredentials, CloudStorageService, CloudStorageTileUploader } from "./CloudStorageBackend";
import { FunctionalSchema } from "./domains/FunctionalSchema";
import { GenericSchema } from "./domains/GenericSchema";
import { IModelJsFs } from "./IModelJsFs";
import { DevToolsRpcImpl } from "./rpc-impl/DevToolsRpcImpl";
import { IModelReadRpcImpl } from "./rpc-impl/IModelReadRpcImpl";
import { IModelTileRpcImpl } from "./rpc-impl/IModelTileRpcImpl";
import { SnapshotIModelRpcImpl } from "./rpc-impl/SnapshotIModelRpcImpl";
import { WipRpcImpl } from "./rpc-impl/WipRpcImpl";
import { initializeRpcBackend } from "./RpcBackend";
import { ITwinWorkspace, Workspace, WorkspaceOpts } from "./workspace/Workspace";
import { BaseSettings, SettingDictionary, SettingsPriority } from "./workspace/Settings";
import { SettingsSpecRegistry } from "./workspace/SettingsSpecRegistry";
const loggerCategory = BackendLoggerCategory.IModelHost;
// cspell:ignore nodereport fatalerror apicall alicloud rpcs
/** @alpha */
export interface CrashReportingConfigNameValuePair {
name: string;
value: string;
}
/** Configuration of the crash-reporting system.
* @alpha
*/
export interface CrashReportingConfig {
/** The directory to which *.dmp and/or iModelJsNativeCrash*.properties.txt files are written. This directory will be created if it does not already exist. */
crashDir: string;
/** max # .dmp files that may exist in crashDir. The default is 50. */
maxDumpsInDir?: number;
/** Enable crash-dumps? If so, .dmp and .properties.txt files will be generated and written to crashDir in the event of an unhandled native-code exception. If not, only .properties.txt files will be written. The default is false. */
enableCrashDumps?: boolean;
/** If enableCrashDumps is true, do you want a full-memory dump? Defaults to false. */
wantFullMemoryDumps?: boolean;
/** Enable node-report? If so, node-report files will be generated in the event of an unhandled exception or fatal error and written to crashDir. The default is false. */
enableNodeReport?: boolean;
/** Additional name, value pairs to write to iModelJsNativeCrash*.properties.txt file in the event of a crash. */
params?: CrashReportingConfigNameValuePair[];
/** Run this .js file to process .dmp and node-report files in the event of a crash.
* This script will be executed with a single command-line parameter: the name of the dump or node-report file.
* In the case of a dump file, there will be a second file with the same basename and the extension ".properties.txt".
* Since it runs in a separate process, this script will have no access to the Javascript
* context of the exiting backend. No default.
*/
dumpProcessorScriptFileName?: string;
/** Upload crash dump and node-reports to Bentley's crash-reporting service? Defaults to false */
uploadToBentley?: boolean;
}
/** Configuration of core-backend.
* @public
*/
export class IModelHostConfiguration {
/**
* Root of the directory holding all the files that iTwin.js caches
* - If not specified at startup a platform specific default is used -
* - Windows: $(HOMEDIR)/AppData/Local/iModelJs/
* - Mac/iOS: $(HOMEDIR)/Library/Caches/iModelJs/
* - Linux: $(HOMEDIR)/.cache/iModelJs/
* where $(HOMEDIR) is documented [here](https://nodejs.org/api/os.html#os_os_homedir)
* - if specified, ensure it is set to a folder with read/write access.
* - Sub-folders within this folder organize various caches -
* - bc/ -> Briefcases
* - appSettings/ -> Offline application settings (only relevant in native applications)
* - etc.
* @see [[IModelHost.cacheDir]] for the value it's set to after startup
*/
public cacheDir?: LocalDirName;
/** Options for creating the [[Workspace]]
* @beta
*/
public workspace?: WorkspaceOpts;
/** The directory where the app's assets are found. */
public appAssetsDir?: LocalDirName;
/** The kind of iModel hub server to use.
* @beta
*/
public hubAccess?: BackendHubAccess;
/** The Azure blob storage credentials to use for the tile cache service. If omitted and no external service implementation is provided, a local cache will be used.
* @beta
*/
public tileCacheAzureCredentials?: AzureBlobStorageCredentials;
/**
* @beta
* @note A reference implementation is set for [[AzureBlobStorage]] if [[tileCacheAzureCredentials]] property is set. To supply a different implementation for any service provider (such as AWS),
* set this property with a custom [[CloudStorageService]].
*/
public tileCacheService?: CloudStorageService;
/** Whether to restrict tile cache URLs by client IP address (if available).
* @beta
*/
public restrictTileUrlsByClientIp?: boolean;
/** Whether to compress cached tiles.
* Defaults to `true`.
*/
public compressCachedTiles?: boolean;
/** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileTreeProps]($common) should wait before returning a "pending" status.
* @internal
*/
public tileTreeRequestTimeout = IModelHostConfiguration.defaultTileRequestTimeout;
/** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileContent]($common) should wait before returning a "pending" status.
* @internal
*/
public tileContentRequestTimeout = IModelHostConfiguration.defaultTileRequestTimeout;
/** The default time, in milliseconds, used for [[tileTreeRequestTimeout]] and [[tileContentRequestTimeout]]. To change this, override one or both of those properties.
* @internal
*/
public static defaultTileRequestTimeout = 20 * 1000;
/** The default time, in seconds, used for [[logTileLoadTimeThreshold]]. To change this, override that property.
* @internal
*/
public static defaultLogTileLoadTimeThreshold = 40;
/** The backend will log when a tile took longer to load than this threshold in seconds.
* @internal
*/
public logTileLoadTimeThreshold: number = IModelHostConfiguration.defaultLogTileLoadTimeThreshold;
/** The default size, in bytes, used for [[logTileSizeThreshold]]. To change this, override that property.
* @internal
*/
public static defaultLogTileSizeThreshold = 20 * 1000000;
/** The backend will log when a tile is loaded with a size in bytes above this threshold.
* @internal
*/
public logTileSizeThreshold: number = IModelHostConfiguration.defaultLogTileSizeThreshold;
/** Crash-reporting configuration
* @alpha
*/
public crashReportingConfig?: CrashReportingConfig;
/** The AuthorizationClient used to get accessTokens
* @beta
*/
public authorizationClient?: AuthorizationClient;
}
/**
* Settings for the application workspace.
* @note this includes the default dictionary from the SettingsSpecRegistry
*/
class ApplicationSettings extends BaseSettings {
private _remove?: VoidFunction;
protected override verifyPriority(priority: SettingsPriority) {
if (priority >= SettingsPriority.iModel) // iModel settings may not appear in ApplicationSettings
throw new Error("Use IModelSettings");
}
private updateDefaults() {
const defaults: SettingDictionary = {};
for (const [specName, val] of SettingsSpecRegistry.allSpecs) {
if (val.default)
defaults[specName] = val.default;
}
this.addDictionary("_default_", 0, defaults);
}
public constructor() {
super();
this._remove = SettingsSpecRegistry.onSpecsChanged.addListener(() => this.updateDefaults());
this.updateDefaults();
}
public override close() {
if (this._remove) {
this._remove();
this._remove = undefined;
}
}
}
/** IModelHost initializes ($backend) and captures its configuration. A backend must call [[IModelHost.startup]] before using any backend classes.
* See [the learning article]($docs/learning/backend/IModelHost.md)
* @public
*/
export class IModelHost {
private constructor() { }
public static authorizationClient?: AuthorizationClient;
/** @alpha */
public static readonly telemetry = new TelemetryManager();
public static backendVersion = "";
private static _cacheDir = "";
private static _appWorkspace?: Workspace;
private static _platform?: typeof IModelJsNative;
/** @internal */
public static get platform(): typeof IModelJsNative {
if (this._platform === undefined)
throw new Error("IModelHost.startup must be called first");
return this._platform;
}
public static configuration?: IModelHostConfiguration;
/** Event raised just after the backend IModelHost was started */
public static readonly onAfterStartup = new BeEvent<() => void>();
/** Event raised just before the backend IModelHost is to be shut down */
public static readonly onBeforeShutdown = new BeEvent<() => void>();
/** @internal */
public static readonly session: Mutable<SessionProps> = { applicationId: "2686", applicationVersion: "1.0.0", sessionId: "" };
/** A uniqueId for this session */
public static get sessionId() { return this.session.sessionId; }
public static set sessionId(id: GuidString) { this.session.sessionId = id; }
/** The Id of this application - needs to be set only if it is an agent application. The applicationId will otherwise originate at the frontend. */
public static get applicationId() { return this.session.applicationId; }
public static set applicationId(id: string) { this.session.applicationId = id; }
/** The version of this application - needs to be set if is an agent application. The applicationVersion will otherwise originate at the frontend. */
public static get applicationVersion() { return this.session.applicationVersion; }
public static set applicationVersion(version: string) { this.session.applicationVersion = version; }
/** Root directory holding files that iTwin.js caches */
public static get cacheDir(): LocalDirName { return this._cacheDir; }
/** The application [[Workspace]] for this `IModelHost`
* @note this `Workspace` only holds [[WorkspaceContainer]]s and [[Settings]] scoped to the currently loaded application(s).
* All organization, iTwin, and iModel based containers or settings must be accessed through [[IModelDb.workspace]] and
* attempting to add them to this Workspace will fail.
* @beta
*/
public static get appWorkspace(): Workspace { return this._appWorkspace!; } // eslint-disable-line @typescript-eslint/no-non-null-assertion
/** The optional [[FileNameResolver]] that resolves keys and partial file names for snapshot iModels. */
public static snapshotFileNameResolver?: FileNameResolver;
/** Get the current access token for this IModelHost, or a blank string if none is available.
* @note for web backends, this will *always* return a blank string because the backend itself has no token (but never needs one either.)
* For all IpcHosts, where this backend is servicing a single frontend, this will be the user's token. For ElectronHost, the backend
* obtains the token and forwards it to the frontend.
* @note accessTokens expire periodically and are automatically refreshed, if possible. Therefore tokens should not be saved, and the value
* returned by this method may change over time throughout the course of a session.
*/
public static async getAccessToken(): Promise<AccessToken> {
try {
return (await this.authorizationClient?.getAccessToken()) ?? "";
} catch (e) {
return "";
}
}
/** @internal */
public static flushLog() {
return this.platform.DgnDb.flushLog();
}
/** @internal */
public static loadNative(): void {
const platform = Platform.load();
this.registerPlatform(platform);
}
private static registerPlatform(platform: typeof IModelJsNative): void {
this._platform = platform;
if (undefined === platform)
return;
if (!ProcessDetector.isMobileAppBackend)
this.validateNativePlatformVersion();
platform.logger = Logger;
}
private static validateNativePlatformVersion(): void {
const requiredVersion = require("../../package.json").dependencies["@bentley/imodeljs-native"]; // eslint-disable-line @typescript-eslint/no-var-requires
const thisVersion = this.platform.version;
if (semver.satisfies(thisVersion, requiredVersion))
return;
if (IModelJsFs.existsSync(path.join(__dirname, "DevBuild.txt"))) {
console.log("Bypassing version checks for development build"); // eslint-disable-line no-console
return;
}
this._platform = undefined;
throw new IModelError(IModelStatus.BadRequest, `imodeljs-native version is (${thisVersion}). core-backend requires version (${requiredVersion})`);
}
/**
* @internal
* @note Use [[IModelHostConfiguration.tileCacheService]] to set the service provider.
*/
public static tileCacheService?: CloudStorageService;
/** @internal */
public static tileUploader?: CloudStorageTileUploader;
private static _hubAccess: BackendHubAccess;
/** @internal */
public static setHubAccess(hubAccess: BackendHubAccess) { this._hubAccess = hubAccess; }
/** Provides access to the IModelHub for this IModelHost
* @beta
* @note If [[IModelHostConfiguration.hubAccess]] was undefined when initializing this class, accessing this property will throw an error.
*/
public static get hubAccess(): BackendHubAccess {
// Strictly speaking, _hubAccess should be marked as possibly undefined since it's not needed for Snapshot iModels.
// However, a decision was made to not provide that type annotation so callers aren't forced to constantly check for
// something that's required in all other workflows.
// This check is here to provide a better error message when hubAccess is inadvertently undefined.
if (this._hubAccess === undefined)
throw new IModelError(IModelStatus.BadRequest, "IModelHost.hubAccess is undefined. Specify an implementation in your IModelHostConfiguration");
return this._hubAccess;
}
private static _isValid = false;
/** Returns true if IModelHost is started. */
public static get isValid() { return this._isValid; }
/** This method must be called before any iTwin.js services are used.
* @param configuration Host configuration data.
* Raises [[onAfterStartup]].
* @see [[shutdown]].
*/
public static async startup(configuration: IModelHostConfiguration = new IModelHostConfiguration()): Promise<void> {
if (this._isValid)
return; // we're already initialized
this._isValid = true;
if (IModelHost.sessionId === "")
IModelHost.sessionId = Guid.createValue();
this.authorizationClient = configuration.authorizationClient;
this.logStartup();
this.backendVersion = require("../../package.json").version; // eslint-disable-line @typescript-eslint/no-var-requires
initializeRpcBackend();
if (this._platform === undefined) {
try {
this.loadNative();
} catch (error) {
Logger.logError(loggerCategory, "Error registering/loading the native platform API", () => (configuration));
throw error;
}
}
if (configuration.crashReportingConfig && configuration.crashReportingConfig.crashDir && !ProcessDetector.isElectronAppBackend && !ProcessDetector.isMobileAppBackend) {
this.platform.setCrashReporting(configuration.crashReportingConfig);
Logger.logTrace(loggerCategory, "Configured crash reporting", () => ({
enableCrashDumps: configuration.crashReportingConfig?.enableCrashDumps,
wantFullMemoryDumps: configuration.crashReportingConfig?.wantFullMemoryDumps,
enableNodeReport: configuration.crashReportingConfig?.enableNodeReport,
uploadToBentley: configuration.crashReportingConfig?.uploadToBentley,
}));
if (configuration.crashReportingConfig.enableNodeReport) {
try {
// node-report reports on V8 fatal errors and unhandled exceptions/Promise rejections.
const nodereport = require("node-report/api"); // eslint-disable-line @typescript-eslint/no-var-requires
nodereport.setEvents("exception+fatalerror+apicall");
nodereport.setDirectory(configuration.crashReportingConfig.crashDir);
nodereport.setVerbose("yes");
Logger.logTrace(loggerCategory, "Configured native crash reporting (node-report)");
} catch (err) {
Logger.logWarning(loggerCategory, "node-report is not installed.");
}
}
}
this.setupHostDirs(configuration);
this._appWorkspace = new ITwinWorkspace(new ApplicationSettings(), configuration.workspace);
BriefcaseManager.initialize(this._briefcaseCacheDir);
[
IModelReadRpcImpl,
IModelTileRpcImpl,
SnapshotIModelRpcImpl,
WipRpcImpl,
DevToolsRpcImpl,
].forEach((rpc) => rpc.register()); // register all of the RPC implementations
[
BisCoreSchema,
GenericSchema,
FunctionalSchema,
].forEach((schema) => schema.registerSchema()); // register all of the schemas
if (undefined !== configuration.hubAccess)
IModelHost._hubAccess = configuration.hubAccess;
IModelHost.configuration = configuration;
IModelHost.setupTileCache();
this.platform.setUseTileCache(IModelHost.tileCacheService ? false : true);
process.once("beforeExit", IModelHost.shutdown);
IModelHost.onAfterStartup.raiseEvent();
}
private static _briefcaseCacheDir: LocalDirName;
private static logStartup() {
if (!Logger.isEnabled(loggerCategory, LogLevel.Trace))
return;
// Extract the iModel details from environment - note this is very specific to Bentley hosted backends, but is quite useful for tracing
let startupInfo: any = {};
const serviceName = process.env.FABRIC_SERVICE_NAME;
if (serviceName) {
// e.g., fabric:/iModelWebViewer3.0/iModelJSGuest/1/08daaeb3-b56f-480b-9051-7efc834d18ae/512d971d-b641-4735-bb1c-c07ab3e44ce7/c1315fcce125ca40b2d405bb7809214daf8b4c85
const serviceNameComponents = serviceName.split("/");
if (serviceNameComponents.length === 7) {
startupInfo = {
...startupInfo,
iTwinId: serviceNameComponents[4],
iModelId: serviceNameComponents[5],
changesetId: serviceNameComponents[6],
};
}
}
Logger.logTrace(loggerCategory, "IModelHost.startup", () => startupInfo);
}
private static setupHostDirs(configuration: IModelHostConfiguration) {
const setupDir = (dir: LocalDirName) => {
dir = path.normalize(dir);
IModelJsFs.recursiveMkDirSync(dir);
return dir;
};
this._cacheDir = setupDir(configuration.cacheDir ?? NativeLibrary.defaultCacheDir);
this._briefcaseCacheDir = path.join(this._cacheDir, "imodels");
}
/** This method must be called when an iTwin.js host is shut down. Raises [[onBeforeShutdown]] */
public static async shutdown(): Promise<void> {
// NB: This method is set as a node listener where `this` is unbound
if (!IModelHost._isValid)
return;
IModelHost._isValid = false;
IModelHost.onBeforeShutdown.raiseEvent();
IModelHost.configuration = undefined;
IModelHost.tileCacheService = undefined;
IModelHost.tileUploader = undefined;
IModelHost.appWorkspace.close();
IModelHost._appWorkspace = undefined;
process.removeListener("beforeExit", IModelHost.shutdown);
}
/**
* Add or update a property that should be included in a crash report.
* @param name The name of the property
* @param value The value of the property
* @alpha
*/
public static setCrashReportProperty(name: string, value: string): void {
assert(undefined !== this._platform);
this._platform.setCrashReportProperty(name, value);
}
/**
* Remove a previously defined property so that will not be included in a crash report.
* @param name The name of the property
* @alpha
*/
public static removeCrashReportProperty(name: string): void {
assert(undefined !== this._platform);
this._platform.setCrashReportProperty(name, undefined);
}
/**
* Get all properties that will be included in a crash report.
* @alpha
*/
public static getCrashReportProperties(): CrashReportingConfigNameValuePair[] {
assert(undefined !== this._platform);
return this._platform.getCrashReportProperties();
}
/** The directory where application assets may be found */
public static get appAssetsDir(): string | undefined { return undefined !== IModelHost.configuration ? IModelHost.configuration.appAssetsDir : undefined; }
/** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileTreeProps]($common) should wait before returning a "pending" status.
* @internal
*/
public static get tileTreeRequestTimeout(): number {
return undefined !== IModelHost.configuration ? IModelHost.configuration.tileTreeRequestTimeout : IModelHostConfiguration.defaultTileRequestTimeout;
}
/** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileContent]($common) should wait before returning a "pending" status.
* @internal
*/
public static get tileContentRequestTimeout(): number {
return undefined !== IModelHost.configuration ? IModelHost.configuration.tileContentRequestTimeout : IModelHostConfiguration.defaultTileRequestTimeout;
}
/** The backend will log when a tile took longer to load than this threshold in seconds. */
public static get logTileLoadTimeThreshold(): number { return undefined !== IModelHost.configuration ? IModelHost.configuration.logTileLoadTimeThreshold : IModelHostConfiguration.defaultLogTileLoadTimeThreshold; }
/** The backend will log when a tile is loaded with a size in bytes above this threshold. */
public static get logTileSizeThreshold(): number { return undefined !== IModelHost.configuration ? IModelHost.configuration.logTileSizeThreshold : IModelHostConfiguration.defaultLogTileSizeThreshold; }
/** Whether external tile caching is active.
* @internal
*/
public static get usingExternalTileCache(): boolean {
return undefined !== IModelHost.tileCacheService;
}
/** Whether to restrict tile cache URLs by client IP address.
* @internal
*/
public static get restrictTileUrlsByClientIp(): boolean { return undefined !== IModelHost.configuration && (IModelHost.configuration.restrictTileUrlsByClientIp ? true : false); }
/** Whether to compress cached tiles.
* @internal
*/
public static get compressCachedTiles(): boolean { return false !== IModelHost.configuration?.compressCachedTiles; }
private static setupTileCache() {
assert(undefined !== IModelHost.configuration);
const config = IModelHost.configuration;
const service = config.tileCacheService;
const credentials = config.tileCacheAzureCredentials;
if (!service && !credentials)
return;
IModelHost.tileUploader = new CloudStorageTileUploader();
if (credentials && !service) {
IModelHost.tileCacheService = new AzureBlobStorage(credentials);
} else if (!credentials && service) {
IModelHost.tileCacheService = service;
} else {
throw new IModelError(BentleyStatus.ERROR, "Cannot use both Azure and custom cloud storage providers for tile cache.");
}
}
}
/** Information about the platform on which the app is running. Also see [[KnownLocations]] and [[IModelJsFs]].
* @public
*/
export class Platform {
/** Get the name of the platform. */
public static get platformName(): "win32" | "linux" | "darwin" | "ios" | "android" | "uwp" {
return process.platform as any;
}
/** @internal */
public static load(): typeof IModelJsNative {
return ProcessDetector.isMobileAppBackend ? (process as any)._linkedBinding("iModelJsNative") : NativeLibrary.load();
}
}
/** Well known directories that may be used by the application. Also see [[Platform]]
* @public
*/
export class KnownLocations {
/** The directory where the imodeljs-native assets are stored. */
public static get nativeAssetsDir(): string { return IModelHost.platform.DgnDb.getAssetsDir(); }
/** The directory where the core-backend assets are stored. */
public static get packageAssetsDir(): string {
return path.join(__dirname, "assets");
}
/** The temporary directory. */
public static get tmpdir(): string {
return os.tmpdir();
}
}
/** Extend this class to provide custom file name resolution behavior.
* @note Only `tryResolveKey` and/or `tryResolveFileName` need to be overridden as the implementations of `resolveKey` and `resolveFileName` work for most purposes.
* @see [[IModelHost.snapshotFileNameResolver]]
* @public
*/
export abstract class FileNameResolver {
/** Resolve a file name from the specified key.
* @param _fileKey The key that identifies the file name in a `Map` or other similar data structure.
* @returns The resolved file name or `undefined` if not found.
*/
public tryResolveKey(_fileKey: string): string | undefined { return undefined; }
/** Resolve a file name from the specified key.
* @param fileKey The key that identifies the file name in a `Map` or other similar data structure.
* @returns The resolved file name.
* @throws [[IModelError]] if not found.
*/
public resolveKey(fileKey: string): string {
const resolvedFileName: string | undefined = this.tryResolveKey(fileKey);
if (undefined === resolvedFileName) {
throw new IModelError(IModelStatus.NotFound, `${fileKey} not resolved`);
}
return resolvedFileName;
}
/** Resolve the input file name, which may be a partial name, into a full path file name.
* @param inFileName The partial file name.
* @returns The resolved full path file name or `undefined` if not found.
*/
public tryResolveFileName(inFileName: string): string | undefined { return inFileName; }
/** Resolve the input file name, which may be a partial name, into a full path file name.
* @param inFileName The partial file name.
* @returns The resolved full path file name.
* @throws [[IModelError]] if not found.
*/
public resolveFileName(inFileName: string): string {
const resolvedFileName: string | undefined = this.tryResolveFileName(inFileName);
if (undefined === resolvedFileName) {
throw new IModelError(IModelStatus.NotFound, `${inFileName} not resolved`);
}
return resolvedFileName;
}
} | the_stack |
import { toArray } from '@lumino/algorithm';
import { IChangedArgs } from '@jupyterlab/coreutils';
import {
CellModel,
CodeCellModel,
MarkdownCellModel,
RawCellModel
} from '@jupyterlab/cells';
import * as nbformat from '@jupyterlab/nbformat';
import { OutputAreaModel } from '@jupyterlab/outputarea';
import { NBTestUtils } from '@jupyterlab/testutils';
import { JSONObject } from '@lumino/coreutils';
class TestModel extends CellModel {
get type(): 'raw' {
return 'raw';
}
}
describe('cells/model', () => {
describe('CellModel', () => {
describe('#constructor()', () => {
it('should create a cell model', () => {
const model = new CellModel({});
expect(model).toBeInstanceOf(CellModel);
});
it('should accept a base cell argument', () => {
const cell: nbformat.IRawCell = {
cell_type: 'raw',
source: 'foo',
metadata: { trusted: false }
};
const model = new CellModel({ cell });
expect(model).toBeInstanceOf(CellModel);
expect(model.value.text).toBe(cell.source);
});
it('should accept a base cell argument with a multiline source', () => {
const cell: nbformat.IRawCell = {
cell_type: 'raw',
source: ['foo\n', 'bar\n', 'baz'],
metadata: { trusted: false },
id: 'cell_id'
};
const model = new CellModel({ cell });
expect(model).toBeInstanceOf(CellModel);
expect(model.value.text).toBe((cell.source as string[]).join(''));
});
it('should use the id argument', () => {
const cell: nbformat.IRawCell = {
cell_type: 'raw',
source: ['foo\n', 'bar\n', 'baz'],
metadata: { trusted: false },
id: 'cell_id'
};
const model = new CellModel({ cell, id: 'my_id' });
expect(model).toBeInstanceOf(CellModel);
expect(model.id).toBe('my_id');
});
it('should use the cell id if an id is not supplied', () => {
const cell: nbformat.IRawCell = {
cell_type: 'raw',
source: ['foo\n', 'bar\n', 'baz'],
metadata: { trusted: false },
id: 'cell_id'
};
const model = new CellModel({ cell });
expect(model).toBeInstanceOf(CellModel);
expect(model.id).toBe('cell_id');
});
it('should generate an id if an id or cell id is not supplied', () => {
const cell = {
cell_type: 'raw',
source: ['foo\n', 'bar\n', 'baz'],
metadata: { trusted: false }
};
const model = new CellModel({ cell });
expect(model).toBeInstanceOf(CellModel);
expect(model.id.length).toBeGreaterThan(0);
});
});
describe('#contentChanged', () => {
it('should signal when model content has changed', () => {
const model = new CellModel({});
let called = false;
model.contentChanged.connect(() => {
called = true;
});
expect(called).toBe(false);
model.value.text = 'foo';
expect(called).toBe(true);
});
});
describe('#stateChanged', () => {
it('should signal when model state has changed', () => {
const model = new CodeCellModel({});
let called = false;
const listener = (sender: any, args: IChangedArgs<any>) => {
if (args.name == 'executionCount') {
// eslint-disable-next-line jest/no-conditional-expect
expect(args.newValue).toBe(1);
called = true;
}
};
model.stateChanged.connect(listener);
model.executionCount = 1;
expect(called).toBe(true);
});
it('should not signal when model state has not changed', () => {
const model = new CodeCellModel({});
let called = 0;
model.stateChanged.connect((model, args) => {
if (args.name == 'executionCount') {
called++;
}
});
expect(called).toBe(0);
model.executionCount = 1;
expect(called).toBe(1);
model.executionCount = 1;
expect(called).toBe(1);
});
});
describe('#trusted', () => {
it('should be the trusted state of the cell', () => {
const model = new CodeCellModel({});
expect(model.trusted).toBe(false);
model.trusted = true;
expect(model.trusted).toBe(true);
const other = new CodeCellModel({ cell: model.toJSON() });
expect(other.trusted).toBe(true);
});
it('should update the trusted state of the output models', () => {
const model = new CodeCellModel({});
model.outputs.add(NBTestUtils.DEFAULT_OUTPUTS[0]);
expect(model.outputs.get(0).trusted).toBe(false);
model.trusted = true;
expect(model.outputs.get(0).trusted).toBe(true);
});
});
describe('#metadataChanged', () => {
it('should signal when model metadata has changed', () => {
const model = new TestModel({});
const listener = (sender: any, args: any) => {
value = args.newValue;
};
let value = '';
model.metadata.changed.connect(listener);
expect(Object.keys(value)).toHaveLength(0);
model.metadata.set('foo', 'bar');
expect(value).toBe('bar');
});
it('should not signal when model metadata has not changed', () => {
const model = new TestModel({});
let called = 0;
model.metadata.changed.connect(() => {
called++;
});
expect(called).toBe(0);
model.metadata.set('foo', 'bar');
expect(called).toBe(1);
model.metadata.set('foo', 'bar');
expect(called).toBe(1);
});
});
describe('#source', () => {
it('should default to an empty string', () => {
const model = new CellModel({});
expect(model.value.text).toHaveLength(0);
});
it('should be settable', () => {
const model = new CellModel({});
expect(model.value.text).toHaveLength(0);
model.value.text = 'foo';
expect(model.value.text).toBe('foo');
});
});
describe('#isDisposed', () => {
it('should be false by default', () => {
const model = new CellModel({});
expect(model.isDisposed).toBe(false);
});
it('should be true after model is disposed', () => {
const model = new CellModel({});
model.dispose();
expect(model.isDisposed).toBe(true);
});
});
describe('#dispose()', () => {
it('should dispose of the resources held by the model', () => {
const model = new TestModel({});
model.dispose();
expect(model.isDisposed).toBe(true);
});
it('should be safe to call multiple times', () => {
const model = new CellModel({});
model.dispose();
model.dispose();
expect(model.isDisposed).toBe(true);
});
});
describe('#toJSON()', () => {
it('should return a base cell encapsulation of the model value', () => {
const cell: nbformat.IRawCell = {
cell_type: 'raw',
source: 'foo',
metadata: { trusted: false }
};
const model = new TestModel({ cell });
expect(model.toJSON()).not.toBe(cell);
expect(model.toJSON()).toEqual(cell);
});
it('should always return a string source', () => {
const cell: nbformat.IRawCell = {
cell_type: 'raw',
source: ['foo\n', 'bar\n', 'baz'],
metadata: { trusted: false }
};
const model = new TestModel({ cell });
cell.source = (cell.source as string[]).join('');
expect(model.toJSON()).not.toBe(cell);
expect(model.toJSON()).toEqual(cell);
});
});
describe('#metadata', () => {
it('should handle a metadata for the cell', () => {
const model = new CellModel({});
expect(model.metadata.get('foo')).toBeUndefined();
model.metadata.set('foo', 1);
expect(model.metadata.get('foo')).toBe(1);
});
it('should get a list of user metadata keys', () => {
const model = new CellModel({});
expect(toArray(model.metadata.keys())).toHaveLength(0);
model.metadata.set('foo', 1);
expect(model.metadata.keys()).toEqual(['foo']);
});
it('should trigger changed signal', () => {
const model = new CellModel({});
let called = false;
model.metadata.changed.connect(() => {
called = true;
});
model.metadata.set('foo', 1);
expect(called).toBe(true);
});
});
});
describe('RawCellModel', () => {
describe('#type', () => {
it('should be set with type "raw"', () => {
const model = new RawCellModel({});
expect(model.type).toBe('raw');
});
});
describe('#toJSON()', () => {
it('should return a raw cell encapsulation of the model value', () => {
const cell: nbformat.IRawCell = {
cell_type: 'raw',
source: 'foo',
metadata: {},
id: 'cell_id'
};
const model = new RawCellModel({ cell });
const serialized = model.toJSON();
expect(serialized).not.toBe(cell);
expect(serialized).toEqual(cell);
});
});
});
describe('MarkdownCellModel', () => {
describe('#type', () => {
it('should be set with type "markdown"', () => {
const model = new MarkdownCellModel({});
expect(model.type).toBe('markdown');
});
});
describe('#toJSON()', () => {
it('should return a markdown cell encapsulation of the model value', () => {
const cell: nbformat.IMarkdownCell = {
cell_type: 'markdown',
source: 'foo',
metadata: {},
id: 'cell_id'
};
const model = new MarkdownCellModel({ cell });
const serialized = model.toJSON();
expect(serialized).not.toBe(cell);
expect(serialized).toEqual(cell);
});
});
});
describe('CodeCellModel', () => {
describe('#constructor()', () => {
it('should create a code cell model', () => {
const model = new CodeCellModel({});
expect(model).toBeInstanceOf(CodeCellModel);
});
it('should accept a code cell argument', () => {
const cell: nbformat.ICodeCell = {
cell_type: 'code',
execution_count: 1,
outputs: [
{
output_type: 'display_data',
data: { 'text/plain': 'foo' },
metadata: {}
} as nbformat.IDisplayData
],
source: 'foo',
metadata: { trusted: false }
};
const model = new CodeCellModel({ cell });
expect(model).toBeInstanceOf(CodeCellModel);
expect(model.value.text).toBe(cell.source);
});
it('should connect the outputs changes to content change signal', () => {
const data = {
output_type: 'display_data',
data: { 'text/plain': 'foo' },
metadata: {}
} as nbformat.IDisplayData;
const model = new CodeCellModel({});
let called = false;
model.contentChanged.connect(() => {
called = true;
});
expect(called).toBe(false);
model.outputs.add(data);
expect(called).toBe(true);
});
it('should sync collapsed and jupyter.outputs_hidden metadata on construction', () => {
let model: CodeCellModel;
let jupyter: JSONObject | undefined;
// Setting `collapsed` works
model = new CodeCellModel({
cell: {
cell_type: 'code',
source: '',
metadata: { collapsed: true }
}
});
expect(model.metadata.get('collapsed')).toBe(true);
jupyter = model.metadata.get('jupyter') as JSONObject;
expect(jupyter.outputs_hidden).toBe(true);
// Setting `jupyter.outputs_hidden` works
model = new CodeCellModel({
cell: {
cell_type: 'code',
source: '',
metadata: { jupyter: { outputs_hidden: true } }
}
});
expect(model.metadata.get('collapsed')).toBe(true);
jupyter = model.metadata.get('jupyter') as JSONObject;
expect(jupyter.outputs_hidden).toBe(true);
// `collapsed` takes precedence
model = new CodeCellModel({
cell: {
cell_type: 'code',
source: '',
metadata: { collapsed: false, jupyter: { outputs_hidden: true } }
}
});
expect(model.metadata.get('collapsed')).toBe(false);
jupyter = model.metadata.get('jupyter') as JSONObject;
expect(jupyter.outputs_hidden).toBe(false);
});
});
describe('#type', () => {
it('should be set with type "code"', () => {
const model = new CodeCellModel({});
expect(model.type).toBe('code');
});
});
describe('#executionCount', () => {
it('should show the execution count of the cell', () => {
const cell: nbformat.ICodeCell = {
cell_type: 'code',
execution_count: 1,
outputs: [],
source: 'foo',
metadata: { trusted: false }
};
const model = new CodeCellModel({ cell });
expect(model.executionCount).toBe(1);
});
it('should be settable', () => {
const model = new CodeCellModel({});
expect(model.executionCount).toBeNull();
model.executionCount = 1;
expect(model.executionCount).toBe(1);
});
it('should emit a state change signal when set', () => {
const model = new CodeCellModel({});
let called = false;
model.stateChanged.connect(() => {
called = true;
});
expect(model.executionCount).toBeNull();
expect(called).toBe(false);
model.executionCount = 1;
expect(model.executionCount).toBe(1);
expect(called).toBe(true);
});
it('should not signal when state has not changed', () => {
const model = new CodeCellModel({});
let called = 0;
model.stateChanged.connect((model, args) => {
if (args.name == 'executionCount') {
called++;
}
});
expect(model.executionCount).toBeNull();
expect(called).toBe(0);
model.executionCount = 1;
expect(model.executionCount).toBe(1);
model.executionCount = 1;
expect(called).toBe(1);
});
it('should set dirty flag and signal', () => {
const model = new CodeCellModel({});
let called = 0;
model.stateChanged.connect((model, args) => {
if (args.name == 'isDirty') {
called++;
}
});
expect(model.executionCount).toBeNull();
expect(model.isDirty).toBe(false);
expect(called).toBe(0);
model.executionCount = 1;
expect(model.isDirty).toBe(false);
expect(called).toBe(0);
model.value.text = 'foo';
expect(model.isDirty).toBe(true);
expect(called).toBe(1);
model.executionCount = 2;
expect(model.isDirty).toBe(false);
expect(called).toBe(2);
});
});
describe('#outputs', () => {
it('should be an output area model', () => {
const model = new CodeCellModel({});
expect(model.outputs).toBeInstanceOf(OutputAreaModel);
});
});
describe('#dispose()', () => {
it('should dispose of the resources held by the model', () => {
const model = new CodeCellModel({});
expect(model.outputs).toBeInstanceOf(OutputAreaModel);
model.dispose();
expect(model.isDisposed).toBe(true);
expect(model.outputs).toBeNull();
});
it('should be safe to call multiple times', () => {
const model = new CodeCellModel({});
model.dispose();
model.dispose();
expect(model.isDisposed).toBe(true);
});
});
describe('#toJSON()', () => {
it('should return a code cell encapsulation of the model value', () => {
const cell: nbformat.ICodeCell = {
cell_type: 'code',
execution_count: 1,
outputs: [
{
output_type: 'display_data',
data: {
'text/plain': 'foo',
'application/json': { bar: 1 }
},
metadata: {}
} as nbformat.IDisplayData
],
source: 'foo',
metadata: { trusted: false },
id: 'cell_id'
};
const model = new CodeCellModel({ cell });
const serialized = model.toJSON();
expect(serialized).not.toBe(cell);
expect(serialized).toEqual(cell);
const output = serialized.outputs[0] as any;
expect(output.data['application/json']['bar']).toBe(1);
});
});
describe('.metadata', () => {
it('should sync collapsed and jupyter.outputs_hidden metadata when changed', () => {
const metadata = new CodeCellModel({}).metadata;
expect(metadata.get('collapsed')).toBeUndefined();
expect(metadata.get('jupyter')).toBeUndefined();
// Setting collapsed sets jupyter.outputs_hidden
metadata.set('collapsed', true);
expect(metadata.get('collapsed')).toBe(true);
expect(metadata.get('jupyter')).toEqual({
outputs_hidden: true
});
metadata.set('collapsed', false);
expect(metadata.get('collapsed')).toBe(false);
expect(metadata.get('jupyter')).toEqual({
outputs_hidden: false
});
metadata.delete('collapsed');
expect(metadata.get('collapsed')).toBeUndefined();
expect(metadata.get('jupyter')).toBeUndefined();
// Setting jupyter.outputs_hidden sets collapsed
metadata.set('jupyter', { outputs_hidden: true });
expect(metadata.get('collapsed')).toBe(true);
expect(metadata.get('jupyter')).toEqual({
outputs_hidden: true
});
metadata.set('jupyter', { outputs_hidden: false });
expect(metadata.get('collapsed')).toBe(false);
expect(metadata.get('jupyter')).toEqual({
outputs_hidden: false
});
metadata.delete('jupyter');
expect(metadata.get('collapsed')).toBeUndefined();
expect(metadata.get('jupyter')).toBeUndefined();
// Deleting jupyter.outputs_hidden preserves other jupyter fields
metadata.set('jupyter', { outputs_hidden: true, other: true });
expect(metadata.get('collapsed')).toBe(true);
expect(metadata.get('jupyter')).toEqual({
outputs_hidden: true,
other: true
});
metadata.set('jupyter', { other: true });
expect(metadata.get('collapsed')).toBeUndefined();
expect(metadata.get('jupyter')).toEqual({
other: true
});
// Deleting collapsed preserves other jupyter fields
metadata.set('jupyter', { outputs_hidden: true, other: true });
expect(metadata.get('collapsed')).toBe(true);
expect(metadata.get('jupyter')).toEqual({
outputs_hidden: true,
other: true
});
metadata.delete('collapsed');
expect(metadata.get('collapsed')).toBeUndefined();
expect(metadata.get('jupyter')).toEqual({
other: true
});
});
});
describe('.ContentFactory', () => {
describe('#constructor()', () => {
it('should create a new output area factory', () => {
const factory = new CodeCellModel.ContentFactory();
expect(factory).toBeInstanceOf(CodeCellModel.ContentFactory);
});
});
describe('#createOutputArea()', () => {
it('should create an output area model', () => {
const factory = new CodeCellModel.ContentFactory();
expect(factory.createOutputArea({ trusted: true })).toBeInstanceOf(
OutputAreaModel
);
});
});
});
describe('.defaultContentFactory', () => {
it('should be an ContentFactory', () => {
expect(CodeCellModel.defaultContentFactory).toBeInstanceOf(
CodeCellModel.ContentFactory
);
});
});
});
}); | the_stack |
import * as protos from '../../protos';
export function commonPrefix(strings: string[]): string {
if (strings.length === 0) {
return '';
}
let result = '';
while (result.length < strings[0].length) {
// try one more character
const next = result + strings[0][result.length];
if (strings.every(str => str.startsWith(next))) {
result = next;
} else {
break;
}
}
return result;
}
// Convert a string Duration, e.g. "600s", to a proper protobuf type since
// protobufjs does not support it at this moment.
export function duration(text: string): protos.google.protobuf.Duration {
const multipliers: {[suffix: string]: number} = {
s: 1,
m: 60,
h: 60 * 60,
d: 60 * 60 * 24,
};
const match = text.match(/^([\d.]+)([smhd])$/);
if (!match) {
throw new Error(`Cannot parse "${text}" into google.protobuf.Duration.`);
}
const float = Number(match[1]);
const suffix = match[2];
const multiplier = multipliers[suffix];
const seconds = float * multiplier;
const floor = Math.floor(seconds);
const frac = seconds - floor;
const result = protos.google.protobuf.Duration.fromObject({
seconds: floor,
nanos: frac * 1e9,
});
return result;
}
// Convert a Duration to (possibly fractional) seconds.
export function seconds(duration: protos.google.protobuf.IDuration): number {
return Number(duration.seconds || 0) + Number(duration.nanos || 0) * 1e-9;
}
// Convert a Duration to (possibly fractional) milliseconds.
export function milliseconds(
duration: protos.google.protobuf.IDuration
): number {
return (
Number(duration.seconds || 0) * 1000 + Number(duration.nanos || 0) * 1e-6
);
}
export function isDigit(value: string): boolean {
return /^\d+$/.test(value);
}
String.prototype.capitalize = function (this: string): string {
if (this.length === 0) {
return this;
}
return this[0].toUpperCase() + this.slice(1);
};
String.prototype.words = function (this: string): string[] {
// split on spaces, non-alphanumeric, or capital letters
return this.split(/(?=[A-Z])|[\s\W_]+/)
.filter(w => w.length > 0)
.map(w => w.toLowerCase());
};
String.prototype.toCamelCase = function (this: string): string {
const words = this.words();
if (words.length === 0) {
return this;
}
const result = [words[0]];
result.push(
...words.slice(1).map(w => {
if (isDigit(w)) {
return '_' + w;
}
return w.capitalize();
})
);
return result.join('');
};
String.prototype.toPascalCase = function (this: string): string {
const words = this.words();
if (words.length === 0) {
return this;
}
const result = words.map(w => w.capitalize());
return result.join('');
};
String.prototype.toKebabCase = function (this: string): string {
const words = this.words();
if (words.length === 0) {
return this;
}
return words.join('-');
};
String.prototype.toSnakeCase = function (this: string): string {
const words = this.words();
if (words.length === 0) {
return this;
}
return words.join('_');
};
String.prototype.replaceAll = function (
this: string,
search: string,
replacement: string
) {
return this.split(search).join(replacement);
};
Array.prototype.toCamelCaseString = function (
this: string[],
joiner: string
): string {
return this.map(part => part.toCamelCase()).join(joiner);
};
Array.prototype.toSnakeCaseString = function (
this: string[],
joiner: string
): string {
return this.map(part => part.toSnakeCase()).join(joiner);
};
export function getResourceNameByPattern(pattern: string): string {
const elements = pattern.split('/');
const name = [];
// Multi pattern like: `projects/{project}/cmekSettings`, we need to append `cmekSettings` to the name.
// Or it will be duplicate with `project/{project}`
// Iterate the elements, if it comes in pairs: user/{userId}, we take `userId` as part of the name.
// if it comes as `profile` with no following `/{profile_id}`, we take `profile` as part of the name.
// So for pattern: `user/{user_id}/profile/blurbs/{blurb_id}`, name will be `userId_profile_blurbId`
while (elements.length > 0) {
const eleName = elements.shift();
if (elements.length === 0) {
name.push(eleName);
break;
} else {
const nextEle = elements[0];
if (nextEle.match(/(?<=\{).*?(?=(?:=.*?)?\})/g)) {
elements.shift();
const params = nextEle.match(/(?<=\{).*?(?=(?:=.*?)?\})/g);
if (params!.length === 1) {
name.push(params![0]);
} else {
// For non-slash resource 'organization/{organization}/tasks/{task_id}{task_name}/result'
// Take parameters that match pattern [{task_id}, {task_name}] and combine them as part of the name.
const params = nextEle.match(/(?<=\{).*?(?=(?:=.*?)?\})/g);
name.push(params!.join('_'));
}
} else {
if (eleName!.match(/{[a-zA-Z_]+(?:=.*?)?}/g)) {
continue;
} else {
name.push(eleName);
}
}
}
}
return name.join('_');
}
export function isStar(pattern: string): boolean {
return pattern === '*';
}
export function isDoubleStar(pattern: string): boolean {
return pattern === '**';
}
// This intakes an array of strings and checks if there is at least one and only one named segment.
// Named segments can be resource names or wildcards.
export function checkIfArrayContainsOnlyOneNamedSegment(
pattern: string[]
): boolean {
let countOfNamedSegments = 0;
// Checks that resources are named
const regexNamed = new RegExp(/^.+=.+/);
const regexWildcard = new RegExp(/^{[a-zA-Z\d-]+}/);
pattern.forEach(element => {
if (regexNamed.test(element) || regexWildcard.test(element)) {
countOfNamedSegments++;
}
});
return countOfNamedSegments === 1;
}
// This takes in a path template segment and converts it into regex.
export function convertSegmentToRegex(pattern: string): string {
const curlyBraceRegex = new RegExp(/{(.[^}]+)/);
const namedResourceRegex = new RegExp(/=/);
const getBeforeAfterEqualsSign = new RegExp(/([^=]*)=(.*)/);
if (isStar(pattern) || isStar(pattern.replaceAll('}', ''))) {
return '[^/]+';
}
// If segment is a double-wildcard, then it will 'eat' the precending '/'.
else if (isDoubleStar(pattern) || isDoubleStar(pattern.replaceAll('}', ''))) {
return '(?:/.*)?';
}
// If segment has a starting curly brace, and is not named, then it is a wildcard.
else if (curlyBraceRegex.test(pattern) && !namedResourceRegex.test(pattern)) {
// Strip any curly braces
const newPattern = pattern.replaceAll('}', '').replaceAll('{', '');
return '(?<' + newPattern + '>[^/]+)';
}
// If segment contains named resource, then the resource could be a wildcard or
// a collectionId
else if (curlyBraceRegex.test(pattern) && namedResourceRegex.test(pattern)) {
// Strip any curly braces
const newPattern = pattern.replaceAll('}', '').replaceAll('{', '');
const elements = newPattern.match(getBeforeAfterEqualsSign);
const name = '(?<' + elements![1] + '>';
const resource = elements![2];
if (isStar(resource)) {
return name + '[^/]+)';
} else if (isDoubleStar(resource)) {
return name + '(?:/.*)?' + ')';
} else {
return name + resource + ')';
}
}
// If segment is just a CollectionId, then the regex equivalent is itself.
else if (pattern.match(/[a-zA-Z_-]+/)) {
return pattern;
} else {
return '';
}
}
// This takes in a full path template and converts it into regex.
export function convertTemplateToRegex(pattern: string): string {
const splitStrings = pattern.split('/');
const regexStrings: string[] = [];
while (splitStrings.length > 0) {
const item = splitStrings.shift();
const itemToRegex = convertSegmentToRegex(item!);
// If item is a double-wildcard, then do not include a '/' separator as a double-wildcard may be empty.
const doubleWildcardRegex = new RegExp(/\*\*/);
if (!doubleWildcardRegex.test(item!)) {
regexStrings.push('/');
}
regexStrings.push(itemToRegex);
}
let helperString = regexStrings.join('');
// Check if string begins with separator
const separatorRegex = new RegExp(/^\//);
if (separatorRegex.test(helperString)) {
helperString = helperString.substring(1);
}
return helperString;
}
// This intakes a path template and returns an array where the first element is the full named
// segment, the second element is the name of the segment, the third element is the segment itself,
// and the fourth element is the named capture regex of the named segement.
// If the path template does not contain exactly one named segment, this function will return an empty array.
export function getNamedSegment(pattern: string): string[] {
// Named segment in path template will always be contained within curly braces, e.g. '{}'
const curlyBraceRegex = new RegExp(/[^{}]+(?=})/);
// Named segment may just be a collection id
const collectionIdRegex = new RegExp(/{.*}/);
const namedSegmentWithoutCurlyBraces = pattern.match(curlyBraceRegex);
const namedSegmentWithCurlyBraces = pattern.match(collectionIdRegex);
if (
!namedSegmentWithoutCurlyBraces ||
!namedSegmentWithCurlyBraces ||
!checkIfArrayContainsOnlyOneNamedSegment(namedSegmentWithCurlyBraces)
) {
return [];
}
const namedSegment = [];
// This contains the full named segment.
namedSegment.push(namedSegmentWithoutCurlyBraces[0]);
// This extracts the name from the named segment.
const nameOfSegmentRegex = new RegExp(/^(.*?)=/);
const nameOfSegment = namedSegmentWithoutCurlyBraces[0].match(
nameOfSegmentRegex
);
// // If the segment is just a collection id (e.g., {database}), then the name of the segment is itself, and the segment is a wildcard.
if (!nameOfSegmentRegex.test(namedSegmentWithoutCurlyBraces[0])) {
namedSegment.push(namedSegmentWithoutCurlyBraces[0]);
namedSegment.push('*');
namedSegment.push('[^/]+');
} else {
namedSegment.push(nameOfSegment![1]);
// This extracts the segment from the named segement.
const extractNameRegex = new RegExp(nameOfSegment![1] + '=(.*)');
const segment = namedSegmentWithoutCurlyBraces[0].match(
extractNameRegex
)![1];
namedSegment.push(segment);
// This converts the full named segment into regex.
// Special case for double wildcard in a named segment as we
// do want to capture it for a named segment.
let resourceRegex = convertTemplateToRegex(segment);
if (isDoubleStar(segment) || isDoubleStar(segment.replaceAll('}', ''))) {
resourceRegex = '.*';
}
const fullRegex = '(?<' + nameOfSegment![1] + '>' + resourceRegex + ')';
namedSegment.push(fullRegex);
}
return namedSegment;
} | the_stack |
import {AeadConfig} from '../aead/aead_config';
import {AeadKeyTemplates} from '../aead/aead_key_templates';
import {PbAesCtrKeyFormat, PbEciesAeadDemParams, PbEciesAeadHkdfKeyFormat, PbEciesAeadHkdfParams, PbEciesAeadHkdfPrivateKey, PbEciesAeadHkdfPublicKey, PbEciesHkdfKemParams, PbEllipticCurveType, PbHashType, PbKeyData, PbKeyTemplate, PbPointFormat} from '../internal/proto';
import * as Registry from '../internal/registry';
import * as Random from '../subtle/random';
import {assertExists, assertInstanceof} from '../testing/internal/test_utils';
import {EciesAeadHkdfPrivateKeyManager} from './ecies_aead_hkdf_private_key_manager';
import {EciesAeadHkdfPublicKeyManager} from './ecies_aead_hkdf_public_key_manager';
import {HybridDecrypt} from './internal/hybrid_decrypt';
import {HybridEncrypt} from './internal/hybrid_encrypt';
const PRIVATE_KEY_TYPE =
'type.googleapis.com/google.crypto.tink.EciesAeadHkdfPrivateKey';
const PRIVATE_KEY_MATERIAL_TYPE = PbKeyData.KeyMaterialType.ASYMMETRIC_PRIVATE;
const VERSION = 0;
const PRIVATE_KEY_MANAGER_PRIMITIVE = HybridDecrypt;
const PUBLIC_KEY_TYPE =
'type.googleapis.com/google.crypto.tink.EciesAeadHkdfPublicKey';
const PUBLIC_KEY_MATERIAL_TYPE = PbKeyData.KeyMaterialType.ASYMMETRIC_PUBLIC;
const PUBLIC_KEY_MANAGER_PRIMITIVE = HybridEncrypt;
describe('ecies aead hkdf private key manager test', function() {
beforeEach(function() {
AeadConfig.register();
// Use a generous promise timeout for running continuously.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 1000; // 1000s
});
afterEach(function() {
Registry.reset();
// Reset the promise timeout to default value.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; // 1s
});
it('new key, empty key format', async function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
try {
await manager.getKeyFactory().newKey(new Uint8Array(0));
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.invalidSerializedKeyFormat());
}
});
it('new key, invalid serialized key format', async function() {
const invalidSerializedKeyFormat = new Uint8Array(0);
const manager = new EciesAeadHkdfPrivateKeyManager();
try {
await manager.getKeyFactory().newKey(invalidSerializedKeyFormat);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.invalidSerializedKeyFormat());
}
});
it('new key, unsupported key format proto', async function() {
const unsupportedKeyFormatProto = new PbAesCtrKeyFormat();
const manager = new EciesAeadHkdfPrivateKeyManager();
try {
await manager.getKeyFactory().newKey(unsupportedKeyFormatProto);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.unsupportedKeyFormat());
}
});
it('new key, invalid format, missing params', async function() {
const invalidFormat = new PbEciesAeadHkdfKeyFormat();
const manager = new EciesAeadHkdfPrivateKeyManager();
try {
await manager.getKeyFactory().newKey(invalidFormat);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.invalidKeyFormatMissingParams());
}
});
it('new key, invalid format, invalid params', async function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
// unknown point format
const invalidFormat = createKeyFormat();
invalidFormat.getParams()?.setEcPointFormat(PbPointFormat.UNKNOWN_FORMAT);
try {
await manager.getKeyFactory().newKey(invalidFormat);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.unknownPointFormat());
}
invalidFormat.getParams()?.setEcPointFormat(PbPointFormat.UNCOMPRESSED);
// missing KEM params
invalidFormat.getParams()?.setKemParams(null);
try {
await manager.getKeyFactory().newKey(invalidFormat);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.missingKemParams());
}
invalidFormat.getParams()?.setKemParams(createKemParams());
// unsupported AEAD template
const templateTypeUrl = 'UNSUPPORTED_KEY_TYPE_URL';
invalidFormat.getParams()?.getDemParams()?.getAeadDem()?.setTypeUrl(
templateTypeUrl);
try {
await manager.getKeyFactory().newKey(invalidFormat);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe(ExceptionText.unsupportedKeyTemplate(templateTypeUrl));
}
});
it('new key, via key format', async function() {
const keyFormats = createTestSetOfKeyFormats();
const manager = new EciesAeadHkdfPrivateKeyManager();
for (const keyFormat of keyFormats) {
const key = await manager.getKeyFactory().newKey(keyFormat);
expect(key.getPublicKey()?.getParams()).toEqual(keyFormat.getParams());
// The keys are tested more in tests for getPrimitive method below, where
// the primitive based on the created key is tested.
}
});
it('new key data, invalid serialized key format', async function() {
const serializedKeyFormats = [new Uint8Array(1), new Uint8Array(0)];
const manager = new EciesAeadHkdfPrivateKeyManager();
const serializedKeyFormatsLength = serializedKeyFormats.length;
for (let i = 0; i < serializedKeyFormatsLength; i++) {
try {
await manager.getKeyFactory().newKeyData(serializedKeyFormats[i]);
fail(
'An exception should be thrown for the string: ' +
serializedKeyFormats[i]);
} catch (e) {
expect(e.toString()).toBe(ExceptionText.invalidSerializedKeyFormat());
continue;
}
}
});
it('new key data, from valid key format', async function() {
const keyFormats = createTestSetOfKeyFormats();
const manager = new EciesAeadHkdfPrivateKeyManager();
for (const keyFormat of keyFormats) {
const serializedKeyFormat = keyFormat.serializeBinary();
const keyData =
await manager.getKeyFactory().newKeyData(serializedKeyFormat);
expect(keyData.getTypeUrl()).toBe(PRIVATE_KEY_TYPE);
expect(keyData.getKeyMaterialType()).toBe(PRIVATE_KEY_MATERIAL_TYPE);
const key =
PbEciesAeadHkdfPrivateKey.deserializeBinary(keyData.getValue());
expect(key.getPublicKey()?.getParams()).toEqual(keyFormat.getParams());
// The keys are tested more in tests for getPrimitive method below, where
// the primitive based on the created key is tested.
}
});
it('get public key data, invalid private key serialization', function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
const privateKey = new Uint8Array([0, 1]); // not a serialized private key
try {
const factory = manager.getKeyFactory();
factory.getPublicKeyData(privateKey);
} catch (e) {
expect(e.toString()).toBe(ExceptionText.invalidSerializedKey());
}
});
it('get public key data, should work', async function() {
const keyFormat = createKeyFormat();
const manager = new EciesAeadHkdfPrivateKeyManager();
const privateKey = await manager.getKeyFactory().newKey(keyFormat);
const factory = manager.getKeyFactory();
const publicKeyData =
factory.getPublicKeyData(privateKey.serializeBinary());
expect(publicKeyData.getTypeUrl()).toBe(PUBLIC_KEY_TYPE);
expect(publicKeyData.getKeyMaterialType()).toBe(PUBLIC_KEY_MATERIAL_TYPE);
const publicKey =
PbEciesAeadHkdfPublicKey.deserializeBinary(publicKeyData.getValue());
expect(publicKey.getVersion())
.toEqual(assertExists(privateKey.getPublicKey()).getVersion());
expect(publicKey.getParams())
.toEqual(assertExists(privateKey.getPublicKey()).getParams());
expect(publicKey.getX())
.toEqual(assertExists(privateKey.getPublicKey()).getX());
expect(publicKey.getY())
.toEqual(assertExists(privateKey.getPublicKey()).getY());
});
it('get primitive, unsupported key data type', async function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
const keyFormat = createKeyFormat();
const keyData =
(await manager.getKeyFactory().newKeyData(keyFormat.serializeBinary()))
.setTypeUrl('unsupported_key_type_url');
try {
await manager.getPrimitive(PRIVATE_KEY_MANAGER_PRIMITIVE, keyData);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe(ExceptionText.unsupportedKeyType(keyData.getTypeUrl()));
}
});
it('get primitive, unsupported key type', async function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
const key = new PbEciesAeadHkdfPublicKey();
try {
await manager.getPrimitive(PRIVATE_KEY_MANAGER_PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.unsupportedKeyType());
}
});
it('get primitive, high version', async function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
const version = manager.getVersion() + 1;
const keyFormat = createKeyFormat();
const key = assertInstanceof(
await manager.getKeyFactory().newKey(keyFormat),
PbEciesAeadHkdfPrivateKey)
.setVersion(version);
try {
await manager.getPrimitive(PRIVATE_KEY_MANAGER_PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.versionOutOfBounds());
}
});
it('get primitive, invalid params', async function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
const keyFormat = createKeyFormat();
const key = assertInstanceof(
await manager.getKeyFactory().newKey(keyFormat),
PbEciesAeadHkdfPrivateKey);
// missing KEM params
key.getPublicKey()?.getParams()?.setKemParams(null);
try {
await manager.getPrimitive(PRIVATE_KEY_MANAGER_PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.missingKemParams());
}
key.getPublicKey()?.getParams()?.setKemParams(createKemParams());
// unsupported AEAD key template type URL
const templateTypeUrl = 'UNSUPPORTED_KEY_TYPE_URL';
key.getPublicKey()?.getParams()?.getDemParams()?.getAeadDem()?.setTypeUrl(
templateTypeUrl);
try {
await manager.getPrimitive(PRIVATE_KEY_MANAGER_PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe(ExceptionText.unsupportedKeyTemplate(templateTypeUrl));
}
});
it('get primitive, invalid serialized key', async function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
const keyFormat = createKeyFormat();
const keyData =
await manager.getKeyFactory().newKeyData(keyFormat.serializeBinary());
for (let i = 0; i < 2; ++i) {
// Set the value of keyData to something which is not a serialization of a
// proper key.
keyData.setValue(new Uint8Array(i));
try {
await manager.getPrimitive(PRIVATE_KEY_MANAGER_PRIMITIVE, keyData);
fail('An exception should be thrown ' + i.toString());
} catch (e) {
expect(e.toString()).toBe(ExceptionText.invalidSerializedKey());
}
}
});
it('get primitive, from key', async function() {
const keyFormats = createTestSetOfKeyFormats();
const privateKeyManager = new EciesAeadHkdfPrivateKeyManager();
const publicKeyManager = new EciesAeadHkdfPublicKeyManager();
for (const keyFormat of keyFormats) {
const key = assertInstanceof(
await privateKeyManager.getKeyFactory().newKey(keyFormat),
PbEciesAeadHkdfPrivateKey);
const hybridEncrypt: HybridEncrypt =
assertExists(await publicKeyManager.getPrimitive(
PUBLIC_KEY_MANAGER_PRIMITIVE, assertExists(key.getPublicKey())));
const hybridDecrypt: HybridDecrypt =
assertExists(await privateKeyManager.getPrimitive(
PRIVATE_KEY_MANAGER_PRIMITIVE, key));
const plaintext = Random.randBytes(10);
const ciphertext = await hybridEncrypt.encrypt(plaintext);
const decryptedCiphertext = await hybridDecrypt.decrypt(ciphertext);
expect(decryptedCiphertext).toEqual(plaintext);
}
});
it('get primitive, from key data', async function() {
const keyFormats = createTestSetOfKeyFormats();
const privateKeyManager = new EciesAeadHkdfPrivateKeyManager();
const publicKeyManager = new EciesAeadHkdfPublicKeyManager();
for (const keyFormat of keyFormats) {
const serializedKeyFormat = keyFormat.serializeBinary();
const keyData = await privateKeyManager.getKeyFactory().newKeyData(
serializedKeyFormat);
const factory = privateKeyManager.getKeyFactory();
const publicKeyData = factory.getPublicKeyData(keyData.getValue_asU8());
const hybridEncrypt: HybridEncrypt =
assertExists(await publicKeyManager.getPrimitive(
PUBLIC_KEY_MANAGER_PRIMITIVE, publicKeyData));
const hybridDecrypt: HybridDecrypt =
assertExists(await privateKeyManager.getPrimitive(
PRIVATE_KEY_MANAGER_PRIMITIVE, keyData));
const plaintext = Random.randBytes(10);
const ciphertext = await hybridEncrypt.encrypt(plaintext);
const decryptedCiphertext = await hybridDecrypt.decrypt(ciphertext);
expect(decryptedCiphertext).toEqual(plaintext);
}
});
it('does support', function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
expect(manager.doesSupport(PRIVATE_KEY_TYPE)).toBe(true);
});
it('get key type', function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
expect(manager.getKeyType()).toBe(PRIVATE_KEY_TYPE);
});
it('get primitive type', function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
expect(manager.getPrimitiveType()).toBe(PRIVATE_KEY_MANAGER_PRIMITIVE);
});
it('get version', function() {
const manager = new EciesAeadHkdfPrivateKeyManager();
expect(manager.getVersion()).toBe(VERSION);
});
});
// Helper classes and functions
class ExceptionText {
static nullKeyFormat(): string {
return 'SecurityException: Key format has to be non-null.';
}
static invalidSerializedKeyFormat(): string {
return 'SecurityException: Input cannot be parsed as ' + PRIVATE_KEY_TYPE +
' key format proto.';
}
static unsupportedPrimitive(): string {
return 'SecurityException: Requested primitive type which is not supported by ' +
'this key manager.';
}
static unsupportedKeyFormat(): string {
return 'SecurityException: Expected ' + PRIVATE_KEY_TYPE +
' key format proto.';
}
static unsupportedKeyType(opt_requestedKeyType?: string): string {
const prefix = 'SecurityException: Key type';
const suffix =
'is not supported. This key manager supports ' + PRIVATE_KEY_TYPE + '.';
if (opt_requestedKeyType) {
return prefix + ' ' + opt_requestedKeyType + ' ' + suffix;
} else {
return prefix + ' ' + suffix;
}
}
static versionOutOfBounds(): string {
return 'SecurityException: Version is out of bound, must be between 0 and ' +
VERSION + '.';
}
static invalidKeyFormatMissingParams(): string {
return 'SecurityException: Invalid key format - missing key params.';
}
static unknownPointFormat(): string {
return 'SecurityException: Invalid key params - unknown EC point format.';
}
static missingKemParams(): string {
return 'SecurityException: Invalid params - missing KEM params.';
}
static unsupportedKeyTemplate(templateTypeUrl: string): string {
return 'SecurityException: Invalid DEM params - ' + templateTypeUrl +
' template is not supported by ECIES AEAD HKDF.';
}
static invalidSerializedKey(): string {
return 'SecurityException: Input cannot be parsed as ' + PRIVATE_KEY_TYPE +
' key-proto.';
}
}
function createKemParams(
opt_curveType: PbEllipticCurveType = PbEllipticCurveType.NIST_P256,
opt_hashType: PbHashType = PbHashType.SHA256): PbEciesHkdfKemParams {
const kemParams = new PbEciesHkdfKemParams()
.setCurveType(opt_curveType)
.setHkdfHashType(opt_hashType);
return kemParams;
}
function createDemParams(opt_keyTemplate?: PbKeyTemplate):
PbEciesAeadDemParams {
if (!opt_keyTemplate) {
opt_keyTemplate = AeadKeyTemplates.aes128CtrHmacSha256();
}
const demParams = new PbEciesAeadDemParams().setAeadDem(opt_keyTemplate);
return demParams;
}
function createKeyParams(
opt_curveType?: PbEllipticCurveType, opt_hashType?: PbHashType,
opt_keyTemplate?: PbKeyTemplate,
opt_pointFormat: PbPointFormat =
PbPointFormat.UNCOMPRESSED): PbEciesAeadHkdfParams {
const params = new PbEciesAeadHkdfParams()
.setKemParams(createKemParams(opt_curveType, opt_hashType))
.setDemParams(createDemParams(opt_keyTemplate))
.setEcPointFormat(opt_pointFormat);
return params;
}
function createKeyFormat(
opt_curveType?: PbEllipticCurveType, opt_hashType?: PbHashType,
opt_keyTemplate?: PbKeyTemplate,
opt_pointFormat?: PbPointFormat): PbEciesAeadHkdfKeyFormat {
const keyFormat = new PbEciesAeadHkdfKeyFormat().setParams(createKeyParams(
opt_curveType, opt_hashType, opt_keyTemplate, opt_pointFormat));
return keyFormat;
}
/**
* Create set of key formats with all possible predefined/supported parameters.
*/
function createTestSetOfKeyFormats(): PbEciesAeadHkdfKeyFormat[] {
const curveTypes = [
PbEllipticCurveType.NIST_P256, PbEllipticCurveType.NIST_P384,
PbEllipticCurveType.NIST_P521
];
const hashTypes = [PbHashType.SHA1, PbHashType.SHA256, PbHashType.SHA512];
const keyTemplates = [
AeadKeyTemplates.aes128CtrHmacSha256(),
AeadKeyTemplates.aes256CtrHmacSha256()
];
const pointFormats = [PbPointFormat.UNCOMPRESSED];
const keyFormats: PbEciesAeadHkdfKeyFormat[] = [];
for (const curve of curveTypes) {
for (const hkdfHash of hashTypes) {
for (const keyTemplate of keyTemplates) {
for (const pointFormat of pointFormats) {
const keyFormat =
createKeyFormat(curve, hkdfHash, keyTemplate, pointFormat);
keyFormats.push(keyFormat);
}
}
}
}
return keyFormats;
} | the_stack |
import { SInt64, UInt64, Int64 } from './int64'
import { sint64rand, uint64rand } from './int64_rand'
import { asciibuf } from './util'
import {
assertEq,
assertEqList,
assertEqObj,
assertThrows,
quickcheck,
} from './test'
TEST('basic', () => {
let s, u
s = new SInt64(0xFFFFFFFF | 0, 0x7FFFFFFF | 0)
assertEq(s.toFloat64(), 9223372036854775807)
assertEq(s.toString(10), "9223372036854775807")
s = new SInt64(0 | 0, 0 | 0)
assertEq(s.toFloat64(), 0)
assertEq(s.toString(10), "0")
u = new UInt64(0xFFFFFFFF | 0, 0xFFFFFFFF | 0)
assertEq(u.toString(10), "18446744073709551615")
})
TEST('constants', () => {
let s, u
s = new SInt64(0xFFFFFFFF | 0, 0x7FFFFFFF | 0)
assert(s.constructor === SInt64.MAX.constructor)
assert(s.eq(SInt64.MAX))
s = new SInt64(0, 0x80000000 | 0)
assert(s.constructor === SInt64.MIN.constructor)
assert(s.eq(SInt64.MIN))
s = new SInt64(0, 0)
assert(s.constructor === SInt64.ZERO.constructor)
assert(s.eq(SInt64.ZERO))
s = new SInt64(1, 0)
assert(s.constructor === SInt64.ONE.constructor)
assert(s.eq(SInt64.ONE))
s = new SInt64(-1 | 0, -1)
assert(s.constructor === SInt64.ONENEG.constructor)
assert(s.eq(SInt64.ONENEG))
u = new UInt64(0xFFFFFFFF | 0, 0xFFFFFFFF | 0)
assert(u.constructor === UInt64.MAX.constructor)
assert(u.eq(UInt64.MAX))
u = new UInt64(0, 0)
assert(u.constructor === UInt64.MIN.constructor)
assert(u.constructor === UInt64.ZERO.constructor)
assert(u.eq(UInt64.MIN))
assert(u.eq(UInt64.ZERO))
})
TEST('toString', () => {
let s, u
s = SInt64.MAX
assertEq(s.toString(16), "7fffffffffffffff")
assertEq(s.toString(10), "9223372036854775807")
assertEq(s.toString(8), "777777777777777777777")
assertEq(s.toString(36), "1y2p0ij32e8e7")
s = SInt64.MIN
assertEq(s.toString(16), "-8000000000000000")
assertEq(s.toString(10), "-9223372036854775808")
assertEq(s.toString(8), "-1000000000000000000000")
assertEq(s.toString(36), "-1y2p0ij32e8e8")
u = UInt64.MAX
assertEq(u.toString(16), "ffffffffffffffff")
assertEq(u.toString(10), "18446744073709551615")
assertEq(u.toString(8), "1777777777777777777777")
assertEq(u.toString(36), "3w5e11264sgsf")
})
TEST('fromStr', () => {
function t(I :any, s :string, radix :int) {
assertEq(I.fromStr(s, radix).toString(radix), s)
}
t(SInt64, "7fffffffffffffff", 16)
t(SInt64, "9223372036854775807", 10)
t(SInt64, "777777777777777777777", 8)
t(SInt64, "1y2p0ij32e8e7", 36)
t(SInt64, "-8000000000000000", 16)
t(SInt64, "-9223372036854775808", 10)
t(SInt64, "-1000000000000000000000", 8)
t(SInt64, "-1y2p0ij32e8e8", 36)
t(UInt64, "efffffffffffffff", 16) // this caught a bug once
t(UInt64, "ffffffffffffffff", 16)
t(UInt64, "18446744073709551615", 10)
t(UInt64, "1777777777777777777777", 8)
t(UInt64, "3w5e11264sgsf", 36)
})
TEST('fromByteStr', () => {
function t(I :any, str :string, radix :int) {
let inbuf = asciibuf(str)
let u = I.fromByteStr(inbuf, radix)
assertEq(u.toString(radix), str)
}
t(SInt64, "7fffffffffffffff", 16)
t(SInt64, "9223372036854775807", 10)
t(SInt64, "777777777777777777777", 8)
t(SInt64, "1y2p0ij32e8e7", 36)
t(SInt64, "-8000000000000000", 16)
t(SInt64, "-9223372036854775808", 10)
t(SInt64, "-1000000000000000000000", 8)
t(SInt64, "-1y2p0ij32e8e8", 36)
t(UInt64, "efffffffffffffff", 16) // this caught a bug once
t(UInt64, "ffffffffffffffff", 16)
t(UInt64, "18446744073709551615", 10)
t(UInt64, "1777777777777777777777", 8)
t(UInt64, "3w5e11264sgsf", 36)
})
TEST('fromByteStr0', () => {
function t(I :any, str :string, radix :int) {
let expectstr = str
if (str[0] == '-') {
str = str.substr(1)
}
let inbuf = asciibuf(str)
let u = I.fromByteStr0(inbuf, radix, 0, inbuf.length)
assertEq(u.toString(radix), expectstr)
}
t(SInt64, "7fffffffffffffff", 16)
t(SInt64, "9223372036854775807", 10)
t(SInt64, "777777777777777777777", 8)
t(SInt64, "1y2p0ij32e8e7", 36)
t(SInt64, "-8000000000000000", 16)
t(SInt64, "-9223372036854775808", 10)
t(SInt64, "-1000000000000000000000", 8)
t(SInt64, "-1y2p0ij32e8e8", 36)
t(UInt64, "efffffffffffffff", 16) // this caught a bug once
t(UInt64, "ffffffffffffffff", 16)
t(UInt64, "18446744073709551615", 10)
t(UInt64, "1777777777777777777777", 8)
t(UInt64, "3w5e11264sgsf", 36)
})
TEST('toBytes', () => {
let s
s = new SInt64(0x01234567, 0x12345678)
assertEqList(
s.toBytesBE(),
[ 0x12, 0x34, 0x56, 0x78, 0x01, 0x23, 0x45, 0x67 ]
)
assertEqList(
s.toBytesLE(),
[ 0x67, 0x45, 0x23, 0x01, 0x78, 0x56, 0x34, 0x12 ]
)
// Note: we are not testing toBytes separately for UInt64
// since SInt64 and UInt64 uses the same implementations.
})
TEST('fromBytes', () => {
let s, u
s = new SInt64(0x01234567, 0x12345678)
u = new UInt64(0x01234567, 0x12345678)
assertEqObj(SInt64.fromBytesLE(s.toBytesLE()), s)
assertEqObj(
SInt64.fromBytesBE([0x12, 0x34, 0x56, 0x78, 0x01, 0x23, 0x45, 0x67]),
s
)
assertEqObj(
SInt64.fromBytesLE([0x67, 0x45, 0x23, 0x01, 0x78, 0x56, 0x34, 0x12]),
s
)
assertEqObj(
UInt64.fromBytesLE([0x67, 0x45, 0x23, 0x01, 0x78, 0x56, 0x34, 0x12]),
u
)
// Note: we are not testing fromBytes separately for UInt64
// since SInt64 and UInt64 uses the same implementations.
})
TEST('fromInt32', () => {
let s, u
s = SInt64.fromInt32(0x7FFFFFFF)
assertEq(s.toString(10), '2147483647')
s = SInt64.fromInt32(0xFFFFFFFF)
assertEq(s.toString(10), '-1')
s = SInt64.fromInt32(-0x80000000)
assertEq(s.toString(10), '-2147483648')
s = SInt64.fromInt32(-0x80000001)
assertEq(s.toString(10), '2147483647') // wraps around
u = UInt64.fromInt32(0xFFFFFFFF)
assertEq(u.toString(10), '4294967295')
u = UInt64.fromInt32(0xFFFFFFFFFF) // limited to 0xFFFFFFFF
assertEq(u.toString(10), '4294967295')
u = UInt64.fromInt32(-0xFFFFFFFe)
assertEq(u.toString(10), '18446744069414584322') // wraps around
// sanity-check constructor before relying on _low and _high values
u = new UInt64(-1, -1)
assertEq(u._low, -1)
assertEq(u._high, -1)
assertEq(u.toString(10), '18446744073709551615')
u = UInt64.fromInt32(-1) // wraps around to UInt64
assertEq(u._low, -1)
assertEq(u._high, -1)
assertEq(u.toString(10), '18446744073709551615')
u = UInt64.fromInt32(-2) // wraps around with -1
assertEq(u.toString(10), '18446744073709551614')
})
TEST('fromFloat64/s', () => {
let s
s = SInt64.fromFloat64(0x7FFFFFFF)
assertEq(s.toFloat64(), 2147483647)
assertEq(s.toString(10), '2147483647')
s = SInt64.fromFloat64(0xFFFFFFFFFF)
assertEq(s.toFloat64(), 1099511627775)
assertEq(s.toString(10), '1099511627775')
s = SInt64.fromFloat64(-0xFFFFFFFFFF)
assertEq(s.toFloat64(), -1099511627775)
assertEq(s.toString(10), '-1099511627775')
s = SInt64.fromFloat64(0x7FFFFFFFFFFFFFFF)
assertEq(s.toFloat64(), 9223372036854775807)
assertEq(s.toString(10), '9223372036854775807')
s = SInt64.fromFloat64(-0x8000000000000000)
assertEq(s.toFloat64(), -9223372036854775808)
assertEq(s.toString(10), '-9223372036854775808')
s = SInt64.fromFloat64(0xFFFFFFFFFFFFFFFF) // limited to SInt64.MAX
assertEq(s.toFloat64(), 9223372036854775807)
assertEq(s.toString(10), '9223372036854775807')
})
TEST('fromFloat64/u', () => {
let u
u = UInt64.fromFloat64(0x7FFFFFFF)
assertEq(u.toFloat64(), 2147483647)
assertEq(u.toString(10), '2147483647')
u = UInt64.fromFloat64(0xFFFFFFFFFF)
assertEq(u.toFloat64(), 1099511627775)
assertEq(u.toString(10), '1099511627775')
u = UInt64.fromFloat64(0xFFFFFFFFFFFFFFFF)
assertEq(u.toFloat64(), 18446744073709551615)
assertEq(u.toString(10), '18446744073709551615')
u = UInt64.fromFloat64(-1) // limited to UInt64.MIN (zero)
assertEq(u.toFloat64(), 0)
assertEq(u.toString(10), '0')
u = UInt64.fromFloat64(-0xFFFFFFFFFF) // limited to UInt64.MIN (zero)
assertEq(u.toFloat64(), 0)
assertEq(u.toString(10), '0')
})
TEST('maybeFromFloat64/s', () => {
let s
s = SInt64.maybeFromFloat64(123) as UInt64
assert(s != null)
assertEq(s.toFloat64(), 123)
assertEq(s.toString(10), '123')
s = SInt64.maybeFromFloat64(0x7FFFFFFF) as UInt64
assert(s != null)
assertEq(s.toFloat64(), 2147483647)
assertEq(s.toString(10), '2147483647')
s = SInt64.maybeFromFloat64(0xFFFFFFFFFF) as UInt64
assert(s != null)
assertEq(s.toFloat64(), 1099511627775)
assertEq(s.toString(10), '1099511627775')
s = SInt64.maybeFromFloat64(-0xFFFFFFFFFF) as UInt64
assert(s != null)
assertEq(s.toFloat64(), -1099511627775)
assertEq(s.toString(10), '-1099511627775')
s = SInt64.maybeFromFloat64(0x7FFFFFFFFFFFFFFF) as UInt64
assert(s != null)
assertEq(s.toFloat64(), 9223372036854775807)
assertEq(s.toString(10), '9223372036854775807')
s = SInt64.maybeFromFloat64(-0x8000000000000000) as UInt64
assert(s != null)
assertEq(s.toFloat64(), -9223372036854775808)
assertEq(s.toString(10), '-9223372036854775808')
s = SInt64.maybeFromFloat64(0xFFFFFFFFFFFFFFFF) as null
// limited to SInt64.MAX
assertEq(s, null)
})
TEST('maybeFromFloat64/u', () => {
let u
u = UInt64.maybeFromFloat64(0x7FFFFFFF) as UInt64
assert(u != null)
assertEq(u.toFloat64(), 2147483647)
assertEq(u.toString(10), '2147483647')
u = UInt64.maybeFromFloat64(0xFFFFFFFFFF) as UInt64
assert(u != null)
assertEq(u.toFloat64(), 1099511627775)
assertEq(u.toString(10), '1099511627775')
u = UInt64.maybeFromFloat64(0xFFFFFFFFFFFFFFFF) as UInt64
assert(u != null)
assertEq(u.toFloat64(), 18446744073709551615)
assertEq(u.toString(10), '18446744073709551615')
u = UInt64.maybeFromFloat64(-1) as null // limited to UInt64.MIN
assertEq(u, null)
u = UInt64.maybeFromFloat64(-0xFFFFFFFFFF) as null // limited to UInt64.MIN
assertEq(u, null)
})
TEST('float64cast', () => {
let u :UInt64, f :number
let fin = 3.141592653589793 // ~PI
// main implementation (possibly wasm)
u = UInt64.fromFloat64Cast(fin)
assertEq(u.toString(16), "400921fb54442d18")
assertEq(u.toFloat64Cast(), fin)
const UInt64c = UInt64 as any
if (UInt64c._js_fromFloat64Cast) {
// JS implementation
const UInt64p = UInt64.prototype as any
u = UInt64c._js_fromFloat64Cast(fin)
assertEq(u.toString(16), "400921fb54442d18")
assertEq(UInt64p._js_toFloat64Cast.call(u), fin)
}
})
TEST('sign-conv', () => {
let s, u
s = SInt64.fromFloat64(-1)
assertEq(s.toFloat64(), -1)
assertEq(s.toString(10), '-1')
u = s.toUnsigned()
assertEq(u.toFloat64(), 0xFFFFFFFFFFFFFFFF)
assertEq(u.toString(16), 'ffffffffffffffff')
s = u.toSigned()
assertEq(s.toFloat64(), -1)
assertEq(s.toString(10), '-1')
})
TEST('sub-max-signed', () => {
let u
//
// UINT64_MAX - INT64_MAX - 1 == INT64_MAX
//
u = UInt64.MAX.sub(SInt64.MAX).sub(SInt64.ONE)
assertEq(u.toFloat64(), SInt64.MAX.toFloat64())
assertEq(u.toString(), SInt64.MAX.toString())
})
TEST('sub-max-unsigned', () => {
let u
//
// UINT64_MAX - UINT64_MAX == 0
//
u = UInt64.MAX.sub(UInt64.MAX)
assertEq(u._low, 0)
assertEq(u._high, 0)
assertEq(u.toFloat64(), 0)
assertEq(u.toString(), '0')
})
TEST('sub-zero-cross-sign', () => {
let s, u
// UINT64_MAX - uint64(1) == 0xFFFFFFFFFFFFFFFe
u = UInt64.MAX.sub(UInt64.ONE)
assertEq(u.toFloat64(), 0xFFFFFFFFFFFFFFFe)
assertEq(u.toString(), '18446744073709551614')
// UINT64_MAX - int64(-1) == 0
u = UInt64.MAX.sub(SInt64.ONENEG) // effectively addition -- wraps to 0
assertEq(u.toFloat64(), 0)
assertEq(u.toString(), '0')
// int64(-1)
s = SInt64.fromInt32(-1)
assertEq(s._low, -1)
assertEq(s._high, -1)
// uint64(0) - int64(-1) == UINT64_MAX
u = UInt64.fromInt32(0).add(s)
assertEq(u.toFloat64(), 0xFFFFFFFFFFFFFFFF)
assertEq(u.toString(), '18446744073709551615')
})
// if wasm is in use and DEBUG, then test JS impl of div as well
let js_mul = (SInt64.prototype as any)._js_mul as (x:Int64)=>SInt64
let js_div_s = (SInt64.prototype as any)._js_div as (x:Int64)=>SInt64
let js_div_u = (UInt64.prototype as any)._js_div as (x:Int64)=>UInt64
let js_mod_s = (SInt64.prototype as any)._js_mod as (x:Int64)=>SInt64
// let js_mod_u = (UInt64.prototype as any)._js_mod as (x:Int64)=>UInt64
let js_popcnt = (SInt64.prototype as any)._js_popcnt as ()=>int
// TODO test js_mod_u
TEST('div-max', () => {
let s, u
// UINT64_MAX / INT64_MAX == 2
s = UInt64.MAX.div(SInt64.MAX)
assertEq(s.toFloat64(), 2)
assertEq(s.toString(), '2')
// UINT64_MAX / UINT64_MAX == 1
u = UInt64.MAX.div(UInt64.MAX)
assertEq(u.toString(), '1')
})
if (js_div_u) TEST('div-max/js', () => {
let s, u
// UINT64_MAX / INT64_MAX == 2
s = js_div_u.call(UInt64.MAX, SInt64.MAX)
assertEq(s.toFloat64(), 2)
assertEq(s.toString(), '2')
// UINT64_MAX / UINT64_MAX == 1
u = js_div_u.call(UInt64.MAX, UInt64.MAX)
assertEq(u.toString(), '1')
})
TEST('div-neg', () => {
let s, u
// uint64(int64(-1)) == UINT64_MAX - 1 == 0xFFFFFFFFFFFFFFFe
s = SInt64.fromInt32(-2)
assertEq(s.toUnsigned().toString(), UInt64.MAX.sub(UInt64.ONE).toString())
// UINT64_MAX / (UINT64_MAX - 1) == 1
// 0xFFFFFFFFFFFFFFFf / 0xFFFFFFFFFFFFFFFe == 1
u = UInt64.MAX.div(s)
assertEq(u.toString(), '1')
// INT64_MIN - 1 == INT64_MIN
s = SInt64.MIN.div(SInt64.ONE)
assertEq(s.toString(), SInt64.MIN.toString())
})
if (js_div_u) TEST('div-neg/js', () => {
let s, u
s = SInt64.fromInt32(-2)
// UINT64_MAX / (UINT64_MAX - 1) == 1
// 0xFFFFFFFFFFFFFFFf / 0xFFFFFFFFFFFFFFFe == 1
u = js_div_u.call(UInt64.MAX, s)
assertEq(u.toString(), '1')
// INT64_MIN - 1 == INT64_MIN
s = js_div_s.call(SInt64.MIN, SInt64.ONE)
assertEq(s.toString(), SInt64.MIN.toString())
})
TEST('div-unsigned', () => {
// make sure division with unsigned numbers yield unsigned results
let a = new UInt64(0, 8)
let b = UInt64.fromFloat64(2656901066)
let x = a.div(b)
assertEq(x.toString(), '12')
assertEq(x.constructor, UInt64)
})
if (js_div_u) TEST('div-unsigned/js', () => {
// make sure division with unsigned numbers yield unsigned results
let a = new UInt64(0, 8)
let b = UInt64.fromFloat64(2656901066)
let x = js_div_u.call(a, b)
assertEq(x.toString(), '12')
assertEq(x.constructor, UInt64)
})
TEST('msb-unsigned', () => {
// most significant bit
// 1 << 63 == 0x8000000000000000
let u = UInt64.ONE.shl(63)
assert(u.eq(SInt64.MIN) == false)
assertEq(u.toString(), "9223372036854775808")
})
TEST('popcnt/s/quickcheck', () => {
// slow, naïve and reliable popcnt implementation used as a reference
function popcnt_naive(n :Int64) {
let c = 0
while (!n.isZero()) {
n = n.and(n.sub(SInt64.ONE)) // clear the least significant bit set
// n = n & n - 1
c++
}
return c
}
quickcheck<SInt64>({ timeout: 100, size: Infinity, gen: sint64rand }, n =>
n.popcnt() == popcnt_naive(n))
quickcheck<SInt64>({ timeout: 100, size: Infinity, gen: sint64rand }, n =>
js_popcnt.call(n) == popcnt_naive(n))
})
TEST('popcnt/u/quickcheck', () => {
// slow, naïve and reliable popcnt implementation used as a reference
function popcnt_naive(n :Int64) {
let c = 0
while (!n.isZero()) {
n = n.and(n.sub(UInt64.ONE)) // clear the least significant bit set
// n = n & n - 1
c++
}
return c
}
quickcheck<UInt64>({ timeout: 100, size: Infinity, gen: uint64rand }, n =>
n.popcnt() == popcnt_naive(n))
quickcheck<UInt64>({ timeout: 100, size: Infinity, gen: uint64rand }, n =>
js_popcnt.call(n) == popcnt_naive(n))
})
// ---------------------------------------------------------------------------
// The remaining tests comes from Google Closure Library's goog/math/long
// ---------------------------------------------------------------------------
// Interprets the given numbers as the bits of a 32-bit int
function i32array(v :number[]) :number[] {
for (let i = 0; i < v.length; ++i) {
v[i] = v[i] & 0xFFFFFFFF
}
return v
}
// Note that these are in numerical order.
var TEST_BITS = i32array([
// low, high, low, high, low, high
0x80000000, 0x00000000, 0xb776d5f5, 0x5634e2db, 0xffefffff, 0xffffffff,
0xfff00000, 0x00000000, 0xfffeffff, 0xffffffff, 0xffff0000, 0x00000000,
0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000, 0xffffffff, 0xfeffffff,
0xffffffff, 0xff000000, 0xffffffff, 0xfffeffff, 0xffffffff, 0xffff0000,
0xffffffff, 0xffff7fff, 0xffffffff, 0xffff8000, 0xffffffff, 0xfffffffe,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000002, 0x00000000, 0x00007fff, 0x00000000, 0x00008000,
0x00000000, 0x0000ffff, 0x00000000, 0x00010000, 0x00000000, 0x00ffffff,
0x00000000, 0x01000000, 0x00000000, 0x5634e2db, 0x00000000, 0xb776d5f5,
0x00000000, 0xffffffff, 0x00000001, 0x00000000, 0x0000ffff, 0xffffffff,
0x00010000, 0x00000000, 0x000fffff, 0xffffffff, 0x00100000, 0x00000000,
0x5634e2db, 0xb776d5f5, 0x7fffffff, 0xffffffff
])
var TEST_ADD_BITS = i32array([
0x3776d5f5, 0x5634e2db, 0x7fefffff, 0xffffffff, 0xb766d5f5, 0x5634e2da,
0x7ff00000, 0x00000000, 0xb766d5f5, 0x5634e2db, 0xffdfffff, 0xffffffff,
0x7ffeffff, 0xffffffff, 0xb775d5f5, 0x5634e2da, 0xffeeffff, 0xfffffffe,
0xffeeffff, 0xffffffff, 0x7fff0000, 0x00000000, 0xb775d5f5, 0x5634e2db,
0xffeeffff, 0xffffffff, 0xffef0000, 0x00000000, 0xfffdffff, 0xffffffff,
0x7ffffffe, 0xffffffff, 0xb776d5f4, 0x5634e2da, 0xffeffffe, 0xfffffffe,
0xffeffffe, 0xffffffff, 0xfffefffe, 0xfffffffe, 0xfffefffe, 0xffffffff,
0x7fffffff, 0x00000000, 0xb776d5f4, 0x5634e2db, 0xffeffffe, 0xffffffff,
0xffefffff, 0x00000000, 0xfffefffe, 0xffffffff, 0xfffeffff, 0x00000000,
0xfffffffd, 0xffffffff, 0x7fffffff, 0xfeffffff, 0xb776d5f5, 0x5534e2da,
0xffefffff, 0xfefffffe, 0xffefffff, 0xfeffffff, 0xfffeffff, 0xfefffffe,
0xfffeffff, 0xfeffffff, 0xfffffffe, 0xfefffffe, 0xfffffffe, 0xfeffffff,
0x7fffffff, 0xff000000, 0xb776d5f5, 0x5534e2db, 0xffefffff, 0xfeffffff,
0xffefffff, 0xff000000, 0xfffeffff, 0xfeffffff, 0xfffeffff, 0xff000000,
0xfffffffe, 0xfeffffff, 0xfffffffe, 0xff000000, 0xffffffff, 0xfdffffff,
0x7fffffff, 0xfffeffff, 0xb776d5f5, 0x5633e2da, 0xffefffff, 0xfffefffe,
0xffefffff, 0xfffeffff, 0xfffeffff, 0xfffefffe, 0xfffeffff, 0xfffeffff,
0xfffffffe, 0xfffefffe, 0xfffffffe, 0xfffeffff, 0xffffffff, 0xfefefffe,
0xffffffff, 0xfefeffff, 0x7fffffff, 0xffff0000, 0xb776d5f5, 0x5633e2db,
0xffefffff, 0xfffeffff, 0xffefffff, 0xffff0000, 0xfffeffff, 0xfffeffff,
0xfffeffff, 0xffff0000, 0xfffffffe, 0xfffeffff, 0xfffffffe, 0xffff0000,
0xffffffff, 0xfefeffff, 0xffffffff, 0xfeff0000, 0xffffffff, 0xfffdffff,
0x7fffffff, 0xffff7fff, 0xb776d5f5, 0x563462da, 0xffefffff, 0xffff7ffe,
0xffefffff, 0xffff7fff, 0xfffeffff, 0xffff7ffe, 0xfffeffff, 0xffff7fff,
0xfffffffe, 0xffff7ffe, 0xfffffffe, 0xffff7fff, 0xffffffff, 0xfeff7ffe,
0xffffffff, 0xfeff7fff, 0xffffffff, 0xfffe7ffe, 0xffffffff, 0xfffe7fff,
0x7fffffff, 0xffff8000, 0xb776d5f5, 0x563462db, 0xffefffff, 0xffff7fff,
0xffefffff, 0xffff8000, 0xfffeffff, 0xffff7fff, 0xfffeffff, 0xffff8000,
0xfffffffe, 0xffff7fff, 0xfffffffe, 0xffff8000, 0xffffffff, 0xfeff7fff,
0xffffffff, 0xfeff8000, 0xffffffff, 0xfffe7fff, 0xffffffff, 0xfffe8000,
0xffffffff, 0xfffeffff, 0x7fffffff, 0xfffffffe, 0xb776d5f5, 0x5634e2d9,
0xffefffff, 0xfffffffd, 0xffefffff, 0xfffffffe, 0xfffeffff, 0xfffffffd,
0xfffeffff, 0xfffffffe, 0xfffffffe, 0xfffffffd, 0xfffffffe, 0xfffffffe,
0xffffffff, 0xfefffffd, 0xffffffff, 0xfefffffe, 0xffffffff, 0xfffefffd,
0xffffffff, 0xfffefffe, 0xffffffff, 0xffff7ffd, 0xffffffff, 0xffff7ffe,
0x7fffffff, 0xffffffff, 0xb776d5f5, 0x5634e2da, 0xffefffff, 0xfffffffe,
0xffefffff, 0xffffffff, 0xfffeffff, 0xfffffffe, 0xfffeffff, 0xffffffff,
0xfffffffe, 0xfffffffe, 0xfffffffe, 0xffffffff, 0xffffffff, 0xfefffffe,
0xffffffff, 0xfeffffff, 0xffffffff, 0xfffefffe, 0xffffffff, 0xfffeffff,
0xffffffff, 0xffff7ffe, 0xffffffff, 0xffff7fff, 0xffffffff, 0xfffffffd,
0x80000000, 0x00000000, 0xb776d5f5, 0x5634e2db, 0xffefffff, 0xffffffff,
0xfff00000, 0x00000000, 0xfffeffff, 0xffffffff, 0xffff0000, 0x00000000,
0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000, 0xffffffff, 0xfeffffff,
0xffffffff, 0xff000000, 0xffffffff, 0xfffeffff, 0xffffffff, 0xffff0000,
0xffffffff, 0xffff7fff, 0xffffffff, 0xffff8000, 0xffffffff, 0xfffffffe,
0xffffffff, 0xffffffff, 0x80000000, 0x00000001, 0xb776d5f5, 0x5634e2dc,
0xfff00000, 0x00000000, 0xfff00000, 0x00000001, 0xffff0000, 0x00000000,
0xffff0000, 0x00000001, 0xffffffff, 0x00000000, 0xffffffff, 0x00000001,
0xffffffff, 0xff000000, 0xffffffff, 0xff000001, 0xffffffff, 0xffff0000,
0xffffffff, 0xffff0001, 0xffffffff, 0xffff8000, 0xffffffff, 0xffff8001,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x80000000, 0x00000002, 0xb776d5f5, 0x5634e2dd, 0xfff00000, 0x00000001,
0xfff00000, 0x00000002, 0xffff0000, 0x00000001, 0xffff0000, 0x00000002,
0xffffffff, 0x00000001, 0xffffffff, 0x00000002, 0xffffffff, 0xff000001,
0xffffffff, 0xff000002, 0xffffffff, 0xffff0001, 0xffffffff, 0xffff0002,
0xffffffff, 0xffff8001, 0xffffffff, 0xffff8002, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x00000002, 0x00000000, 0x00000003,
0x80000000, 0x00007fff, 0xb776d5f5, 0x563562da, 0xfff00000, 0x00007ffe,
0xfff00000, 0x00007fff, 0xffff0000, 0x00007ffe, 0xffff0000, 0x00007fff,
0xffffffff, 0x00007ffe, 0xffffffff, 0x00007fff, 0xffffffff, 0xff007ffe,
0xffffffff, 0xff007fff, 0xffffffff, 0xffff7ffe, 0xffffffff, 0xffff7fff,
0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000, 0x00007ffd,
0x00000000, 0x00007ffe, 0x00000000, 0x00007fff, 0x00000000, 0x00008000,
0x00000000, 0x00008001, 0x80000000, 0x00008000, 0xb776d5f5, 0x563562db,
0xfff00000, 0x00007fff, 0xfff00000, 0x00008000, 0xffff0000, 0x00007fff,
0xffff0000, 0x00008000, 0xffffffff, 0x00007fff, 0xffffffff, 0x00008000,
0xffffffff, 0xff007fff, 0xffffffff, 0xff008000, 0xffffffff, 0xffff7fff,
0xffffffff, 0xffff8000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00007ffe, 0x00000000, 0x00007fff, 0x00000000, 0x00008000,
0x00000000, 0x00008001, 0x00000000, 0x00008002, 0x00000000, 0x0000ffff,
0x80000000, 0x0000ffff, 0xb776d5f5, 0x5635e2da, 0xfff00000, 0x0000fffe,
0xfff00000, 0x0000ffff, 0xffff0000, 0x0000fffe, 0xffff0000, 0x0000ffff,
0xffffffff, 0x0000fffe, 0xffffffff, 0x0000ffff, 0xffffffff, 0xff00fffe,
0xffffffff, 0xff00ffff, 0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff,
0x00000000, 0x00007ffe, 0x00000000, 0x00007fff, 0x00000000, 0x0000fffd,
0x00000000, 0x0000fffe, 0x00000000, 0x0000ffff, 0x00000000, 0x00010000,
0x00000000, 0x00010001, 0x00000000, 0x00017ffe, 0x00000000, 0x00017fff,
0x80000000, 0x00010000, 0xb776d5f5, 0x5635e2db, 0xfff00000, 0x0000ffff,
0xfff00000, 0x00010000, 0xffff0000, 0x0000ffff, 0xffff0000, 0x00010000,
0xffffffff, 0x0000ffff, 0xffffffff, 0x00010000, 0xffffffff, 0xff00ffff,
0xffffffff, 0xff010000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00007fff, 0x00000000, 0x00008000, 0x00000000, 0x0000fffe,
0x00000000, 0x0000ffff, 0x00000000, 0x00010000, 0x00000000, 0x00010001,
0x00000000, 0x00010002, 0x00000000, 0x00017fff, 0x00000000, 0x00018000,
0x00000000, 0x0001ffff, 0x80000000, 0x00ffffff, 0xb776d5f5, 0x5734e2da,
0xfff00000, 0x00fffffe, 0xfff00000, 0x00ffffff, 0xffff0000, 0x00fffffe,
0xffff0000, 0x00ffffff, 0xffffffff, 0x00fffffe, 0xffffffff, 0x00ffffff,
0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000, 0x00fefffe,
0x00000000, 0x00feffff, 0x00000000, 0x00ff7ffe, 0x00000000, 0x00ff7fff,
0x00000000, 0x00fffffd, 0x00000000, 0x00fffffe, 0x00000000, 0x00ffffff,
0x00000000, 0x01000000, 0x00000000, 0x01000001, 0x00000000, 0x01007ffe,
0x00000000, 0x01007fff, 0x00000000, 0x0100fffe, 0x00000000, 0x0100ffff,
0x80000000, 0x01000000, 0xb776d5f5, 0x5734e2db, 0xfff00000, 0x00ffffff,
0xfff00000, 0x01000000, 0xffff0000, 0x00ffffff, 0xffff0000, 0x01000000,
0xffffffff, 0x00ffffff, 0xffffffff, 0x01000000, 0xffffffff, 0xffffffff,
0x00000000, 0x00000000, 0x00000000, 0x00feffff, 0x00000000, 0x00ff0000,
0x00000000, 0x00ff7fff, 0x00000000, 0x00ff8000, 0x00000000, 0x00fffffe,
0x00000000, 0x00ffffff, 0x00000000, 0x01000000, 0x00000000, 0x01000001,
0x00000000, 0x01000002, 0x00000000, 0x01007fff, 0x00000000, 0x01008000,
0x00000000, 0x0100ffff, 0x00000000, 0x01010000, 0x00000000, 0x01ffffff,
0x80000000, 0x5634e2db, 0xb776d5f5, 0xac69c5b6, 0xfff00000, 0x5634e2da,
0xfff00000, 0x5634e2db, 0xffff0000, 0x5634e2da, 0xffff0000, 0x5634e2db,
0xffffffff, 0x5634e2da, 0xffffffff, 0x5634e2db, 0x00000000, 0x5534e2da,
0x00000000, 0x5534e2db, 0x00000000, 0x5633e2da, 0x00000000, 0x5633e2db,
0x00000000, 0x563462da, 0x00000000, 0x563462db, 0x00000000, 0x5634e2d9,
0x00000000, 0x5634e2da, 0x00000000, 0x5634e2db, 0x00000000, 0x5634e2dc,
0x00000000, 0x5634e2dd, 0x00000000, 0x563562da, 0x00000000, 0x563562db,
0x00000000, 0x5635e2da, 0x00000000, 0x5635e2db, 0x00000000, 0x5734e2da,
0x00000000, 0x5734e2db, 0x80000000, 0xb776d5f5, 0xb776d5f6, 0x0dabb8d0,
0xfff00000, 0xb776d5f4, 0xfff00000, 0xb776d5f5, 0xffff0000, 0xb776d5f4,
0xffff0000, 0xb776d5f5, 0xffffffff, 0xb776d5f4, 0xffffffff, 0xb776d5f5,
0x00000000, 0xb676d5f4, 0x00000000, 0xb676d5f5, 0x00000000, 0xb775d5f4,
0x00000000, 0xb775d5f5, 0x00000000, 0xb77655f4, 0x00000000, 0xb77655f5,
0x00000000, 0xb776d5f3, 0x00000000, 0xb776d5f4, 0x00000000, 0xb776d5f5,
0x00000000, 0xb776d5f6, 0x00000000, 0xb776d5f7, 0x00000000, 0xb77755f4,
0x00000000, 0xb77755f5, 0x00000000, 0xb777d5f4, 0x00000000, 0xb777d5f5,
0x00000000, 0xb876d5f4, 0x00000000, 0xb876d5f5, 0x00000001, 0x0dabb8d0,
0x80000000, 0xffffffff, 0xb776d5f6, 0x5634e2da, 0xfff00000, 0xfffffffe,
0xfff00000, 0xffffffff, 0xffff0000, 0xfffffffe, 0xffff0000, 0xffffffff,
0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000, 0xfefffffe,
0x00000000, 0xfeffffff, 0x00000000, 0xfffefffe, 0x00000000, 0xfffeffff,
0x00000000, 0xffff7ffe, 0x00000000, 0xffff7fff, 0x00000000, 0xfffffffd,
0x00000000, 0xfffffffe, 0x00000000, 0xffffffff, 0x00000001, 0x00000000,
0x00000001, 0x00000001, 0x00000001, 0x00007ffe, 0x00000001, 0x00007fff,
0x00000001, 0x0000fffe, 0x00000001, 0x0000ffff, 0x00000001, 0x00fffffe,
0x00000001, 0x00ffffff, 0x00000001, 0x5634e2da, 0x00000001, 0xb776d5f4,
0x80000001, 0x00000000, 0xb776d5f6, 0x5634e2db, 0xfff00000, 0xffffffff,
0xfff00001, 0x00000000, 0xffff0000, 0xffffffff, 0xffff0001, 0x00000000,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xfeffffff,
0x00000000, 0xff000000, 0x00000000, 0xfffeffff, 0x00000000, 0xffff0000,
0x00000000, 0xffff7fff, 0x00000000, 0xffff8000, 0x00000000, 0xfffffffe,
0x00000000, 0xffffffff, 0x00000001, 0x00000000, 0x00000001, 0x00000001,
0x00000001, 0x00000002, 0x00000001, 0x00007fff, 0x00000001, 0x00008000,
0x00000001, 0x0000ffff, 0x00000001, 0x00010000, 0x00000001, 0x00ffffff,
0x00000001, 0x01000000, 0x00000001, 0x5634e2db, 0x00000001, 0xb776d5f5,
0x00000001, 0xffffffff, 0x8000ffff, 0xffffffff, 0xb777d5f5, 0x5634e2da,
0xfff0ffff, 0xfffffffe, 0xfff0ffff, 0xffffffff, 0xffffffff, 0xfffffffe,
0xffffffff, 0xffffffff, 0x0000fffe, 0xfffffffe, 0x0000fffe, 0xffffffff,
0x0000ffff, 0xfefffffe, 0x0000ffff, 0xfeffffff, 0x0000ffff, 0xfffefffe,
0x0000ffff, 0xfffeffff, 0x0000ffff, 0xffff7ffe, 0x0000ffff, 0xffff7fff,
0x0000ffff, 0xfffffffd, 0x0000ffff, 0xfffffffe, 0x0000ffff, 0xffffffff,
0x00010000, 0x00000000, 0x00010000, 0x00000001, 0x00010000, 0x00007ffe,
0x00010000, 0x00007fff, 0x00010000, 0x0000fffe, 0x00010000, 0x0000ffff,
0x00010000, 0x00fffffe, 0x00010000, 0x00ffffff, 0x00010000, 0x5634e2da,
0x00010000, 0xb776d5f4, 0x00010000, 0xfffffffe, 0x00010000, 0xffffffff,
0x80010000, 0x00000000, 0xb777d5f5, 0x5634e2db, 0xfff0ffff, 0xffffffff,
0xfff10000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x0000fffe, 0xffffffff, 0x0000ffff, 0x00000000, 0x0000ffff, 0xfeffffff,
0x0000ffff, 0xff000000, 0x0000ffff, 0xfffeffff, 0x0000ffff, 0xffff0000,
0x0000ffff, 0xffff7fff, 0x0000ffff, 0xffff8000, 0x0000ffff, 0xfffffffe,
0x0000ffff, 0xffffffff, 0x00010000, 0x00000000, 0x00010000, 0x00000001,
0x00010000, 0x00000002, 0x00010000, 0x00007fff, 0x00010000, 0x00008000,
0x00010000, 0x0000ffff, 0x00010000, 0x00010000, 0x00010000, 0x00ffffff,
0x00010000, 0x01000000, 0x00010000, 0x5634e2db, 0x00010000, 0xb776d5f5,
0x00010000, 0xffffffff, 0x00010001, 0x00000000, 0x0001ffff, 0xffffffff,
0x800fffff, 0xffffffff, 0xb786d5f5, 0x5634e2da, 0xffffffff, 0xfffffffe,
0xffffffff, 0xffffffff, 0x000effff, 0xfffffffe, 0x000effff, 0xffffffff,
0x000ffffe, 0xfffffffe, 0x000ffffe, 0xffffffff, 0x000fffff, 0xfefffffe,
0x000fffff, 0xfeffffff, 0x000fffff, 0xfffefffe, 0x000fffff, 0xfffeffff,
0x000fffff, 0xffff7ffe, 0x000fffff, 0xffff7fff, 0x000fffff, 0xfffffffd,
0x000fffff, 0xfffffffe, 0x000fffff, 0xffffffff, 0x00100000, 0x00000000,
0x00100000, 0x00000001, 0x00100000, 0x00007ffe, 0x00100000, 0x00007fff,
0x00100000, 0x0000fffe, 0x00100000, 0x0000ffff, 0x00100000, 0x00fffffe,
0x00100000, 0x00ffffff, 0x00100000, 0x5634e2da, 0x00100000, 0xb776d5f4,
0x00100000, 0xfffffffe, 0x00100000, 0xffffffff, 0x0010ffff, 0xfffffffe,
0x0010ffff, 0xffffffff, 0x80100000, 0x00000000, 0xb786d5f5, 0x5634e2db,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x000effff, 0xffffffff,
0x000f0000, 0x00000000, 0x000ffffe, 0xffffffff, 0x000fffff, 0x00000000,
0x000fffff, 0xfeffffff, 0x000fffff, 0xff000000, 0x000fffff, 0xfffeffff,
0x000fffff, 0xffff0000, 0x000fffff, 0xffff7fff, 0x000fffff, 0xffff8000,
0x000fffff, 0xfffffffe, 0x000fffff, 0xffffffff, 0x00100000, 0x00000000,
0x00100000, 0x00000001, 0x00100000, 0x00000002, 0x00100000, 0x00007fff,
0x00100000, 0x00008000, 0x00100000, 0x0000ffff, 0x00100000, 0x00010000,
0x00100000, 0x00ffffff, 0x00100000, 0x01000000, 0x00100000, 0x5634e2db,
0x00100000, 0xb776d5f5, 0x00100000, 0xffffffff, 0x00100001, 0x00000000,
0x0010ffff, 0xffffffff, 0x00110000, 0x00000000, 0x001fffff, 0xffffffff,
0xd634e2db, 0xb776d5f5, 0x0dabb8d1, 0x0dabb8d0, 0x5624e2db, 0xb776d5f4,
0x5624e2db, 0xb776d5f5, 0x5633e2db, 0xb776d5f4, 0x5633e2db, 0xb776d5f5,
0x5634e2da, 0xb776d5f4, 0x5634e2da, 0xb776d5f5, 0x5634e2db, 0xb676d5f4,
0x5634e2db, 0xb676d5f5, 0x5634e2db, 0xb775d5f4, 0x5634e2db, 0xb775d5f5,
0x5634e2db, 0xb77655f4, 0x5634e2db, 0xb77655f5, 0x5634e2db, 0xb776d5f3,
0x5634e2db, 0xb776d5f4, 0x5634e2db, 0xb776d5f5, 0x5634e2db, 0xb776d5f6,
0x5634e2db, 0xb776d5f7, 0x5634e2db, 0xb77755f4, 0x5634e2db, 0xb77755f5,
0x5634e2db, 0xb777d5f4, 0x5634e2db, 0xb777d5f5, 0x5634e2db, 0xb876d5f4,
0x5634e2db, 0xb876d5f5, 0x5634e2dc, 0x0dabb8d0, 0x5634e2dc, 0x6eedabea,
0x5634e2dc, 0xb776d5f4, 0x5634e2dc, 0xb776d5f5, 0x5635e2db, 0xb776d5f4,
0x5635e2db, 0xb776d5f5, 0x5644e2db, 0xb776d5f4, 0x5644e2db, 0xb776d5f5,
0xffffffff, 0xffffffff, 0x3776d5f5, 0x5634e2da, 0x7fefffff, 0xfffffffe,
0x7fefffff, 0xffffffff, 0x7ffeffff, 0xfffffffe, 0x7ffeffff, 0xffffffff,
0x7ffffffe, 0xfffffffe, 0x7ffffffe, 0xffffffff, 0x7fffffff, 0xfefffffe,
0x7fffffff, 0xfeffffff, 0x7fffffff, 0xfffefffe, 0x7fffffff, 0xfffeffff,
0x7fffffff, 0xffff7ffe, 0x7fffffff, 0xffff7fff, 0x7fffffff, 0xfffffffd,
0x7fffffff, 0xfffffffe, 0x7fffffff, 0xffffffff, 0x80000000, 0x00000000,
0x80000000, 0x00000001, 0x80000000, 0x00007ffe, 0x80000000, 0x00007fff,
0x80000000, 0x0000fffe, 0x80000000, 0x0000ffff, 0x80000000, 0x00fffffe,
0x80000000, 0x00ffffff, 0x80000000, 0x5634e2da, 0x80000000, 0xb776d5f4,
0x80000000, 0xfffffffe, 0x80000000, 0xffffffff, 0x8000ffff, 0xfffffffe,
0x8000ffff, 0xffffffff, 0x800fffff, 0xfffffffe, 0x800fffff, 0xffffffff,
0xd634e2db, 0xb776d5f4
])
var TEST_SUB_BITS = i32array([
0x00000000, 0x00000000, 0xc8892a0a, 0xa9cb1d25, 0x80100000, 0x00000001,
0x80100000, 0x00000000, 0x80010000, 0x00000001, 0x80010000, 0x00000000,
0x80000001, 0x00000001, 0x80000001, 0x00000000, 0x80000000, 0x01000001,
0x80000000, 0x01000000, 0x80000000, 0x00010001, 0x80000000, 0x00010000,
0x80000000, 0x00008001, 0x80000000, 0x00008000, 0x80000000, 0x00000002,
0x80000000, 0x00000001, 0x80000000, 0x00000000, 0x7fffffff, 0xffffffff,
0x7fffffff, 0xfffffffe, 0x7fffffff, 0xffff8001, 0x7fffffff, 0xffff8000,
0x7fffffff, 0xffff0001, 0x7fffffff, 0xffff0000, 0x7fffffff, 0xff000001,
0x7fffffff, 0xff000000, 0x7fffffff, 0xa9cb1d25, 0x7fffffff, 0x48892a0b,
0x7fffffff, 0x00000001, 0x7fffffff, 0x00000000, 0x7fff0000, 0x00000001,
0x7fff0000, 0x00000000, 0x7ff00000, 0x00000001, 0x7ff00000, 0x00000000,
0x29cb1d24, 0x48892a0b, 0x00000000, 0x00000001, 0x3776d5f5, 0x5634e2db,
0x00000000, 0x00000000, 0xb786d5f5, 0x5634e2dc, 0xb786d5f5, 0x5634e2db,
0xb777d5f5, 0x5634e2dc, 0xb777d5f5, 0x5634e2db, 0xb776d5f6, 0x5634e2dc,
0xb776d5f6, 0x5634e2db, 0xb776d5f5, 0x5734e2dc, 0xb776d5f5, 0x5734e2db,
0xb776d5f5, 0x5635e2dc, 0xb776d5f5, 0x5635e2db, 0xb776d5f5, 0x563562dc,
0xb776d5f5, 0x563562db, 0xb776d5f5, 0x5634e2dd, 0xb776d5f5, 0x5634e2dc,
0xb776d5f5, 0x5634e2db, 0xb776d5f5, 0x5634e2da, 0xb776d5f5, 0x5634e2d9,
0xb776d5f5, 0x563462dc, 0xb776d5f5, 0x563462db, 0xb776d5f5, 0x5633e2dc,
0xb776d5f5, 0x5633e2db, 0xb776d5f5, 0x5534e2dc, 0xb776d5f5, 0x5534e2db,
0xb776d5f5, 0x00000000, 0xb776d5f4, 0x9ebe0ce6, 0xb776d5f4, 0x5634e2dc,
0xb776d5f4, 0x5634e2db, 0xb775d5f5, 0x5634e2dc, 0xb775d5f5, 0x5634e2db,
0xb766d5f5, 0x5634e2dc, 0xb766d5f5, 0x5634e2db, 0x6141f319, 0x9ebe0ce6,
0x3776d5f5, 0x5634e2dc, 0x7fefffff, 0xffffffff, 0x48792a0a, 0xa9cb1d24,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xfff10000, 0x00000000,
0xfff0ffff, 0xffffffff, 0xfff00001, 0x00000000, 0xfff00000, 0xffffffff,
0xfff00000, 0x01000000, 0xfff00000, 0x00ffffff, 0xfff00000, 0x00010000,
0xfff00000, 0x0000ffff, 0xfff00000, 0x00008000, 0xfff00000, 0x00007fff,
0xfff00000, 0x00000001, 0xfff00000, 0x00000000, 0xffefffff, 0xffffffff,
0xffefffff, 0xfffffffe, 0xffefffff, 0xfffffffd, 0xffefffff, 0xffff8000,
0xffefffff, 0xffff7fff, 0xffefffff, 0xffff0000, 0xffefffff, 0xfffeffff,
0xffefffff, 0xff000000, 0xffefffff, 0xfeffffff, 0xffefffff, 0xa9cb1d24,
0xffefffff, 0x48892a0a, 0xffefffff, 0x00000000, 0xffeffffe, 0xffffffff,
0xffef0000, 0x00000000, 0xffeeffff, 0xffffffff, 0xffe00000, 0x00000000,
0xffdfffff, 0xffffffff, 0xa9bb1d24, 0x48892a0a, 0x7ff00000, 0x00000000,
0x7ff00000, 0x00000000, 0x48792a0a, 0xa9cb1d25, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xfff10000, 0x00000001, 0xfff10000, 0x00000000,
0xfff00001, 0x00000001, 0xfff00001, 0x00000000, 0xfff00000, 0x01000001,
0xfff00000, 0x01000000, 0xfff00000, 0x00010001, 0xfff00000, 0x00010000,
0xfff00000, 0x00008001, 0xfff00000, 0x00008000, 0xfff00000, 0x00000002,
0xfff00000, 0x00000001, 0xfff00000, 0x00000000, 0xffefffff, 0xffffffff,
0xffefffff, 0xfffffffe, 0xffefffff, 0xffff8001, 0xffefffff, 0xffff8000,
0xffefffff, 0xffff0001, 0xffefffff, 0xffff0000, 0xffefffff, 0xff000001,
0xffefffff, 0xff000000, 0xffefffff, 0xa9cb1d25, 0xffefffff, 0x48892a0b,
0xffefffff, 0x00000001, 0xffefffff, 0x00000000, 0xffef0000, 0x00000001,
0xffef0000, 0x00000000, 0xffe00000, 0x00000001, 0xffe00000, 0x00000000,
0xa9bb1d24, 0x48892a0b, 0x7ff00000, 0x00000001, 0x7ffeffff, 0xffffffff,
0x48882a0a, 0xa9cb1d24, 0x000f0000, 0x00000000, 0x000effff, 0xffffffff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffff0001, 0x00000000,
0xffff0000, 0xffffffff, 0xffff0000, 0x01000000, 0xffff0000, 0x00ffffff,
0xffff0000, 0x00010000, 0xffff0000, 0x0000ffff, 0xffff0000, 0x00008000,
0xffff0000, 0x00007fff, 0xffff0000, 0x00000001, 0xffff0000, 0x00000000,
0xfffeffff, 0xffffffff, 0xfffeffff, 0xfffffffe, 0xfffeffff, 0xfffffffd,
0xfffeffff, 0xffff8000, 0xfffeffff, 0xffff7fff, 0xfffeffff, 0xffff0000,
0xfffeffff, 0xfffeffff, 0xfffeffff, 0xff000000, 0xfffeffff, 0xfeffffff,
0xfffeffff, 0xa9cb1d24, 0xfffeffff, 0x48892a0a, 0xfffeffff, 0x00000000,
0xfffefffe, 0xffffffff, 0xfffe0000, 0x00000000, 0xfffdffff, 0xffffffff,
0xffef0000, 0x00000000, 0xffeeffff, 0xffffffff, 0xa9ca1d24, 0x48892a0a,
0x7fff0000, 0x00000000, 0x7fff0000, 0x00000000, 0x48882a0a, 0xa9cb1d25,
0x000f0000, 0x00000001, 0x000f0000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffff0001, 0x00000001, 0xffff0001, 0x00000000,
0xffff0000, 0x01000001, 0xffff0000, 0x01000000, 0xffff0000, 0x00010001,
0xffff0000, 0x00010000, 0xffff0000, 0x00008001, 0xffff0000, 0x00008000,
0xffff0000, 0x00000002, 0xffff0000, 0x00000001, 0xffff0000, 0x00000000,
0xfffeffff, 0xffffffff, 0xfffeffff, 0xfffffffe, 0xfffeffff, 0xffff8001,
0xfffeffff, 0xffff8000, 0xfffeffff, 0xffff0001, 0xfffeffff, 0xffff0000,
0xfffeffff, 0xff000001, 0xfffeffff, 0xff000000, 0xfffeffff, 0xa9cb1d25,
0xfffeffff, 0x48892a0b, 0xfffeffff, 0x00000001, 0xfffeffff, 0x00000000,
0xfffe0000, 0x00000001, 0xfffe0000, 0x00000000, 0xffef0000, 0x00000001,
0xffef0000, 0x00000000, 0xa9ca1d24, 0x48892a0b, 0x7fff0000, 0x00000001,
0x7ffffffe, 0xffffffff, 0x48892a09, 0xa9cb1d24, 0x000fffff, 0x00000000,
0x000ffffe, 0xffffffff, 0x0000ffff, 0x00000000, 0x0000fffe, 0xffffffff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0x01000000,
0xffffffff, 0x00ffffff, 0xffffffff, 0x00010000, 0xffffffff, 0x0000ffff,
0xffffffff, 0x00008000, 0xffffffff, 0x00007fff, 0xffffffff, 0x00000001,
0xffffffff, 0x00000000, 0xfffffffe, 0xffffffff, 0xfffffffe, 0xfffffffe,
0xfffffffe, 0xfffffffd, 0xfffffffe, 0xffff8000, 0xfffffffe, 0xffff7fff,
0xfffffffe, 0xffff0000, 0xfffffffe, 0xfffeffff, 0xfffffffe, 0xff000000,
0xfffffffe, 0xfeffffff, 0xfffffffe, 0xa9cb1d24, 0xfffffffe, 0x48892a0a,
0xfffffffe, 0x00000000, 0xfffffffd, 0xffffffff, 0xfffeffff, 0x00000000,
0xfffefffe, 0xffffffff, 0xffefffff, 0x00000000, 0xffeffffe, 0xffffffff,
0xa9cb1d23, 0x48892a0a, 0x7fffffff, 0x00000000, 0x7fffffff, 0x00000000,
0x48892a09, 0xa9cb1d25, 0x000fffff, 0x00000001, 0x000fffff, 0x00000000,
0x0000ffff, 0x00000001, 0x0000ffff, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0x01000001, 0xffffffff, 0x01000000,
0xffffffff, 0x00010001, 0xffffffff, 0x00010000, 0xffffffff, 0x00008001,
0xffffffff, 0x00008000, 0xffffffff, 0x00000002, 0xffffffff, 0x00000001,
0xffffffff, 0x00000000, 0xfffffffe, 0xffffffff, 0xfffffffe, 0xfffffffe,
0xfffffffe, 0xffff8001, 0xfffffffe, 0xffff8000, 0xfffffffe, 0xffff0001,
0xfffffffe, 0xffff0000, 0xfffffffe, 0xff000001, 0xfffffffe, 0xff000000,
0xfffffffe, 0xa9cb1d25, 0xfffffffe, 0x48892a0b, 0xfffffffe, 0x00000001,
0xfffffffe, 0x00000000, 0xfffeffff, 0x00000001, 0xfffeffff, 0x00000000,
0xffefffff, 0x00000001, 0xffefffff, 0x00000000, 0xa9cb1d23, 0x48892a0b,
0x7fffffff, 0x00000001, 0x7fffffff, 0xfeffffff, 0x48892a0a, 0xa8cb1d24,
0x000fffff, 0xff000000, 0x000fffff, 0xfeffffff, 0x0000ffff, 0xff000000,
0x0000ffff, 0xfeffffff, 0x00000000, 0xff000000, 0x00000000, 0xfeffffff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xff010000,
0xffffffff, 0xff00ffff, 0xffffffff, 0xff008000, 0xffffffff, 0xff007fff,
0xffffffff, 0xff000001, 0xffffffff, 0xff000000, 0xffffffff, 0xfeffffff,
0xffffffff, 0xfefffffe, 0xffffffff, 0xfefffffd, 0xffffffff, 0xfeff8000,
0xffffffff, 0xfeff7fff, 0xffffffff, 0xfeff0000, 0xffffffff, 0xfefeffff,
0xffffffff, 0xfe000000, 0xffffffff, 0xfdffffff, 0xffffffff, 0xa8cb1d24,
0xffffffff, 0x47892a0a, 0xfffffffe, 0xff000000, 0xfffffffe, 0xfeffffff,
0xfffeffff, 0xff000000, 0xfffeffff, 0xfeffffff, 0xffefffff, 0xff000000,
0xffefffff, 0xfeffffff, 0xa9cb1d24, 0x47892a0a, 0x7fffffff, 0xff000000,
0x7fffffff, 0xff000000, 0x48892a0a, 0xa8cb1d25, 0x000fffff, 0xff000001,
0x000fffff, 0xff000000, 0x0000ffff, 0xff000001, 0x0000ffff, 0xff000000,
0x00000000, 0xff000001, 0x00000000, 0xff000000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xff010001, 0xffffffff, 0xff010000,
0xffffffff, 0xff008001, 0xffffffff, 0xff008000, 0xffffffff, 0xff000002,
0xffffffff, 0xff000001, 0xffffffff, 0xff000000, 0xffffffff, 0xfeffffff,
0xffffffff, 0xfefffffe, 0xffffffff, 0xfeff8001, 0xffffffff, 0xfeff8000,
0xffffffff, 0xfeff0001, 0xffffffff, 0xfeff0000, 0xffffffff, 0xfe000001,
0xffffffff, 0xfe000000, 0xffffffff, 0xa8cb1d25, 0xffffffff, 0x47892a0b,
0xfffffffe, 0xff000001, 0xfffffffe, 0xff000000, 0xfffeffff, 0xff000001,
0xfffeffff, 0xff000000, 0xffefffff, 0xff000001, 0xffefffff, 0xff000000,
0xa9cb1d24, 0x47892a0b, 0x7fffffff, 0xff000001, 0x7fffffff, 0xfffeffff,
0x48892a0a, 0xa9ca1d24, 0x000fffff, 0xffff0000, 0x000fffff, 0xfffeffff,
0x0000ffff, 0xffff0000, 0x0000ffff, 0xfffeffff, 0x00000000, 0xffff0000,
0x00000000, 0xfffeffff, 0x00000000, 0x00ff0000, 0x00000000, 0x00feffff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffff8000,
0xffffffff, 0xffff7fff, 0xffffffff, 0xffff0001, 0xffffffff, 0xffff0000,
0xffffffff, 0xfffeffff, 0xffffffff, 0xfffefffe, 0xffffffff, 0xfffefffd,
0xffffffff, 0xfffe8000, 0xffffffff, 0xfffe7fff, 0xffffffff, 0xfffe0000,
0xffffffff, 0xfffdffff, 0xffffffff, 0xfeff0000, 0xffffffff, 0xfefeffff,
0xffffffff, 0xa9ca1d24, 0xffffffff, 0x48882a0a, 0xfffffffe, 0xffff0000,
0xfffffffe, 0xfffeffff, 0xfffeffff, 0xffff0000, 0xfffeffff, 0xfffeffff,
0xffefffff, 0xffff0000, 0xffefffff, 0xfffeffff, 0xa9cb1d24, 0x48882a0a,
0x7fffffff, 0xffff0000, 0x7fffffff, 0xffff0000, 0x48892a0a, 0xa9ca1d25,
0x000fffff, 0xffff0001, 0x000fffff, 0xffff0000, 0x0000ffff, 0xffff0001,
0x0000ffff, 0xffff0000, 0x00000000, 0xffff0001, 0x00000000, 0xffff0000,
0x00000000, 0x00ff0001, 0x00000000, 0x00ff0000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xffff8001, 0xffffffff, 0xffff8000,
0xffffffff, 0xffff0002, 0xffffffff, 0xffff0001, 0xffffffff, 0xffff0000,
0xffffffff, 0xfffeffff, 0xffffffff, 0xfffefffe, 0xffffffff, 0xfffe8001,
0xffffffff, 0xfffe8000, 0xffffffff, 0xfffe0001, 0xffffffff, 0xfffe0000,
0xffffffff, 0xfeff0001, 0xffffffff, 0xfeff0000, 0xffffffff, 0xa9ca1d25,
0xffffffff, 0x48882a0b, 0xfffffffe, 0xffff0001, 0xfffffffe, 0xffff0000,
0xfffeffff, 0xffff0001, 0xfffeffff, 0xffff0000, 0xffefffff, 0xffff0001,
0xffefffff, 0xffff0000, 0xa9cb1d24, 0x48882a0b, 0x7fffffff, 0xffff0001,
0x7fffffff, 0xffff7fff, 0x48892a0a, 0xa9ca9d24, 0x000fffff, 0xffff8000,
0x000fffff, 0xffff7fff, 0x0000ffff, 0xffff8000, 0x0000ffff, 0xffff7fff,
0x00000000, 0xffff8000, 0x00000000, 0xffff7fff, 0x00000000, 0x00ff8000,
0x00000000, 0x00ff7fff, 0x00000000, 0x00008000, 0x00000000, 0x00007fff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffff8001,
0xffffffff, 0xffff8000, 0xffffffff, 0xffff7fff, 0xffffffff, 0xffff7ffe,
0xffffffff, 0xffff7ffd, 0xffffffff, 0xffff0000, 0xffffffff, 0xfffeffff,
0xffffffff, 0xfffe8000, 0xffffffff, 0xfffe7fff, 0xffffffff, 0xfeff8000,
0xffffffff, 0xfeff7fff, 0xffffffff, 0xa9ca9d24, 0xffffffff, 0x4888aa0a,
0xfffffffe, 0xffff8000, 0xfffffffe, 0xffff7fff, 0xfffeffff, 0xffff8000,
0xfffeffff, 0xffff7fff, 0xffefffff, 0xffff8000, 0xffefffff, 0xffff7fff,
0xa9cb1d24, 0x4888aa0a, 0x7fffffff, 0xffff8000, 0x7fffffff, 0xffff8000,
0x48892a0a, 0xa9ca9d25, 0x000fffff, 0xffff8001, 0x000fffff, 0xffff8000,
0x0000ffff, 0xffff8001, 0x0000ffff, 0xffff8000, 0x00000000, 0xffff8001,
0x00000000, 0xffff8000, 0x00000000, 0x00ff8001, 0x00000000, 0x00ff8000,
0x00000000, 0x00008001, 0x00000000, 0x00008000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xffff8002, 0xffffffff, 0xffff8001,
0xffffffff, 0xffff8000, 0xffffffff, 0xffff7fff, 0xffffffff, 0xffff7ffe,
0xffffffff, 0xffff0001, 0xffffffff, 0xffff0000, 0xffffffff, 0xfffe8001,
0xffffffff, 0xfffe8000, 0xffffffff, 0xfeff8001, 0xffffffff, 0xfeff8000,
0xffffffff, 0xa9ca9d25, 0xffffffff, 0x4888aa0b, 0xfffffffe, 0xffff8001,
0xfffffffe, 0xffff8000, 0xfffeffff, 0xffff8001, 0xfffeffff, 0xffff8000,
0xffefffff, 0xffff8001, 0xffefffff, 0xffff8000, 0xa9cb1d24, 0x4888aa0b,
0x7fffffff, 0xffff8001, 0x7fffffff, 0xfffffffe, 0x48892a0a, 0xa9cb1d23,
0x000fffff, 0xffffffff, 0x000fffff, 0xfffffffe, 0x0000ffff, 0xffffffff,
0x0000ffff, 0xfffffffe, 0x00000000, 0xffffffff, 0x00000000, 0xfffffffe,
0x00000000, 0x00ffffff, 0x00000000, 0x00fffffe, 0x00000000, 0x0000ffff,
0x00000000, 0x0000fffe, 0x00000000, 0x00007fff, 0x00000000, 0x00007ffe,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xfffffffe,
0xffffffff, 0xfffffffd, 0xffffffff, 0xfffffffc, 0xffffffff, 0xffff7fff,
0xffffffff, 0xffff7ffe, 0xffffffff, 0xfffeffff, 0xffffffff, 0xfffefffe,
0xffffffff, 0xfeffffff, 0xffffffff, 0xfefffffe, 0xffffffff, 0xa9cb1d23,
0xffffffff, 0x48892a09, 0xfffffffe, 0xffffffff, 0xfffffffe, 0xfffffffe,
0xfffeffff, 0xffffffff, 0xfffeffff, 0xfffffffe, 0xffefffff, 0xffffffff,
0xffefffff, 0xfffffffe, 0xa9cb1d24, 0x48892a09, 0x7fffffff, 0xffffffff,
0x7fffffff, 0xffffffff, 0x48892a0a, 0xa9cb1d24, 0x00100000, 0x00000000,
0x000fffff, 0xffffffff, 0x00010000, 0x00000000, 0x0000ffff, 0xffffffff,
0x00000001, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x01000000,
0x00000000, 0x00ffffff, 0x00000000, 0x00010000, 0x00000000, 0x0000ffff,
0x00000000, 0x00008000, 0x00000000, 0x00007fff, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xfffffffe,
0xffffffff, 0xfffffffd, 0xffffffff, 0xffff8000, 0xffffffff, 0xffff7fff,
0xffffffff, 0xffff0000, 0xffffffff, 0xfffeffff, 0xffffffff, 0xff000000,
0xffffffff, 0xfeffffff, 0xffffffff, 0xa9cb1d24, 0xffffffff, 0x48892a0a,
0xffffffff, 0x00000000, 0xfffffffe, 0xffffffff, 0xffff0000, 0x00000000,
0xfffeffff, 0xffffffff, 0xfff00000, 0x00000000, 0xffefffff, 0xffffffff,
0xa9cb1d24, 0x48892a0a, 0x80000000, 0x00000000, 0x80000000, 0x00000000,
0x48892a0a, 0xa9cb1d25, 0x00100000, 0x00000001, 0x00100000, 0x00000000,
0x00010000, 0x00000001, 0x00010000, 0x00000000, 0x00000001, 0x00000001,
0x00000001, 0x00000000, 0x00000000, 0x01000001, 0x00000000, 0x01000000,
0x00000000, 0x00010001, 0x00000000, 0x00010000, 0x00000000, 0x00008001,
0x00000000, 0x00008000, 0x00000000, 0x00000002, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xfffffffe,
0xffffffff, 0xffff8001, 0xffffffff, 0xffff8000, 0xffffffff, 0xffff0001,
0xffffffff, 0xffff0000, 0xffffffff, 0xff000001, 0xffffffff, 0xff000000,
0xffffffff, 0xa9cb1d25, 0xffffffff, 0x48892a0b, 0xffffffff, 0x00000001,
0xffffffff, 0x00000000, 0xffff0000, 0x00000001, 0xffff0000, 0x00000000,
0xfff00000, 0x00000001, 0xfff00000, 0x00000000, 0xa9cb1d24, 0x48892a0b,
0x80000000, 0x00000001, 0x80000000, 0x00000001, 0x48892a0a, 0xa9cb1d26,
0x00100000, 0x00000002, 0x00100000, 0x00000001, 0x00010000, 0x00000002,
0x00010000, 0x00000001, 0x00000001, 0x00000002, 0x00000001, 0x00000001,
0x00000000, 0x01000002, 0x00000000, 0x01000001, 0x00000000, 0x00010002,
0x00000000, 0x00010001, 0x00000000, 0x00008002, 0x00000000, 0x00008001,
0x00000000, 0x00000003, 0x00000000, 0x00000002, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffff8002,
0xffffffff, 0xffff8001, 0xffffffff, 0xffff0002, 0xffffffff, 0xffff0001,
0xffffffff, 0xff000002, 0xffffffff, 0xff000001, 0xffffffff, 0xa9cb1d26,
0xffffffff, 0x48892a0c, 0xffffffff, 0x00000002, 0xffffffff, 0x00000001,
0xffff0000, 0x00000002, 0xffff0000, 0x00000001, 0xfff00000, 0x00000002,
0xfff00000, 0x00000001, 0xa9cb1d24, 0x48892a0c, 0x80000000, 0x00000002,
0x80000000, 0x00000002, 0x48892a0a, 0xa9cb1d27, 0x00100000, 0x00000003,
0x00100000, 0x00000002, 0x00010000, 0x00000003, 0x00010000, 0x00000002,
0x00000001, 0x00000003, 0x00000001, 0x00000002, 0x00000000, 0x01000003,
0x00000000, 0x01000002, 0x00000000, 0x00010003, 0x00000000, 0x00010002,
0x00000000, 0x00008003, 0x00000000, 0x00008002, 0x00000000, 0x00000004,
0x00000000, 0x00000003, 0x00000000, 0x00000002, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xffff8003, 0xffffffff, 0xffff8002,
0xffffffff, 0xffff0003, 0xffffffff, 0xffff0002, 0xffffffff, 0xff000003,
0xffffffff, 0xff000002, 0xffffffff, 0xa9cb1d27, 0xffffffff, 0x48892a0d,
0xffffffff, 0x00000003, 0xffffffff, 0x00000002, 0xffff0000, 0x00000003,
0xffff0000, 0x00000002, 0xfff00000, 0x00000003, 0xfff00000, 0x00000002,
0xa9cb1d24, 0x48892a0d, 0x80000000, 0x00000003, 0x80000000, 0x00007fff,
0x48892a0a, 0xa9cb9d24, 0x00100000, 0x00008000, 0x00100000, 0x00007fff,
0x00010000, 0x00008000, 0x00010000, 0x00007fff, 0x00000001, 0x00008000,
0x00000001, 0x00007fff, 0x00000000, 0x01008000, 0x00000000, 0x01007fff,
0x00000000, 0x00018000, 0x00000000, 0x00017fff, 0x00000000, 0x00010000,
0x00000000, 0x0000ffff, 0x00000000, 0x00008001, 0x00000000, 0x00008000,
0x00000000, 0x00007fff, 0x00000000, 0x00007ffe, 0x00000000, 0x00007ffd,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffff8000,
0xffffffff, 0xffff7fff, 0xffffffff, 0xff008000, 0xffffffff, 0xff007fff,
0xffffffff, 0xa9cb9d24, 0xffffffff, 0x4889aa0a, 0xffffffff, 0x00008000,
0xffffffff, 0x00007fff, 0xffff0000, 0x00008000, 0xffff0000, 0x00007fff,
0xfff00000, 0x00008000, 0xfff00000, 0x00007fff, 0xa9cb1d24, 0x4889aa0a,
0x80000000, 0x00008000, 0x80000000, 0x00008000, 0x48892a0a, 0xa9cb9d25,
0x00100000, 0x00008001, 0x00100000, 0x00008000, 0x00010000, 0x00008001,
0x00010000, 0x00008000, 0x00000001, 0x00008001, 0x00000001, 0x00008000,
0x00000000, 0x01008001, 0x00000000, 0x01008000, 0x00000000, 0x00018001,
0x00000000, 0x00018000, 0x00000000, 0x00010001, 0x00000000, 0x00010000,
0x00000000, 0x00008002, 0x00000000, 0x00008001, 0x00000000, 0x00008000,
0x00000000, 0x00007fff, 0x00000000, 0x00007ffe, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xffff8001, 0xffffffff, 0xffff8000,
0xffffffff, 0xff008001, 0xffffffff, 0xff008000, 0xffffffff, 0xa9cb9d25,
0xffffffff, 0x4889aa0b, 0xffffffff, 0x00008001, 0xffffffff, 0x00008000,
0xffff0000, 0x00008001, 0xffff0000, 0x00008000, 0xfff00000, 0x00008001,
0xfff00000, 0x00008000, 0xa9cb1d24, 0x4889aa0b, 0x80000000, 0x00008001,
0x80000000, 0x0000ffff, 0x48892a0a, 0xa9cc1d24, 0x00100000, 0x00010000,
0x00100000, 0x0000ffff, 0x00010000, 0x00010000, 0x00010000, 0x0000ffff,
0x00000001, 0x00010000, 0x00000001, 0x0000ffff, 0x00000000, 0x01010000,
0x00000000, 0x0100ffff, 0x00000000, 0x00020000, 0x00000000, 0x0001ffff,
0x00000000, 0x00018000, 0x00000000, 0x00017fff, 0x00000000, 0x00010001,
0x00000000, 0x00010000, 0x00000000, 0x0000ffff, 0x00000000, 0x0000fffe,
0x00000000, 0x0000fffd, 0x00000000, 0x00008000, 0x00000000, 0x00007fff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xff010000,
0xffffffff, 0xff00ffff, 0xffffffff, 0xa9cc1d24, 0xffffffff, 0x488a2a0a,
0xffffffff, 0x00010000, 0xffffffff, 0x0000ffff, 0xffff0000, 0x00010000,
0xffff0000, 0x0000ffff, 0xfff00000, 0x00010000, 0xfff00000, 0x0000ffff,
0xa9cb1d24, 0x488a2a0a, 0x80000000, 0x00010000, 0x80000000, 0x00010000,
0x48892a0a, 0xa9cc1d25, 0x00100000, 0x00010001, 0x00100000, 0x00010000,
0x00010000, 0x00010001, 0x00010000, 0x00010000, 0x00000001, 0x00010001,
0x00000001, 0x00010000, 0x00000000, 0x01010001, 0x00000000, 0x01010000,
0x00000000, 0x00020001, 0x00000000, 0x00020000, 0x00000000, 0x00018001,
0x00000000, 0x00018000, 0x00000000, 0x00010002, 0x00000000, 0x00010001,
0x00000000, 0x00010000, 0x00000000, 0x0000ffff, 0x00000000, 0x0000fffe,
0x00000000, 0x00008001, 0x00000000, 0x00008000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xff010001, 0xffffffff, 0xff010000,
0xffffffff, 0xa9cc1d25, 0xffffffff, 0x488a2a0b, 0xffffffff, 0x00010001,
0xffffffff, 0x00010000, 0xffff0000, 0x00010001, 0xffff0000, 0x00010000,
0xfff00000, 0x00010001, 0xfff00000, 0x00010000, 0xa9cb1d24, 0x488a2a0b,
0x80000000, 0x00010001, 0x80000000, 0x00ffffff, 0x48892a0a, 0xaacb1d24,
0x00100000, 0x01000000, 0x00100000, 0x00ffffff, 0x00010000, 0x01000000,
0x00010000, 0x00ffffff, 0x00000001, 0x01000000, 0x00000001, 0x00ffffff,
0x00000000, 0x02000000, 0x00000000, 0x01ffffff, 0x00000000, 0x01010000,
0x00000000, 0x0100ffff, 0x00000000, 0x01008000, 0x00000000, 0x01007fff,
0x00000000, 0x01000001, 0x00000000, 0x01000000, 0x00000000, 0x00ffffff,
0x00000000, 0x00fffffe, 0x00000000, 0x00fffffd, 0x00000000, 0x00ff8000,
0x00000000, 0x00ff7fff, 0x00000000, 0x00ff0000, 0x00000000, 0x00feffff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xaacb1d24,
0xffffffff, 0x49892a0a, 0xffffffff, 0x01000000, 0xffffffff, 0x00ffffff,
0xffff0000, 0x01000000, 0xffff0000, 0x00ffffff, 0xfff00000, 0x01000000,
0xfff00000, 0x00ffffff, 0xa9cb1d24, 0x49892a0a, 0x80000000, 0x01000000,
0x80000000, 0x01000000, 0x48892a0a, 0xaacb1d25, 0x00100000, 0x01000001,
0x00100000, 0x01000000, 0x00010000, 0x01000001, 0x00010000, 0x01000000,
0x00000001, 0x01000001, 0x00000001, 0x01000000, 0x00000000, 0x02000001,
0x00000000, 0x02000000, 0x00000000, 0x01010001, 0x00000000, 0x01010000,
0x00000000, 0x01008001, 0x00000000, 0x01008000, 0x00000000, 0x01000002,
0x00000000, 0x01000001, 0x00000000, 0x01000000, 0x00000000, 0x00ffffff,
0x00000000, 0x00fffffe, 0x00000000, 0x00ff8001, 0x00000000, 0x00ff8000,
0x00000000, 0x00ff0001, 0x00000000, 0x00ff0000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffffffff, 0xaacb1d25, 0xffffffff, 0x49892a0b,
0xffffffff, 0x01000001, 0xffffffff, 0x01000000, 0xffff0000, 0x01000001,
0xffff0000, 0x01000000, 0xfff00000, 0x01000001, 0xfff00000, 0x01000000,
0xa9cb1d24, 0x49892a0b, 0x80000000, 0x01000001, 0x80000000, 0x5634e2db,
0x48892a0b, 0x00000000, 0x00100000, 0x5634e2dc, 0x00100000, 0x5634e2db,
0x00010000, 0x5634e2dc, 0x00010000, 0x5634e2db, 0x00000001, 0x5634e2dc,
0x00000001, 0x5634e2db, 0x00000000, 0x5734e2dc, 0x00000000, 0x5734e2db,
0x00000000, 0x5635e2dc, 0x00000000, 0x5635e2db, 0x00000000, 0x563562dc,
0x00000000, 0x563562db, 0x00000000, 0x5634e2dd, 0x00000000, 0x5634e2dc,
0x00000000, 0x5634e2db, 0x00000000, 0x5634e2da, 0x00000000, 0x5634e2d9,
0x00000000, 0x563462dc, 0x00000000, 0x563462db, 0x00000000, 0x5633e2dc,
0x00000000, 0x5633e2db, 0x00000000, 0x5534e2dc, 0x00000000, 0x5534e2db,
0x00000000, 0x00000000, 0xffffffff, 0x9ebe0ce6, 0xffffffff, 0x5634e2dc,
0xffffffff, 0x5634e2db, 0xffff0000, 0x5634e2dc, 0xffff0000, 0x5634e2db,
0xfff00000, 0x5634e2dc, 0xfff00000, 0x5634e2db, 0xa9cb1d24, 0x9ebe0ce6,
0x80000000, 0x5634e2dc, 0x80000000, 0xb776d5f5, 0x48892a0b, 0x6141f31a,
0x00100000, 0xb776d5f6, 0x00100000, 0xb776d5f5, 0x00010000, 0xb776d5f6,
0x00010000, 0xb776d5f5, 0x00000001, 0xb776d5f6, 0x00000001, 0xb776d5f5,
0x00000000, 0xb876d5f6, 0x00000000, 0xb876d5f5, 0x00000000, 0xb777d5f6,
0x00000000, 0xb777d5f5, 0x00000000, 0xb77755f6, 0x00000000, 0xb77755f5,
0x00000000, 0xb776d5f7, 0x00000000, 0xb776d5f6, 0x00000000, 0xb776d5f5,
0x00000000, 0xb776d5f4, 0x00000000, 0xb776d5f3, 0x00000000, 0xb77655f6,
0x00000000, 0xb77655f5, 0x00000000, 0xb775d5f6, 0x00000000, 0xb775d5f5,
0x00000000, 0xb676d5f6, 0x00000000, 0xb676d5f5, 0x00000000, 0x6141f31a,
0x00000000, 0x00000000, 0xffffffff, 0xb776d5f6, 0xffffffff, 0xb776d5f5,
0xffff0000, 0xb776d5f6, 0xffff0000, 0xb776d5f5, 0xfff00000, 0xb776d5f6,
0xfff00000, 0xb776d5f5, 0xa9cb1d25, 0x00000000, 0x80000000, 0xb776d5f6,
0x80000000, 0xffffffff, 0x48892a0b, 0xa9cb1d24, 0x00100001, 0x00000000,
0x00100000, 0xffffffff, 0x00010001, 0x00000000, 0x00010000, 0xffffffff,
0x00000002, 0x00000000, 0x00000001, 0xffffffff, 0x00000001, 0x01000000,
0x00000001, 0x00ffffff, 0x00000001, 0x00010000, 0x00000001, 0x0000ffff,
0x00000001, 0x00008000, 0x00000001, 0x00007fff, 0x00000001, 0x00000001,
0x00000001, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0xfffffffe,
0x00000000, 0xfffffffd, 0x00000000, 0xffff8000, 0x00000000, 0xffff7fff,
0x00000000, 0xffff0000, 0x00000000, 0xfffeffff, 0x00000000, 0xff000000,
0x00000000, 0xfeffffff, 0x00000000, 0xa9cb1d24, 0x00000000, 0x48892a0a,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffff0001, 0x00000000,
0xffff0000, 0xffffffff, 0xfff00001, 0x00000000, 0xfff00000, 0xffffffff,
0xa9cb1d25, 0x48892a0a, 0x80000001, 0x00000000, 0x80000001, 0x00000000,
0x48892a0b, 0xa9cb1d25, 0x00100001, 0x00000001, 0x00100001, 0x00000000,
0x00010001, 0x00000001, 0x00010001, 0x00000000, 0x00000002, 0x00000001,
0x00000002, 0x00000000, 0x00000001, 0x01000001, 0x00000001, 0x01000000,
0x00000001, 0x00010001, 0x00000001, 0x00010000, 0x00000001, 0x00008001,
0x00000001, 0x00008000, 0x00000001, 0x00000002, 0x00000001, 0x00000001,
0x00000001, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0xfffffffe,
0x00000000, 0xffff8001, 0x00000000, 0xffff8000, 0x00000000, 0xffff0001,
0x00000000, 0xffff0000, 0x00000000, 0xff000001, 0x00000000, 0xff000000,
0x00000000, 0xa9cb1d25, 0x00000000, 0x48892a0b, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xffff0001, 0x00000001, 0xffff0001, 0x00000000,
0xfff00001, 0x00000001, 0xfff00001, 0x00000000, 0xa9cb1d25, 0x48892a0b,
0x80000001, 0x00000001, 0x8000ffff, 0xffffffff, 0x488a2a0a, 0xa9cb1d24,
0x00110000, 0x00000000, 0x0010ffff, 0xffffffff, 0x00020000, 0x00000000,
0x0001ffff, 0xffffffff, 0x00010001, 0x00000000, 0x00010000, 0xffffffff,
0x00010000, 0x01000000, 0x00010000, 0x00ffffff, 0x00010000, 0x00010000,
0x00010000, 0x0000ffff, 0x00010000, 0x00008000, 0x00010000, 0x00007fff,
0x00010000, 0x00000001, 0x00010000, 0x00000000, 0x0000ffff, 0xffffffff,
0x0000ffff, 0xfffffffe, 0x0000ffff, 0xfffffffd, 0x0000ffff, 0xffff8000,
0x0000ffff, 0xffff7fff, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xfffeffff,
0x0000ffff, 0xff000000, 0x0000ffff, 0xfeffffff, 0x0000ffff, 0xa9cb1d24,
0x0000ffff, 0x48892a0a, 0x0000ffff, 0x00000000, 0x0000fffe, 0xffffffff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xfff10000, 0x00000000,
0xfff0ffff, 0xffffffff, 0xa9cc1d24, 0x48892a0a, 0x80010000, 0x00000000,
0x80010000, 0x00000000, 0x488a2a0a, 0xa9cb1d25, 0x00110000, 0x00000001,
0x00110000, 0x00000000, 0x00020000, 0x00000001, 0x00020000, 0x00000000,
0x00010001, 0x00000001, 0x00010001, 0x00000000, 0x00010000, 0x01000001,
0x00010000, 0x01000000, 0x00010000, 0x00010001, 0x00010000, 0x00010000,
0x00010000, 0x00008001, 0x00010000, 0x00008000, 0x00010000, 0x00000002,
0x00010000, 0x00000001, 0x00010000, 0x00000000, 0x0000ffff, 0xffffffff,
0x0000ffff, 0xfffffffe, 0x0000ffff, 0xffff8001, 0x0000ffff, 0xffff8000,
0x0000ffff, 0xffff0001, 0x0000ffff, 0xffff0000, 0x0000ffff, 0xff000001,
0x0000ffff, 0xff000000, 0x0000ffff, 0xa9cb1d25, 0x0000ffff, 0x48892a0b,
0x0000ffff, 0x00000001, 0x0000ffff, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xfff10000, 0x00000001, 0xfff10000, 0x00000000,
0xa9cc1d24, 0x48892a0b, 0x80010000, 0x00000001, 0x800fffff, 0xffffffff,
0x48992a0a, 0xa9cb1d24, 0x00200000, 0x00000000, 0x001fffff, 0xffffffff,
0x00110000, 0x00000000, 0x0010ffff, 0xffffffff, 0x00100001, 0x00000000,
0x00100000, 0xffffffff, 0x00100000, 0x01000000, 0x00100000, 0x00ffffff,
0x00100000, 0x00010000, 0x00100000, 0x0000ffff, 0x00100000, 0x00008000,
0x00100000, 0x00007fff, 0x00100000, 0x00000001, 0x00100000, 0x00000000,
0x000fffff, 0xffffffff, 0x000fffff, 0xfffffffe, 0x000fffff, 0xfffffffd,
0x000fffff, 0xffff8000, 0x000fffff, 0xffff7fff, 0x000fffff, 0xffff0000,
0x000fffff, 0xfffeffff, 0x000fffff, 0xff000000, 0x000fffff, 0xfeffffff,
0x000fffff, 0xa9cb1d24, 0x000fffff, 0x48892a0a, 0x000fffff, 0x00000000,
0x000ffffe, 0xffffffff, 0x000f0000, 0x00000000, 0x000effff, 0xffffffff,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xa9db1d24, 0x48892a0a,
0x80100000, 0x00000000, 0x80100000, 0x00000000, 0x48992a0a, 0xa9cb1d25,
0x00200000, 0x00000001, 0x00200000, 0x00000000, 0x00110000, 0x00000001,
0x00110000, 0x00000000, 0x00100001, 0x00000001, 0x00100001, 0x00000000,
0x00100000, 0x01000001, 0x00100000, 0x01000000, 0x00100000, 0x00010001,
0x00100000, 0x00010000, 0x00100000, 0x00008001, 0x00100000, 0x00008000,
0x00100000, 0x00000002, 0x00100000, 0x00000001, 0x00100000, 0x00000000,
0x000fffff, 0xffffffff, 0x000fffff, 0xfffffffe, 0x000fffff, 0xffff8001,
0x000fffff, 0xffff8000, 0x000fffff, 0xffff0001, 0x000fffff, 0xffff0000,
0x000fffff, 0xff000001, 0x000fffff, 0xff000000, 0x000fffff, 0xa9cb1d25,
0x000fffff, 0x48892a0b, 0x000fffff, 0x00000001, 0x000fffff, 0x00000000,
0x000f0000, 0x00000001, 0x000f0000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0xa9db1d24, 0x48892a0b, 0x80100000, 0x00000001,
0xd634e2db, 0xb776d5f5, 0x9ebe0ce6, 0x6141f31a, 0x5644e2db, 0xb776d5f6,
0x5644e2db, 0xb776d5f5, 0x5635e2db, 0xb776d5f6, 0x5635e2db, 0xb776d5f5,
0x5634e2dc, 0xb776d5f6, 0x5634e2dc, 0xb776d5f5, 0x5634e2db, 0xb876d5f6,
0x5634e2db, 0xb876d5f5, 0x5634e2db, 0xb777d5f6, 0x5634e2db, 0xb777d5f5,
0x5634e2db, 0xb77755f6, 0x5634e2db, 0xb77755f5, 0x5634e2db, 0xb776d5f7,
0x5634e2db, 0xb776d5f6, 0x5634e2db, 0xb776d5f5, 0x5634e2db, 0xb776d5f4,
0x5634e2db, 0xb776d5f3, 0x5634e2db, 0xb77655f6, 0x5634e2db, 0xb77655f5,
0x5634e2db, 0xb775d5f6, 0x5634e2db, 0xb775d5f5, 0x5634e2db, 0xb676d5f6,
0x5634e2db, 0xb676d5f5, 0x5634e2db, 0x6141f31a, 0x5634e2db, 0x00000000,
0x5634e2da, 0xb776d5f6, 0x5634e2da, 0xb776d5f5, 0x5633e2db, 0xb776d5f6,
0x5633e2db, 0xb776d5f5, 0x5624e2db, 0xb776d5f6, 0x5624e2db, 0xb776d5f5,
0x00000000, 0x00000000, 0xd634e2db, 0xb776d5f6, 0xffffffff, 0xffffffff,
0xc8892a0a, 0xa9cb1d24, 0x80100000, 0x00000000, 0x800fffff, 0xffffffff,
0x80010000, 0x00000000, 0x8000ffff, 0xffffffff, 0x80000001, 0x00000000,
0x80000000, 0xffffffff, 0x80000000, 0x01000000, 0x80000000, 0x00ffffff,
0x80000000, 0x00010000, 0x80000000, 0x0000ffff, 0x80000000, 0x00008000,
0x80000000, 0x00007fff, 0x80000000, 0x00000001, 0x80000000, 0x00000000,
0x7fffffff, 0xffffffff, 0x7fffffff, 0xfffffffe, 0x7fffffff, 0xfffffffd,
0x7fffffff, 0xffff8000, 0x7fffffff, 0xffff7fff, 0x7fffffff, 0xffff0000,
0x7fffffff, 0xfffeffff, 0x7fffffff, 0xff000000, 0x7fffffff, 0xfeffffff,
0x7fffffff, 0xa9cb1d24, 0x7fffffff, 0x48892a0a, 0x7fffffff, 0x00000000,
0x7ffffffe, 0xffffffff, 0x7fff0000, 0x00000000, 0x7ffeffff, 0xffffffff,
0x7ff00000, 0x00000000, 0x7fefffff, 0xffffffff, 0x29cb1d24, 0x48892a0a,
0x00000000, 0x00000000
])
var TEST_MUL_BITS = i32array([
0x80000000, 0x00000000, 0x80000000, 0x00000000, 0x1ad92a0a, 0xa9cb1d25,
0x00000000, 0x00000000, 0xd2500000, 0x00000000, 0x00100000, 0x00000000,
0x80000000, 0x00000000, 0x65ae2a0a, 0xa9cb1d25, 0x00110000, 0x00000001,
0x00100000, 0x00000000, 0x00000000, 0x00000000, 0x1d250000, 0x00000000,
0x00010000, 0x00000000, 0x00000000, 0x00000000, 0x00010000, 0x00000000,
0x80000000, 0x00000000, 0xf254472f, 0xa9cb1d25, 0x00100001, 0x00000001,
0x00100000, 0x00000000, 0x00010001, 0x00000001, 0x00010000, 0x00000000,
0x00000000, 0x00000000, 0xa9cb1d25, 0x00000000, 0x00000001, 0x00000000,
0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000,
0x00000001, 0x00000000, 0x80000000, 0x00000000, 0x5332f527, 0xcecb1d25,
0x00100000, 0x01000001, 0x00100000, 0x00000000, 0x00010000, 0x01000001,
0x00010000, 0x00000000, 0x01000001, 0x01000001, 0x01000001, 0x00000000,
0x00000000, 0x00000000, 0x0aa9cb1d, 0x25000000, 0x00000000, 0x01000000,
0x00000000, 0x00000000, 0x00000000, 0x01000000, 0x00000000, 0x00000000,
0x01000000, 0x01000000, 0x01000000, 0x00000000, 0x00010000, 0x01000000,
0x80000000, 0x00000000, 0x7293d3d5, 0xc6f01d25, 0x00100000, 0x00010001,
0x00100000, 0x00000000, 0x00010000, 0x00010001, 0x00010000, 0x00000000,
0x00010001, 0x00010001, 0x00010001, 0x00000000, 0x00000100, 0x01010001,
0x00000100, 0x01000000, 0x00000000, 0x00000000, 0x2a0aa9cb, 0x1d250000,
0x00000000, 0x00010000, 0x00000000, 0x00000000, 0x00000000, 0x00010000,
0x00000000, 0x00000000, 0x00010000, 0x00010000, 0x00010000, 0x00000000,
0x00000100, 0x00010000, 0x00000100, 0x00000000, 0x00000001, 0x00010000,
0x80000000, 0x00000000, 0xdd8e7ef0, 0x385d9d25, 0x00100000, 0x00008001,
0x00100000, 0x00000000, 0x80010000, 0x00008001, 0x80010000, 0x00000000,
0x00008001, 0x00008001, 0x00008001, 0x00000000, 0x00000080, 0x01008001,
0x00000080, 0x01000000, 0x00000000, 0x80018001, 0x00000000, 0x80010000,
0x00000000, 0x00000000, 0x950554e5, 0x8e928000, 0x00000000, 0x00008000,
0x00000000, 0x00000000, 0x80000000, 0x00008000, 0x80000000, 0x00000000,
0x00008000, 0x00008000, 0x00008000, 0x00000000, 0x00000080, 0x00008000,
0x00000080, 0x00000000, 0x00000000, 0x80008000, 0x00000000, 0x80000000,
0x00000000, 0x40008000, 0x00000000, 0x00000000, 0x91125415, 0x53963a4a,
0x00200000, 0x00000002, 0x00200000, 0x00000000, 0x00020000, 0x00000002,
0x00020000, 0x00000000, 0x00000002, 0x00000002, 0x00000002, 0x00000000,
0x00000000, 0x02000002, 0x00000000, 0x02000000, 0x00000000, 0x00020002,
0x00000000, 0x00020000, 0x00000000, 0x00010002, 0x00000000, 0x00010000,
0x80000000, 0x00000000, 0x48892a0a, 0xa9cb1d25, 0x00100000, 0x00000001,
0x00100000, 0x00000000, 0x00010000, 0x00000001, 0x00010000, 0x00000000,
0x00000001, 0x00000001, 0x00000001, 0x00000000, 0x00000000, 0x01000001,
0x00000000, 0x01000000, 0x00000000, 0x00010001, 0x00000000, 0x00010000,
0x00000000, 0x00008001, 0x00000000, 0x00008000, 0x00000000, 0x00000002,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x80000000, 0x00000000, 0xb776d5f5, 0x5634e2db,
0xffefffff, 0xffffffff, 0xfff00000, 0x00000000, 0xfffeffff, 0xffffffff,
0xffff0000, 0x00000000, 0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000,
0xffffffff, 0xfeffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xfffeffff,
0xffffffff, 0xffff0000, 0xffffffff, 0xffff7fff, 0xffffffff, 0xffff8000,
0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x6eedabea, 0xac69c5b6, 0xffdfffff, 0xfffffffe,
0xffe00000, 0x00000000, 0xfffdffff, 0xfffffffe, 0xfffe0000, 0x00000000,
0xfffffffd, 0xfffffffe, 0xfffffffe, 0x00000000, 0xffffffff, 0xfdfffffe,
0xffffffff, 0xfe000000, 0xffffffff, 0xfffdfffe, 0xffffffff, 0xfffe0000,
0xffffffff, 0xfffefffe, 0xffffffff, 0xffff0000, 0xffffffff, 0xfffffffc,
0xffffffff, 0xfffffffe, 0x00000000, 0x00000000, 0x00000000, 0x00000002,
0x80000000, 0x00000000, 0xb383d525, 0x1b389d25, 0x000fffff, 0xffff8001,
0x00100000, 0x00000000, 0x8000ffff, 0xffff8001, 0x80010000, 0x00000000,
0xffff8000, 0xffff8001, 0xffff8001, 0x00000000, 0xffffff80, 0x00ff8001,
0xffffff80, 0x01000000, 0xffffffff, 0x80008001, 0xffffffff, 0x80010000,
0xffffffff, 0xc0000001, 0xffffffff, 0xc0008000, 0xffffffff, 0xffff0002,
0xffffffff, 0xffff8001, 0x00000000, 0x00000000, 0x00000000, 0x00007fff,
0x00000000, 0x0000fffe, 0x00000000, 0x00000000, 0x6afaab1a, 0x716d8000,
0xffffffff, 0xffff8000, 0x00000000, 0x00000000, 0x7fffffff, 0xffff8000,
0x80000000, 0x00000000, 0xffff7fff, 0xffff8000, 0xffff8000, 0x00000000,
0xffffff7f, 0xffff8000, 0xffffff80, 0x00000000, 0xffffffff, 0x7fff8000,
0xffffffff, 0x80000000, 0xffffffff, 0xbfff8000, 0xffffffff, 0xc0000000,
0xffffffff, 0xffff0000, 0xffffffff, 0xffff8000, 0x00000000, 0x00000000,
0x00000000, 0x00008000, 0x00000000, 0x00010000, 0x00000000, 0x3fff8000,
0x80000000, 0x00000000, 0x1e7e803f, 0x8ca61d25, 0x000fffff, 0xffff0001,
0x00100000, 0x00000000, 0x0000ffff, 0xffff0001, 0x00010000, 0x00000000,
0xffff0000, 0xffff0001, 0xffff0001, 0x00000000, 0xffffff00, 0x00ff0001,
0xffffff00, 0x01000000, 0xffffffff, 0x00000001, 0xffffffff, 0x00010000,
0xffffffff, 0x7fff8001, 0xffffffff, 0x80008000, 0xffffffff, 0xfffe0002,
0xffffffff, 0xffff0001, 0x00000000, 0x00000000, 0x00000000, 0x0000ffff,
0x00000000, 0x0001fffe, 0x00000000, 0x7ffe8001, 0x00000000, 0x7fff8000,
0x00000000, 0x00000000, 0xd5f55634, 0xe2db0000, 0xffffffff, 0xffff0000,
0x00000000, 0x00000000, 0xffffffff, 0xffff0000, 0x00000000, 0x00000000,
0xfffeffff, 0xffff0000, 0xffff0000, 0x00000000, 0xfffffeff, 0xffff0000,
0xffffff00, 0x00000000, 0xfffffffe, 0xffff0000, 0xffffffff, 0x00000000,
0xffffffff, 0x7fff0000, 0xffffffff, 0x80000000, 0xffffffff, 0xfffe0000,
0xffffffff, 0xffff0000, 0x00000000, 0x00000000, 0x00000000, 0x00010000,
0x00000000, 0x00020000, 0x00000000, 0x7fff0000, 0x00000000, 0x80000000,
0x00000000, 0xffff0000, 0x80000000, 0x00000000, 0x3ddf5eed, 0x84cb1d25,
0x000fffff, 0xff000001, 0x00100000, 0x00000000, 0x0000ffff, 0xff000001,
0x00010000, 0x00000000, 0xff000000, 0xff000001, 0xff000001, 0x00000000,
0xffff0000, 0x00000001, 0xffff0000, 0x01000000, 0xfffffeff, 0xff010001,
0xffffff00, 0x00010000, 0xffffff7f, 0xff008001, 0xffffff80, 0x00008000,
0xffffffff, 0xfe000002, 0xffffffff, 0xff000001, 0x00000000, 0x00000000,
0x00000000, 0x00ffffff, 0x00000000, 0x01fffffe, 0x0000007f, 0xfeff8001,
0x0000007f, 0xffff8000, 0x000000ff, 0xfeff0001, 0x000000ff, 0xffff0000,
0x00000000, 0x00000000, 0xf55634e2, 0xdb000000, 0xffffffff, 0xff000000,
0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0x00000000, 0x00000000,
0xfeffffff, 0xff000000, 0xff000000, 0x00000000, 0xfffeffff, 0xff000000,
0xffff0000, 0x00000000, 0xfffffeff, 0xff000000, 0xffffff00, 0x00000000,
0xffffff7f, 0xff000000, 0xffffff80, 0x00000000, 0xffffffff, 0xfe000000,
0xffffffff, 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x01000000,
0x00000000, 0x02000000, 0x0000007f, 0xff000000, 0x00000080, 0x00000000,
0x000000ff, 0xff000000, 0x00000100, 0x00000000, 0x0000ffff, 0xff000000,
0x80000000, 0x00000000, 0xbc56e5ef, 0x15ff6759, 0xd24fffff, 0xa9cb1d25,
0xd2500000, 0x00000000, 0x1d24ffff, 0xa9cb1d25, 0x1d250000, 0x00000000,
0xa9cb1d24, 0xa9cb1d25, 0xa9cb1d25, 0x00000000, 0xffa9cb1c, 0xcecb1d25,
0xffa9cb1d, 0x25000000, 0xffffa9ca, 0xc6f01d25, 0xffffa9cb, 0x1d250000,
0xffffd4e5, 0x385d9d25, 0xffffd4e5, 0x8e928000, 0xffffffff, 0x53963a4a,
0xffffffff, 0xa9cb1d25, 0x00000000, 0x00000000, 0x00000000, 0x5634e2db,
0x00000000, 0xac69c5b6, 0x00002b1a, 0x1b389d25, 0x00002b1a, 0x716d8000,
0x00005634, 0x8ca61d25, 0x00005634, 0xe2db0000, 0x005634e2, 0x84cb1d25,
0x005634e2, 0xdb000000, 0x80000000, 0x00000000, 0x74756f10, 0x9f4f5297,
0xa0afffff, 0x48892a0b, 0xa0b00000, 0x00000000, 0x2a0affff, 0x48892a0b,
0x2a0b0000, 0x00000000, 0x48892a0a, 0x48892a0b, 0x48892a0b, 0x00000000,
0xff488929, 0x53892a0b, 0xff48892a, 0x0b000000, 0xffff4888, 0x72942a0b,
0xffff4889, 0x2a0b0000, 0xffffa443, 0xdd8eaa0b, 0xffffa444, 0x95058000,
0xfffffffe, 0x91125416, 0xffffffff, 0x48892a0b, 0x00000000, 0x00000000,
0x00000000, 0xb776d5f5, 0x00000001, 0x6eedabea, 0x00005bba, 0xb383aa0b,
0x00005bbb, 0x6afa8000, 0x0000b776, 0x1e7e2a0b, 0x0000b776, 0xd5f50000,
0x00b776d5, 0x3d892a0b, 0x00b776d5, 0xf5000000, 0x3dc7d297, 0x9f4f5297,
0x80000000, 0x00000000, 0x9ebe0ce5, 0xa9cb1d25, 0x000fffff, 0x00000001,
0x00100000, 0x00000000, 0x0000ffff, 0x00000001, 0x00010000, 0x00000000,
0x00000000, 0x00000001, 0x00000001, 0x00000000, 0xfeffffff, 0x01000001,
0xff000000, 0x01000000, 0xfffeffff, 0x00010001, 0xffff0000, 0x00010000,
0xffff7fff, 0x00008001, 0xffff8000, 0x00008000, 0xfffffffe, 0x00000002,
0xffffffff, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0xffffffff,
0x00000001, 0xfffffffe, 0x00007ffe, 0xffff8001, 0x00007fff, 0xffff8000,
0x0000fffe, 0xffff0001, 0x0000ffff, 0xffff0000, 0x00fffffe, 0xff000001,
0x00ffffff, 0xff000000, 0x5634e2da, 0xa9cb1d25, 0xb776d5f4, 0x48892a0b,
0x00000000, 0x00000000, 0x5634e2db, 0x00000000, 0xffffffff, 0x00000000,
0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xfeffffff, 0x00000000,
0xff000000, 0x00000000, 0xfffeffff, 0x00000000, 0xffff0000, 0x00000000,
0xffff7fff, 0x00000000, 0xffff8000, 0x00000000, 0xfffffffe, 0x00000000,
0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000,
0x00000002, 0x00000000, 0x00007fff, 0x00000000, 0x00008000, 0x00000000,
0x0000ffff, 0x00000000, 0x00010000, 0x00000000, 0x00ffffff, 0x00000000,
0x01000000, 0x00000000, 0x5634e2db, 0x00000000, 0xb776d5f5, 0x00000000,
0xffffffff, 0x00000000, 0x80000000, 0x00000000, 0x2b642a0a, 0xa9cb1d25,
0x000f0000, 0x00000001, 0x00100000, 0x00000000, 0x00000000, 0x00000001,
0x00010000, 0x00000000, 0xffff0001, 0x00000001, 0x00000001, 0x00000000,
0xffff0000, 0x01000001, 0x00000000, 0x01000000, 0xffff0000, 0x00010001,
0x00000000, 0x00010000, 0x7fff0000, 0x00008001, 0x80000000, 0x00008000,
0xfffe0000, 0x00000002, 0xffff0000, 0x00000001, 0x00000000, 0x00000000,
0x0000ffff, 0xffffffff, 0x0001ffff, 0xfffffffe, 0x7ffeffff, 0xffff8001,
0x7fffffff, 0xffff8000, 0xfffeffff, 0xffff0001, 0xffffffff, 0xffff0000,
0xfffeffff, 0xff000001, 0xffffffff, 0xff000000, 0xe2daffff, 0xa9cb1d25,
0xd5f4ffff, 0x48892a0b, 0xfffeffff, 0x00000001, 0xffffffff, 0x00000000,
0x00000000, 0x00000000, 0xe2db0000, 0x00000000, 0xffff0000, 0x00000000,
0x00000000, 0x00000000, 0xffff0000, 0x00000000, 0x00000000, 0x00000000,
0xffff0000, 0x00000000, 0x00000000, 0x00000000, 0xffff0000, 0x00000000,
0x00000000, 0x00000000, 0xffff0000, 0x00000000, 0x00000000, 0x00000000,
0x7fff0000, 0x00000000, 0x80000000, 0x00000000, 0xfffe0000, 0x00000000,
0xffff0000, 0x00000000, 0x00000000, 0x00000000, 0x00010000, 0x00000000,
0x00020000, 0x00000000, 0x7fff0000, 0x00000000, 0x80000000, 0x00000000,
0xffff0000, 0x00000000, 0x00000000, 0x00000000, 0xffff0000, 0x00000000,
0x00000000, 0x00000000, 0xe2db0000, 0x00000000, 0xd5f50000, 0x00000000,
0xffff0000, 0x00000000, 0x00000000, 0x00000000, 0xffff0000, 0x00000000,
0x80000000, 0x00000000, 0x76392a0a, 0xa9cb1d25, 0x00000000, 0x00000001,
0x00100000, 0x00000000, 0xfff10000, 0x00000001, 0x00010000, 0x00000000,
0xfff00001, 0x00000001, 0x00000001, 0x00000000, 0xfff00000, 0x01000001,
0x00000000, 0x01000000, 0xfff00000, 0x00010001, 0x00000000, 0x00010000,
0xfff00000, 0x00008001, 0x00000000, 0x00008000, 0xffe00000, 0x00000002,
0xfff00000, 0x00000001, 0x00000000, 0x00000000, 0x000fffff, 0xffffffff,
0x001fffff, 0xfffffffe, 0xffefffff, 0xffff8001, 0xffffffff, 0xffff8000,
0xffefffff, 0xffff0001, 0xffffffff, 0xffff0000, 0xffefffff, 0xff000001,
0xffffffff, 0xff000000, 0x2dafffff, 0xa9cb1d25, 0x5f4fffff, 0x48892a0b,
0xffefffff, 0x00000001, 0xffffffff, 0x00000000, 0xffef0000, 0x00000001,
0xffff0000, 0x00000000, 0x00000000, 0x00000000, 0x2db00000, 0x00000000,
0xfff00000, 0x00000000, 0x00000000, 0x00000000, 0xfff00000, 0x00000000,
0x00000000, 0x00000000, 0xfff00000, 0x00000000, 0x00000000, 0x00000000,
0xfff00000, 0x00000000, 0x00000000, 0x00000000, 0xfff00000, 0x00000000,
0x00000000, 0x00000000, 0xfff00000, 0x00000000, 0x00000000, 0x00000000,
0xffe00000, 0x00000000, 0xfff00000, 0x00000000, 0x00000000, 0x00000000,
0x00100000, 0x00000000, 0x00200000, 0x00000000, 0xfff00000, 0x00000000,
0x00000000, 0x00000000, 0xfff00000, 0x00000000, 0x00000000, 0x00000000,
0xfff00000, 0x00000000, 0x00000000, 0x00000000, 0x2db00000, 0x00000000,
0x5f500000, 0x00000000, 0xfff00000, 0x00000000, 0x00000000, 0x00000000,
0xfff00000, 0x00000000, 0x00000000, 0x00000000, 0xfff00000, 0x00000000,
0x80000000, 0x00000000, 0x8a74d669, 0x9f4f5297, 0x4a7b1d24, 0x48892a0b,
0xa0b00000, 0x00000000, 0xd3d61d24, 0x48892a0b, 0x2a0b0000, 0x00000000,
0xf254472f, 0x48892a0b, 0x48892a0b, 0x00000000, 0xce13a64e, 0x53892a0b,
0x2448892a, 0x0b000000, 0xc6ef65ad, 0x72942a0b, 0x1d244889, 0x2a0b0000,
0x385d4168, 0xdd8eaa0b, 0x8e922444, 0x95058000, 0x53963a48, 0x91125416,
0xa9cb1d24, 0x48892a0b, 0x00000000, 0x00000000, 0x5634e2db, 0xb776d5f5,
0xac69c5b7, 0x6eedabea, 0x1b38f8df, 0xb383aa0b, 0x716ddbbb, 0x6afa8000,
0x8ca6d49b, 0x1e7e2a0b, 0xe2dbb776, 0xd5f50000, 0x858293fa, 0x3d892a0b,
0xdbb776d5, 0xf5000000, 0x53c739f0, 0x9f4f5297, 0x22ca6fa5, 0x36ad9c79,
0x6141f319, 0x48892a0b, 0xb776d5f5, 0x00000000, 0x7fc01d24, 0x48892a0b,
0xd5f50000, 0x00000000, 0x091b1d24, 0x48892a0b, 0x5f500000, 0x00000000,
0x80000000, 0x00000000, 0xc8892a0a, 0xa9cb1d25, 0x80100000, 0x00000001,
0x00100000, 0x00000000, 0x80010000, 0x00000001, 0x00010000, 0x00000000,
0x80000001, 0x00000001, 0x00000001, 0x00000000, 0x80000000, 0x01000001,
0x00000000, 0x01000000, 0x80000000, 0x00010001, 0x00000000, 0x00010000,
0x80000000, 0x00008001, 0x00000000, 0x00008000, 0x00000000, 0x00000002,
0x80000000, 0x00000001, 0x00000000, 0x00000000, 0x7fffffff, 0xffffffff,
0xffffffff, 0xfffffffe, 0x7fffffff, 0xffff8001, 0xffffffff, 0xffff8000,
0x7fffffff, 0xffff0001, 0xffffffff, 0xffff0000, 0x7fffffff, 0xff000001,
0xffffffff, 0xff000000, 0x7fffffff, 0xa9cb1d25, 0x7fffffff, 0x48892a0b,
0x7fffffff, 0x00000001, 0xffffffff, 0x00000000, 0x7fff0000, 0x00000001,
0xffff0000, 0x00000000, 0x7ff00000, 0x00000001, 0xfff00000, 0x00000000,
0x29cb1d24, 0x48892a0b
])
var TEST_DIV_BITS = i32array([
0x00000000, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x000007ff,
0x00000000, 0x00000800, 0x00000000, 0x00007fff, 0x00000000, 0x00008000,
0x00000000, 0x7fffffff, 0x00000000, 0x80000000, 0x0000007f, 0xffff8000,
0x00000080, 0x00000000, 0x00007fff, 0x80007fff, 0x00008000, 0x00000000,
0x0000fffe, 0x0003fff8, 0x00010000, 0x00000000, 0x40000000, 0x00000000,
0x80000000, 0x00000000, 0x80000000, 0x00000000, 0xc0000000, 0x00000000,
0xfffefffd, 0xfffbfff8, 0xffff0000, 0x00000000, 0xffff7fff, 0x7fff8000,
0xffff8000, 0x00000000, 0xffffff7f, 0xffff8000, 0xffffff80, 0x00000000,
0xfffffffe, 0x83e3cc1a, 0xffffffff, 0x4d64985a, 0xffffffff, 0x80000000,
0xffffffff, 0x80000000, 0xffffffff, 0xffff8000, 0xffffffff, 0xffff8000,
0xffffffff, 0xfffff800, 0xffffffff, 0xfffff800, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000488, 0x00000000, 0x00000488, 0x00000000, 0x00004889,
0x00000000, 0x00004889, 0x00000000, 0x48892a0a, 0x00000000, 0x48892a0a,
0x00000048, 0x8929c220, 0x00000048, 0x892a0aa9, 0x00004888, 0xe181c849,
0x00004889, 0x2a0aa9cb, 0x00009111, 0x31f2efb0, 0x00009112, 0x54155396,
0x24449505, 0x54e58e92, 0x48892a0a, 0xa9cb1d25, 0xb776d5f5, 0x5634e2db,
0xdbbb6afa, 0xab1a716e, 0xffff6eec, 0x89c3bff2, 0xffff6eed, 0xabeaac6a,
0xffffb776, 0x8d6be3a1, 0xffffb776, 0xd5f55635, 0xffffffb7, 0x76d5acce,
0xffffffb7, 0x76d5f557, 0xffffffff, 0x2898cfc6, 0xffffffff, 0x9ac930b4,
0xffffffff, 0xb776d5f6, 0xffffffff, 0xb776d5f6, 0xffffffff, 0xffffb777,
0xffffffff, 0xffffb777, 0xffffffff, 0xfffffb78, 0xffffffff, 0xfffffb78,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000001,
0x00000000, 0x0000000f, 0x00000000, 0x00000010, 0x00000000, 0x000fffff,
0x00000000, 0x00100000, 0x00000000, 0x0ffffff0, 0x00000000, 0x10000000,
0x0000000f, 0xfff0000f, 0x00000010, 0x00000000, 0x0000001f, 0xffc0007f,
0x00000020, 0x00000000, 0x00080000, 0x00000000, 0x00100000, 0x00000001,
0xffefffff, 0xffffffff, 0xfff80000, 0x00000000, 0xffffffdf, 0xffbfff80,
0xffffffe0, 0x00000000, 0xffffffef, 0xffeffff0, 0xfffffff0, 0x00000000,
0xffffffff, 0xeffffff0, 0xffffffff, 0xf0000000, 0xffffffff, 0xffd07c7a,
0xffffffff, 0xffe9ac94, 0xffffffff, 0xfff00000, 0xffffffff, 0xfff00000,
0xffffffff, 0xfffffff0, 0xffffffff, 0xfffffff0, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x0000000f, 0x00000000, 0x00000010,
0x00000000, 0x000fffff, 0x00000000, 0x00100000, 0x00000000, 0x0ffffff0,
0x00000000, 0x10000000, 0x0000000f, 0xfff0000f, 0x00000010, 0x00000000,
0x0000001f, 0xffc0007f, 0x00000020, 0x00000000, 0x00080000, 0x00000000,
0x00100000, 0x00000000, 0xfff00000, 0x00000000, 0xfff80000, 0x00000000,
0xffffffdf, 0xffbfff80, 0xffffffe0, 0x00000000, 0xffffffef, 0xffeffff0,
0xfffffff0, 0x00000000, 0xffffffff, 0xeffffff0, 0xffffffff, 0xf0000000,
0xffffffff, 0xffd07c7a, 0xffffffff, 0xffe9ac94, 0xffffffff, 0xfff00000,
0xffffffff, 0xfff00000, 0xffffffff, 0xfffffff0, 0xffffffff, 0xfffffff0,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000001, 0x00000000, 0x0000ffff, 0x00000000, 0x00010000,
0x00000000, 0x00ffffff, 0x00000000, 0x01000000, 0x00000000, 0xffff0001,
0x00000001, 0x00000000, 0x00000001, 0xfffc0007, 0x00000002, 0x00000000,
0x00008000, 0x00000000, 0x00010000, 0x00000001, 0xfffeffff, 0xffffffff,
0xffff8000, 0x00000000, 0xfffffffd, 0xfffbfff8, 0xfffffffe, 0x00000000,
0xfffffffe, 0xfffeffff, 0xffffffff, 0x00000000, 0xffffffff, 0xfeffffff,
0xffffffff, 0xff000000, 0xffffffff, 0xfffd07c8, 0xffffffff, 0xfffe9aca,
0xffffffff, 0xffff0000, 0xffffffff, 0xffff0000, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0000ffff,
0x00000000, 0x00010000, 0x00000000, 0x00ffffff, 0x00000000, 0x01000000,
0x00000000, 0xffff0000, 0x00000001, 0x00000000, 0x00000001, 0xfffc0007,
0x00000002, 0x00000000, 0x00008000, 0x00000000, 0x00010000, 0x00000000,
0xffff0000, 0x00000000, 0xffff8000, 0x00000000, 0xfffffffd, 0xfffbfff8,
0xfffffffe, 0x00000000, 0xfffffffe, 0xfffeffff, 0xffffffff, 0x00000000,
0xffffffff, 0xfeffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xfffd07c8,
0xffffffff, 0xfffe9aca, 0xffffffff, 0xffff0000, 0xffffffff, 0xffff0000,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x000000ff,
0x00000000, 0x00000100, 0x00000000, 0x0000ffff, 0x00000000, 0x00010000,
0x00000000, 0x0001fffc, 0x00000000, 0x00020000, 0x00000000, 0x80000000,
0x00000001, 0x00000001, 0xfffffffe, 0xffffffff, 0xffffffff, 0x80000000,
0xffffffff, 0xfffdfffc, 0xffffffff, 0xfffe0000, 0xffffffff, 0xfffeffff,
0xffffffff, 0xffff0000, 0xffffffff, 0xffffff00, 0xffffffff, 0xffffff00,
0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x000000ff, 0x00000000, 0x00000100, 0x00000000, 0x0000ffff,
0x00000000, 0x00010000, 0x00000000, 0x0001fffc, 0x00000000, 0x00020000,
0x00000000, 0x80000000, 0x00000001, 0x00000000, 0xffffffff, 0x00000000,
0xffffffff, 0x80000000, 0xffffffff, 0xfffdfffc, 0xffffffff, 0xfffe0000,
0xffffffff, 0xfffeffff, 0xffffffff, 0xffff0000, 0xffffffff, 0xffffff00,
0xffffffff, 0xffffff00, 0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000001,
0x00000000, 0x000000ff, 0x00000000, 0x00000100, 0x00000000, 0x000001ff,
0x00000000, 0x00000200, 0x00000000, 0x00800000, 0x00000000, 0x01000001,
0xffffffff, 0xfeffffff, 0xffffffff, 0xff800000, 0xffffffff, 0xfffffe00,
0xffffffff, 0xfffffe00, 0xffffffff, 0xffffff00, 0xffffffff, 0xffffff00,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x000000ff, 0x00000000, 0x00000100,
0x00000000, 0x000001ff, 0x00000000, 0x00000200, 0x00000000, 0x00800000,
0x00000000, 0x01000000, 0xffffffff, 0xff000000, 0xffffffff, 0xff800000,
0xffffffff, 0xfffffe00, 0xffffffff, 0xfffffe00, 0xffffffff, 0xffffff00,
0xffffffff, 0xffffff00, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00000002,
0x00000000, 0x00008000, 0x00000000, 0x00010001, 0xffffffff, 0xfffeffff,
0xffffffff, 0xffff8000, 0xffffffff, 0xfffffffe, 0xffffffff, 0xfffffffe,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000001,
0x00000000, 0x00000002, 0x00000000, 0x00008000, 0x00000000, 0x00010000,
0xffffffff, 0xffff0000, 0xffffffff, 0xffff8000, 0xffffffff, 0xfffffffe,
0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00004000,
0x00000000, 0x00008001, 0xffffffff, 0xffff7fff, 0xffffffff, 0xffffc000,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x00004000, 0x00000000, 0x00008000, 0xffffffff, 0xffff8000,
0xffffffff, 0xffffc000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x00000002,
0xffffffff, 0xfffffffe, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff,
0xffffffff, 0xfffffffe, 0x00000000, 0x00000002, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0xffffc001, 0xffffffff, 0xffff8001, 0x00000000, 0x00007fff,
0x00000000, 0x00003fff, 0x00000000, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffc000, 0xffffffff, 0xffff8000,
0x00000000, 0x00008000, 0x00000000, 0x00004000, 0x00000000, 0x00000001,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffff8001,
0xffffffff, 0xffff0001, 0x00000000, 0x0000ffff, 0x00000000, 0x00007fff,
0x00000000, 0x00000002, 0x00000000, 0x00000001, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xfffffffe,
0xffffffff, 0xffff8000, 0xffffffff, 0xffff0000, 0x00000000, 0x00010000,
0x00000000, 0x00008000, 0x00000000, 0x00000002, 0x00000000, 0x00000002,
0x00000000, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0xffffff01, 0xffffffff, 0xffffff01, 0xffffffff, 0xfffffe01,
0xffffffff, 0xfffffe01, 0xffffffff, 0xff800001, 0xffffffff, 0xff000001,
0x00000000, 0x00ffffff, 0x00000000, 0x007fffff, 0x00000000, 0x00000200,
0x00000000, 0x000001ff, 0x00000000, 0x00000100, 0x00000000, 0x000000ff,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffff01, 0xffffffff, 0xffffff00,
0xffffffff, 0xfffffe01, 0xffffffff, 0xfffffe00, 0xffffffff, 0xff800000,
0xffffffff, 0xff000000, 0x00000000, 0x01000000, 0x00000000, 0x00800000,
0x00000000, 0x00000200, 0x00000000, 0x00000200, 0x00000000, 0x00000100,
0x00000000, 0x00000100, 0x00000000, 0x00000001, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xffffffff, 0xffffffaa, 0xffffffff, 0xffffffaa, 0xffffffff, 0xffffa9cc,
0xffffffff, 0xffffa9cc, 0xffffffff, 0xffff5398, 0xffffffff, 0xffff5397,
0xffffffff, 0xd4e58e93, 0xffffffff, 0xa9cb1d25, 0x00000000, 0x5634e2db,
0x00000000, 0x2b1a716d, 0x00000000, 0x0000ac6b, 0x00000000, 0x0000ac69,
0x00000000, 0x00005635, 0x00000000, 0x00005634, 0x00000000, 0x00000056,
0x00000000, 0x00000056, 0x00000000, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0xffffffff, 0xffffff49, 0xffffffff, 0xffffff49,
0xffffffff, 0xffff488a, 0xffffffff, 0xffff488a, 0xffffffff, 0xfffe9116,
0xffffffff, 0xfffe9113, 0xffffffff, 0xa4449506, 0xffffffff, 0x48892a0b,
0x00000000, 0xb776d5f5, 0x00000000, 0x5bbb6afa, 0x00000000, 0x00016ef0,
0x00000000, 0x00016eed, 0x00000000, 0x0000b777, 0x00000000, 0x0000b776,
0x00000000, 0x000000b7, 0x00000000, 0x000000b7, 0x00000000, 0x00000002,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffff01,
0xffffffff, 0xffffff01, 0xffffffff, 0xffff0001, 0xffffffff, 0xffff0001,
0xffffffff, 0xfffe0004, 0xffffffff, 0xfffe0001, 0xffffffff, 0x80000001,
0xffffffff, 0x00000001, 0x00000000, 0xffffffff, 0x00000000, 0x7fffffff,
0x00000000, 0x00020004, 0x00000000, 0x0001ffff, 0x00000000, 0x00010001,
0x00000000, 0x0000ffff, 0x00000000, 0x00000100, 0x00000000, 0x000000ff,
0x00000000, 0x00000002, 0x00000000, 0x00000001, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffff01, 0xffffffff, 0xffffff00, 0xffffffff, 0xffff0001,
0xffffffff, 0xffff0000, 0xffffffff, 0xfffe0004, 0xffffffff, 0xfffe0000,
0xffffffff, 0x80000000, 0xffffffff, 0x00000000, 0x00000001, 0x00000000,
0x00000000, 0x80000000, 0x00000000, 0x00020004, 0x00000000, 0x00020000,
0x00000000, 0x00010001, 0x00000000, 0x00010000, 0x00000000, 0x00000100,
0x00000000, 0x00000100, 0x00000000, 0x00000002, 0x00000000, 0x00000001,
0x00000000, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffff0001,
0xffffffff, 0xffff0001, 0xffffffff, 0xff000001, 0xffffffff, 0xff000001,
0xffffffff, 0x00010000, 0xffffffff, 0x00000001, 0xfffffffe, 0x0003fff9,
0xfffffffe, 0x00000001, 0xffff8000, 0x00000001, 0xffff0000, 0x00000001,
0x0000ffff, 0xffffffff, 0x00007fff, 0xffffffff, 0x00000002, 0x00040008,
0x00000001, 0xffffffff, 0x00000001, 0x00010001, 0x00000000, 0xffffffff,
0x00000000, 0x01000001, 0x00000000, 0x00ffffff, 0x00000000, 0x0002f838,
0x00000000, 0x00016536, 0x00000000, 0x00010000, 0x00000000, 0x0000ffff,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff,
0xffffffff, 0xffff0001, 0xffffffff, 0xffff0000, 0xffffffff, 0xff000001,
0xffffffff, 0xff000000, 0xffffffff, 0x00010000, 0xffffffff, 0x00000000,
0xfffffffe, 0x0003fff9, 0xfffffffe, 0x00000000, 0xffff8000, 0x00000000,
0xffff0000, 0x00000000, 0x00010000, 0x00000000, 0x00008000, 0x00000000,
0x00000002, 0x00040008, 0x00000002, 0x00000000, 0x00000001, 0x00010001,
0x00000001, 0x00000000, 0x00000000, 0x01000001, 0x00000000, 0x01000000,
0x00000000, 0x0002f838, 0x00000000, 0x00016536, 0x00000000, 0x00010000,
0x00000000, 0x00010000, 0x00000000, 0x00000001, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xfffffff1,
0xffffffff, 0xfffffff1, 0xffffffff, 0xfff00001, 0xffffffff, 0xfff00001,
0xffffffff, 0xf0000010, 0xffffffff, 0xf0000001, 0xfffffff0, 0x000ffff1,
0xfffffff0, 0x00000001, 0xffffffe0, 0x003fff81, 0xffffffe0, 0x00000001,
0xfff80000, 0x00000001, 0xfff00000, 0x00000001, 0x000fffff, 0xffffffff,
0x0007ffff, 0xffffffff, 0x00000020, 0x00400080, 0x0000001f, 0xffffffff,
0x00000010, 0x00100010, 0x0000000f, 0xffffffff, 0x00000000, 0x10000010,
0x00000000, 0x0fffffff, 0x00000000, 0x002f8386, 0x00000000, 0x0016536c,
0x00000000, 0x00100000, 0x00000000, 0x000fffff, 0x00000000, 0x00000010,
0x00000000, 0x0000000f, 0x00000000, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff,
0xffffffff, 0xfffffff1, 0xffffffff, 0xfffffff0, 0xffffffff, 0xfff00001,
0xffffffff, 0xfff00000, 0xffffffff, 0xf0000010, 0xffffffff, 0xf0000000,
0xfffffff0, 0x000ffff1, 0xfffffff0, 0x00000000, 0xffffffe0, 0x003fff81,
0xffffffe0, 0x00000000, 0xfff80000, 0x00000000, 0xfff00000, 0x00000000,
0x00100000, 0x00000000, 0x00080000, 0x00000000, 0x00000020, 0x00400080,
0x00000020, 0x00000000, 0x00000010, 0x00100010, 0x00000010, 0x00000000,
0x00000000, 0x10000010, 0x00000000, 0x10000000, 0x00000000, 0x002f8386,
0x00000000, 0x0016536c, 0x00000000, 0x00100000, 0x00000000, 0x00100000,
0x00000000, 0x00000010, 0x00000000, 0x00000010, 0x00000000, 0x00000001,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xfffffa9d,
0xffffffff, 0xfffffa9d, 0xffffffff, 0xffffa9cc, 0xffffffff, 0xffffa9cc,
0xffffffff, 0xa9cb1d25, 0xffffffff, 0xa9cb1d25, 0xffffffa9, 0xcb1d7a7e,
0xffffffa9, 0xcb1d2449, 0xffffa9cb, 0x7358d531, 0xffffa9cb, 0x1d24488a,
0xffff5397, 0x93196ae0, 0xffff5396, 0x3a489113, 0xd4e58e92, 0x24449506,
0xa9cb1d24, 0x48892a0b, 0x5634e2db, 0xb776d5f5, 0x2b1a716d, 0xdbbb6afa,
0x0000ac6b, 0x1e8dac09, 0x0000ac69, 0xc5b76eed, 0x00005635, 0x3910f087,
0x00005634, 0xe2dbb776, 0x00000056, 0x34e331ec, 0x00000056, 0x34e2dbb7,
0x00000001, 0x00000002, 0x00000000, 0x784a3552, 0x00000000, 0x5634e2dc,
0x00000000, 0x5634e2db, 0x00000000, 0x00005634, 0x00000000, 0x00005634,
0x00000000, 0x00000563, 0x00000000, 0x00000563, 0x00000000, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff,
0xffffffff, 0xfffff801, 0xffffffff, 0xfffff801, 0xffffffff, 0xffff8001,
0xffffffff, 0xffff8001, 0xffffffff, 0x80000001, 0xffffffff, 0x80000001,
0xffffff80, 0x00008000, 0xffffff80, 0x00000001, 0xffff8000, 0x7fff8001,
0xffff8000, 0x00000001, 0xffff0001, 0xfffc0008, 0xffff0000, 0x00000001,
0xc0000000, 0x00000001, 0x80000000, 0x00000001, 0x7fffffff, 0xffffffff,
0x3fffffff, 0xffffffff, 0x00010002, 0x00040008, 0x0000ffff, 0xffffffff,
0x00008000, 0x80008000, 0x00007fff, 0xffffffff, 0x00000080, 0x00008000,
0x0000007f, 0xffffffff, 0x00000001, 0x7c1c33e6, 0x00000000, 0xb29b67a6,
0x00000000, 0x80000000, 0x00000000, 0x7fffffff, 0x00000000, 0x00008000,
0x00000000, 0x00007fff, 0x00000000, 0x00000800, 0x00000000, 0x000007ff,
0x00000000, 0x00000001, 0x00000000, 0x00000001
])
var TEST_STRINGS = [
'-9223372036854775808',
'-5226755067826871589',
'-4503599627370497',
'-4503599627370496',
'-281474976710657',
'-281474976710656',
'-4294967297',
'-4294967296',
'-16777217',
'-16777216',
'-65537',
'-65536',
'-32769',
'-32768',
'-2',
'-1',
'0',
'1',
'2',
'32767',
'32768',
'65535',
'65536',
'16777215',
'16777216',
'1446306523',
'3078018549',
'4294967295',
'4294967296',
'281474976710655',
'281474976710656',
'4503599627370495',
'4503599627370496',
'6211839219354490357',
'9223372036854775807'
]
TEST('ToFromBits', () => {
for (var i = 0; i < TEST_BITS.length; i += 2) {
let val = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
assertEq(val._low, TEST_BITS[i + 1])
assertEq(val._high, TEST_BITS[i])
}
})
TEST('ToFromInt32', () => {
for (var i = 0; i < TEST_BITS.length; i += 1) {
let val = SInt64.fromInt32(TEST_BITS[i])
assertEq(val.toInt32(), TEST_BITS[i])
}
})
TEST('ToFromFloat64', () => {
for (var i = 0; i < TEST_BITS.length; i += 2) {
let num = TEST_BITS[i] * Math.pow(2, 32) + TEST_BITS[i + 1] >= 0 ?
TEST_BITS[i + 1] :
Math.pow(2, 32) + TEST_BITS[i + 1];
let val = SInt64.fromFloat64(num)
assertEq(val.toFloat64(), num)
}
// Test edge cases
assertEq(SInt64.fromFloat64(NaN), SInt64.ZERO)
assertEq(SInt64.fromFloat64(Infinity), SInt64.MAX)
assertEq(SInt64.fromFloat64(-Infinity), SInt64.MIN)
})
TEST('FromDecimalCachedValues', () => {
// Make sure we are not leaking longs by incorrect caching of decimal
// numbers and failing-fast in debug mode.
assertThrows(() => SInt64.fromInt32(0.1))
assertThrows(() => SInt64.fromInt32(0.2))
assertThrows(() => SInt64.fromInt32(1.1))
})
TEST('egz', () => {
for (var i = 0; i < TEST_BITS.length; i += 2) {
let val = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
assertEq(val.eqz(), TEST_BITS[i] == 0 && TEST_BITS[i + 1] == 0)
}
})
TEST('isNeg', () => {
for (var i = 0; i < TEST_BITS.length; i += 2) {
let val = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
assertEq(val.isNeg(), (TEST_BITS[i] >> 31) != 0)
}
})
TEST('isOdd', () => {
for (var i = 0; i < TEST_BITS.length; i += 2) {
let val = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
assertEq(val.isOdd(), (TEST_BITS[i + 1] & 1) != 0)
}
})
TEST('comparisons', () => {
for (let i = 0; i < TEST_BITS.length; i += 2) {
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
for (let j = 0; j < TEST_BITS.length; j += 2) {
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
assertEq(vi.eq(vj), i == j, "comparison#" + i)
assertEq(vi.lt(vj), i < j, "comparison#" + i)
assertEq(vi.lte(vj), i <= j, "comparison#" + i)
assertEq(vi.gt(vj), i > j, "comparison#" + i)
assertEq(vi.gte(vj), i >= j, "comparison#" + i)
}
}
})
TEST('bitOperations', () => {
for (let i = 0; i < TEST_BITS.length; i += 2) {
let actx = `bitOperations[i=${i}]`
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
assertEq(vi.not()._high, ~TEST_BITS[i], actx)
assertEq(vi.not()._low, ~TEST_BITS[i + 1], actx)
for (let j = 0; j < TEST_BITS.length; j += 2) {
actx = `bitOperations[i=${i},j=${j}]`
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
assertEq(vi.and(vj)._high, TEST_BITS[i] & TEST_BITS[j], actx)
assertEq(vi.and(vj)._low, TEST_BITS[i + 1] & TEST_BITS[j + 1], actx)
assertEq(vi.or(vj)._high, TEST_BITS[i] | TEST_BITS[j], actx)
assertEq(vi.or(vj)._low, TEST_BITS[i + 1] | TEST_BITS[j + 1], actx)
assertEq(vi.xor(vj)._high, TEST_BITS[i] ^ TEST_BITS[j], actx)
assertEq(vi.xor(vj)._low, TEST_BITS[i + 1] ^ TEST_BITS[j + 1], actx)
}
actx = `bitOperations[i=${i}]`
assertEq(vi.shl(0)._high, TEST_BITS[i], actx)
assertEq(vi.shl(0)._low, TEST_BITS[i + 1], actx)
assertEq(vi.shr_s(0)._high, TEST_BITS[i], actx)
assertEq(vi.shr_s(0)._low, TEST_BITS[i + 1], actx)
assertEq(vi.shr_u(0)._high, TEST_BITS[i], actx)
assertEq(vi.shr_u(0)._low, TEST_BITS[i + 1], actx)
for (let len = 1; len < 64; ++len) {
actx = `bitOperations[i=${i},len=${len}]`
if (len < 32) {
assertEq(
vi.shl(len)._high,
(TEST_BITS[i] << len) | (TEST_BITS[i + 1] >>> (32 - len)),
actx
)
assertEq(vi.shl(len)._low, TEST_BITS[i + 1] << len, actx)
assertEq(vi.shr_s(len)._high, TEST_BITS[i] >> len, actx)
assertEq(
vi.shr_s(len)._low,
(TEST_BITS[i + 1] >>> len) | (TEST_BITS[i] << (32 - len)),
actx
)
assertEq(vi.shr_u(len)._high, TEST_BITS[i] >>> len, actx)
assertEq(
vi.shr_u(len)._low,
(TEST_BITS[i + 1] >>> len) | (TEST_BITS[i] << (32 - len)),
actx
)
} else {
assertEq(vi.shl(len)._high, TEST_BITS[i + 1] << (len - 32), actx)
assertEq(vi.shl(len)._low, 0, actx)
assertEq(vi.shr_s(len)._high, TEST_BITS[i] >= 0 ? 0 : -1, actx)
assertEq(vi.shr_s(len)._low, TEST_BITS[i] >> (len - 32), actx)
assertEq(vi.shr_u(len)._high, 0, actx)
if (len == 32) {
assertEq(vi.shr_u(len)._low, TEST_BITS[i], actx)
} else {
assertEq(
vi.shr_u(len)._low,
TEST_BITS[i] >>> (len - 32),
actx
)
}
}
}
actx = `bitOperations[i=${i}]`
assertEq(vi.shl(64)._high, TEST_BITS[i], actx)
assertEq(vi.shl(64)._low, TEST_BITS[i + 1], actx)
assertEq(vi.shr_s(64)._high, TEST_BITS[i], actx)
assertEq(vi.shr_s(64)._low, TEST_BITS[i + 1], actx)
assertEq(vi.shr_u(64)._high, TEST_BITS[i], actx)
assertEq(vi.shr_u(64)._low, TEST_BITS[i + 1], actx)
}
})
TEST('neg', () => {
for (let i = 0; i < TEST_BITS.length; i += 2) {
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
if (TEST_BITS[i + 1] == 0) {
assertEq(vi.neg()._high, (~TEST_BITS[i] + 1) | 0)
assertEq(vi.neg()._low, 0)
} else {
assertEq(vi.neg()._high, ~TEST_BITS[i])
assertEq(vi.neg()._low, (~TEST_BITS[i + 1] + 1) | 0)
}
}
})
TEST('add', () => {
let count = 0
for (let i = 0; i < TEST_BITS.length; i += 2) {
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
for (let j = 0; j < i; j += 2) {
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
let result = vi.add(vj)
assertEq(result._high, TEST_ADD_BITS[count++])
assertEq(result._low, TEST_ADD_BITS[count++])
}
}
})
TEST('sub', () => {
let count = 0
for (let i = 0; i < TEST_BITS.length; i += 2) {
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
for (let j = 0; j < TEST_BITS.length; j += 2) {
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
let result = vi.sub(vj)
assertEq(result._high, TEST_SUB_BITS[count++])
assertEq(result._low, TEST_SUB_BITS[count++])
}
}
})
TEST('mul', () => {
let count = 0;
for (let i = 0; i < TEST_BITS.length; i += 2) {
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
for (let j = 0; j < i; j += 2) {
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
let result = vi.mul(vj)
assertEq(result._high, TEST_MUL_BITS[count++])
assertEq(result._low, TEST_MUL_BITS[count++])
}
}
})
if (js_mul) TEST('mul/js', () => {
let count = 0;
for (let i = 0; i < TEST_BITS.length; i += 2) {
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
for (let j = 0; j < i; j += 2) {
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
let result = js_mul.call(vi, vj)
assertEq(result._high, TEST_MUL_BITS[count++])
assertEq(result._low, TEST_MUL_BITS[count++])
}
}
})
TEST('div-mod', () => {
let countPerDivModCall = 0
for (let j = 0; j < TEST_BITS.length; j += 2) {
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
if (!vj.eqz()) {
countPerDivModCall += 2
}
}
let countDivMod = 0
for (let i = 0; i < TEST_BITS.length; i += 2) {
// goog.global['testDivMod' + i] = createTestDivMod(i, countDivMod)
// function createTestDivMod(i, countDivMod) {
//return function() {
let count = countDivMod
countDivMod += countPerDivModCall
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
for (let j = 0; j < TEST_BITS.length; j += 2) {
let vj = new SInt64(TEST_BITS[j + 1], TEST_BITS[j])
if (!vj.eqz()) {
let divResult = vi.div(vj)
assertEq(divResult._high, TEST_DIV_BITS[count])
assertEq(divResult._low, TEST_DIV_BITS[count + 1])
let modResult = vi.mod(vj)
let combinedResult = divResult.mul(vj).add(modResult)
assert(vi.eq(combinedResult))
if (js_div_s) {
assert(js_mod_s)
divResult = js_div_s.call(vi, vj)
assertEq(divResult._high, TEST_DIV_BITS[count])
assertEq(divResult._low, TEST_DIV_BITS[count + 1])
let modResult = js_mod_s.call(vi, vj)
let combinedResult = divResult.mul(vj).add(modResult)
assert(vi.eq(combinedResult))
}
count += 2
}
}
}
})
TEST('ToFromString', () => {
for (let i = 0; i < TEST_BITS.length; i += 2) {
let vi = new SInt64(TEST_BITS[i + 1], TEST_BITS[i])
let str = vi.toString(10)
assertEq(str, TEST_STRINGS[i / 2])
let n = SInt64.fromStr(str, 10)
assertEq(n._high, TEST_BITS[i])
assertEq(n._low, TEST_BITS[i + 1])
for (let radix = 2; radix <= 36; ++radix) {
let result = vi.toString(radix)
n = SInt64.fromStr(result, radix)
assertEq(n._high, TEST_BITS[i])
assertEq(n._low, TEST_BITS[i + 1])
}
}
// this was once wrong in goog.math.Long
assertEq(SInt64.fromStr("zzzzzz", 36).toString(36), "zzzzzz")
assertEq(SInt64.fromStr("-zzzzzz", 36).toString(36), "-zzzzzz")
}) | the_stack |
module Shumway.AVM2 {
import Multiname = Shumway.AVM2.ABC.Multiname;
import ByteArray = Shumway.AVM2.AS.flash.utils.ByteArray;
import forEachPublicProperty = Shumway.AVM2.Runtime.forEachPublicProperty;
import construct = Shumway.AVM2.Runtime.construct;
export enum AMF0Marker {
NUMBER = 0x00,
BOOLEAN = 0x01,
STRING = 0x02,
OBJECT = 0x03,
NULL = 0x05,
UNDEFINED = 0x06,
REFERENCE = 0x07,
ECMA_ARRAY = 0x08,
OBJECT_END = 0x09,
STRICT_ARRAY = 0x0A,
DATE = 0x0B,
LONG_STRING = 0x0C,
XML = 0x0F,
TYPED_OBJECT = 0x10,
AVMPLUS = 0x11
}
function writeString(ba: ByteArray, s) {
if (s.length > 0xFFFF) {
throw 'AMF short string exceeded';
}
if (!s.length) {
ba.writeByte(0x00);
ba.writeByte(0x00);
return;
}
var bytes = Shumway.StringUtilities.utf8decode(s);
ba.writeByte((bytes.length >> 8) & 255);
ba.writeByte(bytes.length & 255);
for (var i = 0; i < bytes.length; i++) {
ba.writeByte(bytes[i]);
}
}
function readString(ba: ByteArray) {
var byteLength = (ba.readByte() << 8) | ba.readByte();
if (!byteLength) {
return '';
}
var buffer = new Uint8Array(byteLength);
for (var i = 0; i < byteLength; i++) {
buffer[i] = ba.readByte();
}
return Shumway.StringUtilities.utf8encode(buffer);
}
function writeDouble(ba: ByteArray, value) {
var buffer = new ArrayBuffer(8);
var view = new DataView(buffer);
view.setFloat64(0, value, false);
for (var i = 0; i < buffer.byteLength; i++) {
ba.writeByte(view.getUint8(i));
}
}
function readDouble(ba: ByteArray) {
var buffer = new ArrayBuffer(8);
var view = new DataView(buffer);
for (var i = 0; i < buffer.byteLength; i++) {
view.setUint8(i, ba.readByte());
}
return view.getFloat64(0, false);
}
function setAvmProperty(obj, propertyName, value) {
obj.asSetPublicProperty(propertyName, value);
}
export class AMF0 {
public static write(ba: ByteArray, obj) {
switch (typeof obj) {
case 'boolean':
ba.writeByte(AMF0Marker.BOOLEAN);
ba.writeByte(obj ? 0x01: 0x00);
break;
case 'number':
ba.writeByte(AMF0Marker.NUMBER);
writeDouble(ba, obj);
break;
case 'undefined':
ba.writeByte(AMF0Marker.UNDEFINED);
break;
case 'string':
ba.writeByte(AMF0Marker.STRING);
writeString(ba, obj);
break;
case 'object':
if (obj === null) {
ba.writeByte(AMF0Marker.NULL);
} else if (Array.isArray(obj)) {
ba.writeByte(AMF0Marker.ECMA_ARRAY);
ba.writeByte((obj.length >>> 24) & 255);
ba.writeByte((obj.length >> 16) & 255);
ba.writeByte((obj.length >> 8) & 255);
ba.writeByte(obj.length & 255);
forEachPublicProperty(obj, function (key, value) {
writeString(ba, key);
this.write(ba, value);
}, this);
ba.writeByte(0x00);
ba.writeByte(0x00);
ba.writeByte(AMF0Marker.OBJECT_END);
} else {
ba.writeByte(AMF0Marker.OBJECT);
forEachPublicProperty(obj, function (key, value) {
writeString(ba, key);
this.write(ba, value);
}, this);
ba.writeByte(0x00);
ba.writeByte(0x00);
ba.writeByte(AMF0Marker.OBJECT_END);
}
return;
}
}
public static read(ba: ByteArray) {
var marker = ba.readByte();
switch (marker) {
case AMF0Marker.NUMBER:
return readDouble(ba);
case AMF0Marker.BOOLEAN:
return !!ba.readByte();
case AMF0Marker.STRING:
return readString(ba);
case AMF0Marker.OBJECT:
var obj = {};
while (true) {
var key = readString(ba);
if (!key.length) break;
setAvmProperty(obj, key, this.read(ba));
}
if (ba.readByte() !== AMF0Marker.OBJECT_END) {
throw 'AMF0 End marker is not found';
}
return obj;
case AMF0Marker.NULL:
return null;
case AMF0Marker.UNDEFINED:
return undefined;
case AMF0Marker.ECMA_ARRAY:
var arr = [];
arr.length = (ba.readByte() << 24) | (ba.readByte() << 16) |
(ba.readByte() << 8) | ba.readByte();
while (true) {
var key = readString(ba);
if (!key.length) break;
setAvmProperty(arr, key, this.read(ba));
}
if (ba.readByte() !== AMF0Marker.OBJECT_END) {
throw 'AMF0 End marker is not found';
}
return arr;
case AMF0Marker.STRICT_ARRAY:
var arr = [];
arr.length = (ba.readByte() << 24) | (ba.readByte() << 16) |
(ba.readByte() << 8) | ba.readByte();
for (var i = 0; i < arr.length; i++) {
arr[i] = this.read(ba);
}
return arr;
case AMF0Marker.AVMPLUS:
return readAmf3Data(ba, {});
default:
throw 'AMF0 Unknown marker ' + marker;
}
}
}
export enum AMF3Marker {
UNDEFINED = 0x00,
NULL = 0x01,
FALSE = 0x02,
TRUE = 0x03,
INTEGER = 0x04,
DOUBLE = 0x05,
STRING = 0x06,
XML_DOC = 0x07,
DATE = 0x08,
ARRAY = 0x09,
OBJECT = 0x0A,
XML = 0x0B,
BYTEARRAY = 0x0C,
VECTOR_INT = 0x0D,
VECTOR_UINT = 0x0E,
VECTOR_DOUBLE = 0x0F,
VECTOR_OBJECT = 0x10,
DICTIONARY = 0x11
}
function readU29(ba: ByteArray) {
var b1 = ba.readByte();
if ((b1 & 0x80) === 0) {
return b1;
}
var b2 = ba.readByte();
if ((b2 & 0x80) === 0) {
return ((b1 & 0x7F) << 7) | b2;
}
var b3 = ba.readByte();
if ((b3 & 0x80) === 0) {
return ((b1 & 0x7F) << 14) | ((b2 & 0x7F) << 7) | b3;
}
var b4 = ba.readByte();
return ((b1 & 0x7F) << 22) | ((b2 & 0x7F) << 15) | ((b3 & 0x7F) << 8) | b4;
}
function writeU29(ba: ByteArray, value) {
if ((value & 0xFFFFFF80) === 0) {
ba.writeByte(value & 0x7F);
} else if ((value & 0xFFFFC000) === 0) {
ba.writeByte(0x80 | ((value >> 7) & 0x7F));
ba.writeByte(value & 0x7F);
} else if ((value & 0xFFE00000) === 0) {
ba.writeByte(0x80 | ((value >> 14) & 0x7F));
ba.writeByte(0x80 | ((value >> 7) & 0x7F));
ba.writeByte(value & 0x7F);
} else if ((value & 0xC0000000) === 0) {
ba.writeByte(0x80 | ((value >> 22) & 0x7F));
ba.writeByte(0x80 | ((value >> 15) & 0x7F));
ba.writeByte(0x80 | ((value >> 8) & 0x7F));
ba.writeByte(value & 0xFF);
} else {
throw 'AMF3 U29 range';
}
}
function readUTF8vr(ba: ByteArray, caches) {
var u29s = readU29(ba);
if (u29s === 0x01) {
return '';
}
var stringsCache = caches.stringsCache || (caches.stringsCache = []);
if ((u29s & 1) === 0) {
return stringsCache[u29s >> 1];
}
var byteLength = u29s >> 1;
var buffer = new Uint8Array(byteLength);
for (var i = 0; i < byteLength; i++) {
buffer[i] = ba.readByte();
}
var value = Shumway.StringUtilities.utf8encode(buffer);
stringsCache.push(value);
return value;
}
function writeUTF8vr(ba: ByteArray, value, caches) {
if (value === '') {
ba.writeByte(0x01); // empty string
return;
}
var stringsCache = caches.stringsCache || (caches.stringsCache = []);
var index = stringsCache.indexOf(value);
if (index >= 0) {
writeU29(ba, index << 1);
return;
}
stringsCache.push(value);
var bytes = Shumway.StringUtilities.utf8decode(value);
writeU29(ba, 1 | (bytes.length << 1));
for (var i = 0; i < bytes.length; i++) {
ba.writeByte(bytes[i]);
}
}
function readAmf3Data(ba: ByteArray, caches) {
var marker = ba.readByte();
switch (marker) {
case AMF3Marker.NULL:
return null;
case AMF3Marker.UNDEFINED:
return undefined;
case AMF3Marker.FALSE:
return false;
case AMF3Marker.TRUE:
return true;
case AMF3Marker.INTEGER:
return readU29(ba);
case AMF3Marker.DOUBLE:
return readDouble(ba);
case AMF3Marker.STRING:
return readUTF8vr(ba, caches);
case AMF3Marker.DATE:
return new Date(readDouble(ba));
case AMF3Marker.OBJECT:
var u29o = readU29(ba);
if ((u29o & 1) === 0) {
return caches.objectsCache[u29o >> 1];
}
if ((u29o & 4) !== 0) {
throw 'AMF3 Traits-Ext is not supported';
}
var traits, objectClass;
if ((u29o & 2) === 0) {
traits = caches.traitsCache[u29o >> 2];
objectClass = traits.class;
} else {
traits = {};
var aliasName = readUTF8vr(ba, caches);
traits.className = aliasName;
objectClass = aliasName && aliasesCache.names[aliasName];
traits.class = objectClass;
traits.isDynamic = (u29o & 8) !== 0;
traits.members = [];
var slots = objectClass && objectClass.instanceBindings.slots;
for (var i = 0, j = u29o >> 4; i < j; i++) {
var traitName = readUTF8vr(ba, caches);
var slot = null;
for (var j = 1; slots && j < slots.length; j++) {
if (slots[j].name.name === traitName) {
slot = slots[j];
break;
}
}
traits.members.push(slot ? Multiname.getQualifiedName(slot.name) :
Multiname.getPublicQualifiedName(traitName));
}
(caches.traitsCache || (caches.traitsCache = [])).push(traits);
}
var obj = objectClass ? construct(objectClass, []) : {};
(caches.objectsCache || (caches.objectsCache = [])).push(obj);
for (var i = 0; i < traits.members.length; i++) {
var value = readAmf3Data(ba, caches);
obj[traits.members[i]] = value;
}
if (traits.isDynamic) {
while (true) {
var key = readUTF8vr(ba, caches);
if (!key.length) break;
var value = readAmf3Data(ba, caches);
setAvmProperty(obj, key, value);
}
}
return obj;
case AMF3Marker.ARRAY:
var u29o = readU29(ba);
if ((u29o & 1) === 0) {
return caches.objectsCache[u29o >> 1];
}
var arr = [];
(caches.objectsCache || (caches.objectsCache = [])).push(arr);
var densePortionLength = u29o >> 1;
while (true) {
var key = readUTF8vr(ba, caches);
if (!key.length) break;
var value = readAmf3Data(ba, caches);
setAvmProperty(arr, key, value);
}
for (var i = 0; i < densePortionLength; i++) {
var value = readAmf3Data(ba, caches);
setAvmProperty(arr, i, value);
}
return arr;
default:
throw 'AMF3 Unknown marker ' + marker;
}
}
function writeCachedReference(ba: ByteArray, obj, caches) {
var objectsCache = caches.objectsCache || (caches.objectsCache = []);
var index = objectsCache.indexOf(obj);
if (index < 0) {
objectsCache.push(obj);
return false;
}
writeU29(ba, index << 1);
return true;
}
function writeAmf3Data(ba: ByteArray, obj, caches) {
switch (typeof obj) {
case 'boolean':
ba.writeByte(obj ? AMF3Marker.TRUE : AMF3Marker.FALSE);
break;
case 'number':
if (obj === (obj | 0)) {
ba.writeByte(AMF3Marker.INTEGER);
writeU29(ba, obj);
} else {
ba.writeByte(AMF3Marker.DOUBLE);
writeDouble(ba, obj);
}
break;
case 'undefined':
ba.writeByte(AMF3Marker.UNDEFINED);
break;
case 'string':
ba.writeByte(AMF3Marker.STRING);
writeUTF8vr(ba, obj, caches);
break;
case 'object':
if (obj === null) {
ba.writeByte(AMF3Marker.NULL);
} else if (Array.isArray(obj)) {
ba.writeByte(AMF3Marker.ARRAY);
if (writeCachedReference(ba, obj, caches))
break;
var densePortionLength = 0;
while (densePortionLength in obj) {
++densePortionLength;
}
writeU29(ba, (densePortionLength << 1) | 1);
forEachPublicProperty(obj, function (i, value) {
if (isNumeric(i) && i >= 0 && i < densePortionLength) {
return;
}
writeUTF8vr(ba, i, caches);
writeAmf3Data(ba, value, caches);
});
writeUTF8vr(ba, '', caches);
for (var j = 0; j < densePortionLength; j++) {
writeAmf3Data(ba, obj[j], caches);
}
} else if (obj instanceof Date) {
ba.writeByte(AMF3Marker.DATE);
if (writeCachedReference(ba, obj, caches))
break;
writeU29(ba, 1);
writeDouble(ba, obj.valueOf());
} else {
// TODO Vector, Dictionary, ByteArray and XML support
ba.writeByte(AMF3Marker.OBJECT);
if (writeCachedReference(ba, obj, caches))
break;
var isDynamic = true;
var objectClass = obj.class;
if (objectClass) {
isDynamic = !objectClass.classInfo.instanceInfo.isSealed();
var aliasName = aliasesCache.classes.get(objectClass) || '';
var traits, traitsCount;
var traitsCache = caches.traitsCache || (caches.traitsCache = []);
var traitsInfos = caches.traitsInfos || (caches.traitsInfos = []);
var traitsRef = traitsCache.indexOf(objectClass);
if (traitsRef < 0) {
var slots = objectClass.instanceBindings.slots;
traits = [];
var traitsNames = [];
for (var i = 1; i < slots.length; i++) {
var slot = slots[i];
if (!slot.name.getNamespace().isPublic()) {
continue;
}
traits.push(Multiname.getQualifiedName(slot.name));
traitsNames.push(slot.name.name);
}
traitsCache.push(objectClass);
traitsInfos.push(traits);
traitsCount = traitsNames.length;
writeU29(ba, (isDynamic ? 0x0B : 0x03) + (traitsCount << 4));
writeUTF8vr(ba, aliasName, caches);
for (var i = 0; i < traitsCount; i++) {
writeUTF8vr(ba, traitsNames[i], caches);
}
} else {
traits = traitsInfos[traitsRef];
traitsCount = traits.length;
writeU29(ba, 0x01 + (traitsRef << 2));
}
for (var i = 0; i < traitsCount; i++) {
writeAmf3Data(ba, obj[traits[i]], caches);
}
} else {
// object with no class definition
writeU29(ba, 0x0B);
writeUTF8vr(ba, '', caches); // empty alias name
}
if (isDynamic) {
forEachPublicProperty(obj, function (i, value) {
writeUTF8vr(ba, i, caches);
writeAmf3Data(ba, value, caches);
});
writeUTF8vr(ba, '', caches);
}
}
return;
}
}
// Also used in linker.ts for registering/retrieving class aliases.
export var aliasesCache = {
classes: new WeakMap(),
names: Object.create(null)
};
export class AMF3 {
public static write(ba: ByteArray, object) {
writeAmf3Data(ba, object, {});
}
public static read(ba: ByteArray) {
return readAmf3Data(ba, {});
}
}
} | the_stack |
import { Browser, EmitType, select } from '@syncfusion/ej2-base';
import { EventHandler, isNullOrUndefined, closest } from '@syncfusion/ej2-base';
import { createElement } from '@syncfusion/ej2-base';
import { Grid } from '../../../src/grid/base/grid';
import { Freeze } from '../../../src/grid/actions/freeze';
import { Selection } from '../../../src/grid/actions/selection';
import { Page } from '../../../src/grid/actions/page';
import { data } from '../base/datasource.spec';
import { Group } from '../../../src/grid/actions/group';
import { Sort } from '../../../src/grid/actions/sort';
import { Edit } from '../../../src/grid/actions/edit';
import { Toolbar } from '../../../src/grid/actions/toolbar';
import { VirtualScroll } from '../../../src/grid/actions/virtual-scroll';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { QueryCellInfoEventArgs, RowSelectingEventArgs, RowSelectEventArgs, RowDeselectEventArgs } from '../../../src/grid/base/interface';
import { createGrid, destroy, getClickObj } from '../base/specutil.spec';
import {profile , inMB, getMemoryProfile} from '../base/common.spec';
import { Column } from '../../../src/grid/models/column';
import { Row } from '../../../src/grid/models/row';
import { rowSelecting } from '../../../src';
Grid.Inject(Selection, Page, Sort, Group, Edit, Toolbar, Freeze, VirtualScroll);
function copyObject(source: Object, destiation: Object): Object {
for (let prop in source) {
destiation[prop] = source[prop];
}
return destiation;
}
function getEventObject(eventType: string, eventName: string, target?: Element, x?: number, y?: number): Object {
let tempEvent: any = document.createEvent(eventType);
tempEvent.initEvent(eventName, true, true);
let returnObject: any = copyObject(tempEvent, {});
returnObject.preventDefault = () => { return true; };
if (!isNullOrUndefined(x)) {
returnObject.pageX = x;
returnObject.clientX = x;
}
if (!isNullOrUndefined(y)) {
returnObject.pageY = y;
returnObject.clientY = y;
}
if (!isNullOrUndefined(target)) {
returnObject.target = returnObject.srcElement = returnObject.toElement = returnObject.currentTarget = target;
}
return returnObject;
}
let ctr: number = 0;
let count500: string[] = Array.apply(null, Array(5)).map(() => 'Column' + ++ctr + '');
let virtualData: Object[] = (() => {
let arr: Object[] = [];
for (let i: number = 0, o: Object = {}, j: number = 0; i < 1000; i++ , j++ , o = {}) {
count500.forEach((lt: string) => o[lt] = 'Column' + lt + 'Row' + i);
arr[j] = o;
}
return arr;
})();
describe('Selection Shortcuts testing', () => {
let gridObj: Grid;
let preventDefault: Function = new Function();
let selectionModule: Selection;
let rows: Element[];
beforeAll((done: Function) => {
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)
}
gridObj = createGrid(
{
dataSource: data,
columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' },
{ field: 'ShipCity' }],
allowPaging: true,
pageSettings: { pageSize: 8, pageCount: 4, currentPage: 1 },
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('shiftDown intial cell, row shortcut testing', (done: Function) => {
let args: any = { action: 'shiftDown', preventDefault: preventDefault };
let len: number = 5;
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
let focusHandler: Function = () => {
gridObj.keyboardModule.keyAction(args);
for (let i: number = 0; i <= 1; i++) {
if (i === 1) {
len = 1;
}
for (let j: number = 0; j < len; j++) {
expect(rows[i].querySelectorAll('.e-rowcell')[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
gridObj.clearSelection();
EventHandler.remove(gridObj.element, 'focus', focusHandler);
done();
};
EventHandler.add(gridObj.element, 'focus', focusHandler, gridObj);
gridObj.element.focus();
EventHandler.trigger(gridObj.element, 'focus');
});
it('downarrow shortcut testing', () => {
let args: any = { action: 'downArrow', preventDefault: preventDefault };
(gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement).click();
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('2');
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(gridObj.getSelectedRecords().length).toBe(1);
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
expect(rows[2].firstElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getSelectedRowCellIndexes().length).toBe(1);
});
it('upArrow shortcut testing', () => {
let args: any = { action: 'upArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('1');
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(1);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
expect(rows[1].firstElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(1);
});
it('select cell method testing', () => {
gridObj.clearSelection();
selectionModule.selectCell({ rowIndex: 0, cellIndex: 2 });
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement)).not.toBeNull();
selectionModule.selectCell({ rowIndex: 0, cellIndex: 2 });
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement)).not.toBeNull();
selectionModule.selectCell({ rowIndex: 0, cellIndex: 2 }, true);
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement)).toBeNull();
selectionModule.selectCell({ rowIndex: 0, cellIndex: 2 }, true);
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement)).not.toBeNull();
});
it('rightArrow shortcut next row testing', () => {
gridObj.clearSelection();
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
selectionModule.selectCell({ rowIndex: 0, cellIndex: 4 }, true);
gridObj.keyboardModule.keyAction(args);
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect((rows[1].querySelector('.e-cellselectionbackground') as HTMLTableCellElement)).toBeNull();
});
it('rightArrow shortcut next row testing', () => {
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
selectionModule.selectCell({ rowIndex: 0, cellIndex: 4 }, true);
gridObj.keyboardModule.keyAction(args);
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect((rows[1].querySelector('.e-cellselectionbackground'))).toBeNull();
});
it('leftarrow shortcut prev row testing', () => {
let args: any = { action: 'leftArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(3);
});
it('leftarrow shortcut testing', () => {
let args: any = { action: 'leftArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(2);
});
it('home shortcut testing', () => {
gridObj.selectRow(1);
let args: any = { action: 'home', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('1');
expect((rows[1].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(0);
});
it('end shortcut testing', () => {
let args: any = { action: 'end', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('1');
expect((rows[1].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(4);
});
it('ctrlHome shortcut testing', () => {
let args: any = { action: 'ctrlHome', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('0');
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(0);
});
it('ctrlEnd shortcut testing', () => {
let args: any = { action: 'ctrlEnd', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('7');
expect(rows[7].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect((rows[7].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(4);
gridObj.selectionModule.clearCellSelection();
});
it('shiftUp row shortcut testing', (done: Function) => {
let args: any = { action: 'shiftUp', preventDefault: preventDefault };
let flag: boolean = true;
gridObj.rowSelected = () => {
if (!flag) { return; }
flag = false;
gridObj.rowSelected = null;
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('2');
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[1].getAttribute('aria-rowindex')).toBe('3');
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[7].querySelectorAll('.e-rowcell')[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
done();
};
gridObj.selectRow(3);
});
it('shiftDown row shortcut testing', () => {
let args: any = { action: 'shiftDown', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('3');
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[1].getAttribute('aria-rowindex')).toBe('4');
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[7].querySelectorAll('.e-rowcell')[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('shiftUp row shortcut reverse testing', () => {
let args: any = { action: 'shiftUp', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('3');
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(rows[7].querySelectorAll('.e-rowcell')[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('shiftLeft cell shortcut testing', () => {
let args: any = { action: 'shiftLeft', preventDefault: preventDefault };
selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
gridObj.keyboardModule.keyAction(args);
expect(rows[1].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('shiftRight cell shortcut testing', () => {
let args: any = { action: 'shiftRight', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
gridObj.keyboardModule.keyAction(args);
expect(rows[1].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].querySelectorAll('.e-rowcell')[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('shiftUp cell shortcut testing', () => {
let args: any = { action: 'shiftUp', preventDefault: preventDefault };
let st: number = 2;
let len: number = 2;
gridObj.keyboardModule.keyAction(args);
for (let i: number = 0; i <= 1; i++) {
if (i === 1) {
st = 0;
len = 1;
}
for (let j: number = st; j < len; j++) {
expect(rows[i].querySelectorAll('.e-rowcell')[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
});
it('shiftDown cell shortcut testing', () => {
let args: any = { action: 'shiftDown', preventDefault: preventDefault };
let st: number = 1;
let len: number = 3;
gridObj.keyboardModule.keyAction(args);
gridObj.keyboardModule.keyAction(args);
for (let i: number = 1; i <= 2; i++) {
if (i === 2) {
st = 0;
len = 2;
}
for (let j: number = st; j < len; j++) {
expect(rows[i].querySelectorAll('.e-rowcell')[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
});
it('escape shortcut testing', () => {
let args: any = { action: 'escape', preventDefault: preventDefault };
gridObj.selectRows([0, 1, 2]);
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getSelectedRecords().length).toBe(0);
expect(gridObj.getSelectedRowIndexes().length).toBe(0);
});
it('ctrl + A shortcut testing', () => {
let args: any = { action: 'ctrlPlusA', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(gridObj.element.querySelectorAll('.e-rowcell').length);
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(gridObj.element.querySelectorAll('.e-rowcell').length);
});
it('shiftDown - header', () => {
(gridObj.getHeaderContent().querySelector('.e-headercell') as HTMLElement).click()
let args: any = { action: 'shiftDown', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect((<any>gridObj).focusModule.active.constructor.name).toBe('HeaderFocus');
});
afterAll(() => {
destroy(gridObj);
gridObj = preventDefault = selectionModule = rows = null;
});
});
describe('grid selection functionalities with Frozen rows', function () {
let gridObj: Grid;
let preventDefault: Function = new Function();
let selectionModule: Selection;
let rows: Element[];
beforeAll(function (done) {
gridObj = createGrid({
frozenRows: 2,
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
}, done);
});
it('downarrow shortcut testing', function () {
rows = gridObj.getRows();
let args: any = { action: 'downArrow', preventDefault: preventDefault };
(gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement).click();
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('2');
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(gridObj.getSelectedRecords().length).toBe(1);
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
expect(rows[2].firstElementChild.classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(gridObj.getSelectedRowCellIndexes().length).toBe(0);
});
it('upArrow shortcut testing', function () {
let args: any = { action: 'upArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('tr[aria-selected="true"]')[0].getAttribute('aria-rowindex')).toBe('1');
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(gridObj.selectionModule.selectedRecords.length).toBe(1);
expect(gridObj.selectionModule.selectedRowIndexes.length).toBe(1);
});
afterAll(function () {
destroy(gridObj);
});
});
describe('EJ2-34955 - Grid row Selected Issue Fixes', () =>{
let gridObj: Grid;
let count: number = 0;
beforeAll((done) => {
gridObj = createGrid({
dataSource: data,
selectionSettings: { persistSelection: true },
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' }
],
allowPaging: true,
rowSelected: function () {
count = count + 1;
}
}, done);
});
it('Selected count', function (done) {
gridObj.refresh();
expect(count).toBe(0);
done();
});
});
describe('Grid Selection module', () => {
describe('grid single seletion functionalities', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Single', mode: 'Both' },
}, done);
});
it('single row - selectRow testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
selectionModule.selectRow(0, true);
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(5);
expect(selectionModule.selectedRecords.length).toBe(1);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
});
it('single row testing', () => {
selectionModule.selectRow(2, true);
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(1);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
});
it('single row - selectRowsByRange testing', () => {
selectionModule.clearRowSelection();
selectionModule.selectRowsByRange(3, 4);
expect(rows[3].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(selectionModule.selectedRecords.length).toBe(1);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
});
it('single row - selectRows testing', () => {
selectionModule.clearRowSelection();
gridObj.selectRows([1, 2]);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(selectionModule.selectedRecords.length).toBe(1);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
});
it('single row - addRowsToSelection testing', () => {
selectionModule.clearRowSelection();
selectionModule.addRowsToSelection([2]);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(selectionModule.selectedRecords.length).toBe(1);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
});
it('clear row selection testing', () => {
selectionModule.selectRow(1, true);
selectionModule.clearRowSelection();
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(0);
expect(selectionModule.selectedRecords.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('single cell - selectCell testing', () => {
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(1);
});
it('single cell testing', () => {
selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
expect((rows[1].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(1);
expect(selectionModule.selectedRowCellIndexes.length).toBe(1);
expect(rows[0].querySelectorAll('.e-cellselectionbackground').length).toBe(0);
});
it('single cell - selectCellsByRange testing', () => {
selectionModule.clearCellSelection();
selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 0 }, { rowIndex: 1, cellIndex: 1 });
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('single cell - selectCellsByRange box mode testing', () => {
selectionModule.clearCellSelection();
gridObj.selectionSettings.cellSelectionMode = 'Box';
gridObj.dataBind();
selectionModule.selectCellsByRange({ rowIndex: 1, cellIndex: 1 }, { rowIndex: 2, cellIndex: 2 });
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('single cell - selectCells testing', () => {
selectionModule.clearCellSelection();
selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [0] }, { rowIndex: 1, cellIndexes: [1] }]);
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('single cell - addCellsToSelection testing', () => {
selectionModule.clearCellSelection();
selectionModule.addCellsToSelection([{ rowIndex: 0, cellIndex: 0 }]);
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('clear cell selection testing', () => {
selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
selectionModule.clearCellSelection();
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(selectionModule.selectedRecords.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = null;
});
});
describe('grid single selection functionalities with Freeze pane', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
beforeAll((done: Function) => {
gridObj = createGrid(
{
frozenColumns: 2,
frozenRows: 2,
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Single', mode: 'Both' },
}, done);
});
it('single row - selectRow testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
selectionModule.selectRow(0, true);
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(5);
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
});
it('single row testing', () => {
selectionModule.selectRow(2, true);
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
});
it('clear row selection testing', () => {
selectionModule.selectRow(1, true);
selectionModule.clearRowSelection();
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(0);
expect(selectionModule.selectedRecords.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('single cell - selectCell testing', () => {
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
expect((rows[0].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(1);
});
it('single cell testing', () => {
selectionModule.selectCell({ rowIndex: 1, cellIndex: 3 }, true);
let mRows: Element[] = gridObj.getMovableRows();
expect(
(mRows[1].querySelector('.e-cellselectionbackground') as HTMLTableCellElement).cellIndex).toBe(3 - gridObj.frozenColumns);
expect(selectionModule.selectedRowCellIndexes.length).toBe(1);
expect(mRows[0].querySelectorAll('.e-cellselectionbackground').length).toBe(0);
});
it('clear cell selection testing', () => {
selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
selectionModule.clearCellSelection();
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(selectionModule.selectedRecords.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = null;
});
});
});
describe('Mode and Type changes', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let rowSelecting: (e?: Object) => void;
let rowSelected: (e?: Object) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
rowSelecting: rowSelecting,
rowSelected: rowSelected,
}, done);
});
it('multi row - selectRow test with mode change ',() =>{
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
selectionModule.selectRow(4,true);
rows[6].firstChild.dispatchEvent(shiftEvt);
gridObj.selectionSettings.mode='Cell';
gridObj.dataBind();
gridObj.selectionSettings.mode="Row";
gridObj.dataBind();
rows[8].firstChild.dispatchEvent(shiftEvt);
expect(gridObj.selectionModule.selectedRowIndexes.length).toBe(1);
expect(rows[8].hasAttribute('aria-selected')).toBeTruthy;
expect(rows[8].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
});
it('final type change row count',() =>{
rows[5].firstChild.dispatchEvent(shiftEvt);
gridObj.selectionSettings.type="Single";
gridObj.dataBind();
gridObj.selectionSettings.type="Multiple";
rows[0].firstChild.dispatchEvent(shiftEvt);
expect(gridObj.selectionModule.selectedRowIndexes.length).toBe(1);
expect(gridObj.selectionModule.selectedRecords.length).toBe(1);
});
it('cell selection with type change',() =>{
gridObj.selectionSettings.mode="Cell";
gridObj.dataBind();
(rows[1].querySelectorAll('.e-rowcell')[1] as HTMLElement).click();
rows[2].querySelectorAll('.e-rowcell')[2].dispatchEvent(shiftEvt);
gridObj.selectionSettings.mode="Row";
gridObj.dataBind();
gridObj.selectionSettings.mode="Cell";
gridObj.dataBind();
rows[2].querySelectorAll('.e-rowcell')[2].dispatchEvent(shiftEvt);
expect(gridObj.selectionModule.selectedRowCellIndexes.length).toBe(1);
expect(rows[2].firstElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy;
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy;
});
it('cell selection with mode change',() =>{
rows[3].querySelectorAll('.e-rowcell')[3].dispatchEvent(shiftEvt);
gridObj.selectionSettings.type="Single";
gridObj.dataBind();
gridObj.selectionSettings.type="Multiple";
gridObj.dataBind();
rows[4].querySelectorAll('.e-rowcell')[2].dispatchEvent(shiftEvt);
expect(gridObj.selectionModule.selectedRowCellIndexes.length).toBe(1);
expect(rows[4].firstElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy;
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy;
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = shiftEvt = null;
});
});
describe('Grid Selection module', () => {
describe('grid row multiple seletion functionalities', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
let rowSelecting: (e?: Object) => void;
let rowSelected: (e?: Object) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
rowSelecting: rowSelecting,
rowSelected: rowSelected,
}, done);
});
it('multi row - selectRow testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
selectionModule.selectRowsByRange(0, 1);
selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [0] }]);
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('single row testing', () => {
selectionModule.selectRow(2, true);
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(1);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
});
it('multi row - addRowsToSelection testing', () => {
selectionModule.addRowsToSelection([4]);
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('multi row - ctrl click testing', () => {
rows[0].firstChild.dispatchEvent(ctrlEvt);
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(3);
expect(selectionModule.selectedRowIndexes.length).toBe(3);
});
it('multi row toogle - ctrl click testing', () => {
rows[4].firstChild.dispatchEvent(ctrlEvt);
expect(rows[4].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('clear row selection testing', () => {
selectionModule.clearRowSelection();
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(0);
expect(selectionModule.selectedRecords.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('multi row - shift click testing', () => {
(rows[4].firstChild as HTMLElement).click();
rows[3].firstChild.dispatchEvent(shiftEvt);
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('multi row - shift click testing', () => {
rows[5].firstChild.dispatchEvent(shiftEvt);
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[5].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[5].firstElementChild.classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('multi row - shift click testing', () => {
rows[2].firstChild.dispatchEvent(shiftEvt);
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(3);
expect(selectionModule.selectedRowIndexes.length).toBe(3);
});
it('rowSelecting event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.rowSelecting = spyFn;
selectionModule.selectRow(2, true);
expect(spyFn).toHaveBeenCalled();
});
it('rowSelected event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.rowSelected = spyFn;
selectionModule.selectRow(3, true);
expect(spyFn).toHaveBeenCalled();
});
it('multi cell - selectRows testing', () => {
selectionModule.clearRowSelection();
selectionModule.selectRows([0, 2])
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('EJ2-19254 - selectRowsByRange testing - startvalue-0, endvalue-null', () => {
selectionModule.clearRowSelection();
selectionModule.selectRowsByRange(0, null);
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowIndexes.length).toBe(1);
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = shiftEvt = null;
});
});
describe('grid selection functionalities: deselection with persistSelection property', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { persistSelection: true },
}, done);
});
it('selection and deselection with persistSelection property', () => {
selectionModule = gridObj.selectionModule;
selectionModule.selectRow(1, true);
rows = gridObj.getRows();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
selectionModule.selectedRecords[0].querySelector('td').click();
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = null;
});
});
describe('grid row multiple selection functionalities with Freeze pane', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
let rowSelecting: (e?: Object) => void;
let rowSelected: (e?: Object) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
frozenColumns: 2,
frozenRows: 2,
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
rowSelecting: rowSelecting,
rowSelected: rowSelected,
}, done);
});
it('multi row - selectRow testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
selectionModule.selectRowsByRange(1, 2);
selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [0] }]);
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(4);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('single row testing', () => {
selectionModule.selectRow(3, true);
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(2);
expect(selectionModule.selectedRowIndexes.length).toBe(1);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
});
it('multi row - addRowsToSelection testing', () => {
selectionModule.addRowsToSelection([4]);
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(4);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('multi row - ctrl click testing', () => {
rows[0].firstChild.dispatchEvent(ctrlEvt);
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(6);
expect(selectionModule.selectedRowIndexes.length).toBe(3);
});
it('multi row toogle - ctrl click testing', () => {
rows[4].firstChild.dispatchEvent(ctrlEvt);
expect(rows[4].hasAttribute('aria-selected')).toBeFalsy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(selectionModule.selectedRecords.length).toBe(4);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('clear row selection testing', () => {
selectionModule.clearRowSelection();
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(0);
expect(selectionModule.selectedRecords.length).toBe(0);
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('multi row - shift click testing', () => {
(rows[4].firstChild as HTMLElement).click();
rows[3].firstChild.dispatchEvent(shiftEvt);
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(4);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('multi row - shift click testing', () => {
rows[5].firstChild.dispatchEvent(shiftEvt);
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[5].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[5].firstElementChild.classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(selectionModule.selectedRecords.length).toBe(4);
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
it('multi row - shift click testing', () => {
rows[2].firstChild.dispatchEvent(shiftEvt);
expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[4].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[4].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRecords.length).toBe(6);
expect(selectionModule.selectedRowIndexes.length).toBe(3);
});
it('rowSelecting event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.rowSelecting = spyFn;
selectionModule.selectRow(2, true);
expect(spyFn).toHaveBeenCalled();
});
it('rowSelected event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.rowSelected = spyFn;
selectionModule.selectRow(3, true);
expect(spyFn).toHaveBeenCalled();
});
it('multi cell - selectRows testing', () => {
selectionModule.clearRowSelection();
selectionModule.selectRows([0, 2])
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowIndexes.length).toBe(2);
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = shiftEvt = null;
});
});
});
describe('Grid Selection module', () => {
describe('grid cell multiple seletion functionalities', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let cells: NodeListOf<Element>;
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
let cellSelecting: (e?: Object) => void;
let cellSelected: (e?: Object) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Cell' },
cellSelecting: cellSelecting,
cellSelected: cellSelected,
}, done);
});
it('multi cell - selectCellsByRange testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 0 }, { rowIndex: 1, cellIndex: 1 });
let len = gridObj.getColumns().length;
for (let i: number = 0; i <= 1; i++) {
cells = rows[i].querySelectorAll('.e-rowcell');
if (i === 1) {
len = 2;
}
for (let j: number = 0; j < len; j++) {
expect(cells[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
expect(rows[0].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[0].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('multi cell - selectCellsByRange box mode testing', () => {
gridObj.selectionSettings.cellSelectionMode = 'Box';
gridObj.dataBind();
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 2 }, { rowIndex: 1, cellIndex: 3 });
for (let i: number = 0; i <= 1; i++) {
cells = rows[i].querySelectorAll('.e-rowcell');
for (let j: number = 2; j < 4; j++) {
expect(cells[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
expect(rows[0].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(rows[0].querySelectorAll('.e-rowcell')[4].classList.contains('e-cellselectionbackground')).toBeFalsy();
gridObj.selectionSettings.cellSelectionMode = 'Flow';
gridObj.dataBind();
});
it('single cell testing', () => {
selectionModule.selectCell({ rowIndex: 2, cellIndex: 2 }, true);
expect(rows[2].querySelectorAll('.e-rowcell')[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(1);
expect(rows[0].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('multi cell - addCellsToSelection testing', () => {
selectionModule.addCellsToSelection([{ rowIndex: 1, cellIndex: 1 }]);
expect(rows[2].querySelectorAll('.e-rowcell')[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
});
it('multi cell - addRowsToSelection click testing', () => {
rows[0].firstChild.dispatchEvent(ctrlEvt);
expect(rows[2].querySelectorAll('.e-rowcell')[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[0].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(3);
});
it('multi cell toogle - addRowsToSelection click testing', () => {
rows[0].firstChild.dispatchEvent(ctrlEvt);
expect(rows[0].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('selection on same row - addRowsToSelection click testing', () => {
rows[0].querySelectorAll('.e-rowcell')[1].dispatchEvent(ctrlEvt);
expect(rows[0].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('clear cell selection testing', () => {
selectionModule.clearCellSelection();
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('multi cell - shift click testing', () => {
(rows[1].querySelectorAll('.e-rowcell')[1] as HTMLElement).click();
rows[2].querySelectorAll('.e-rowcell')[2].dispatchEvent(shiftEvt);
let cellIndex: number = 1;
let len: number = 5;
for (let i: number = 1; i <= 2; i++) {
cells = rows[i].querySelectorAll('.e-rowcell');
if (i === 1) {
cellIndex = 2;
len = 3;
}
for (let j: number = cellIndex; j < len; j++) {
expect(cells[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
});
it('multi cell - shift click testing', () => {
rows[0].querySelectorAll('.e-rowcell')[0].dispatchEvent(shiftEvt);
let len: number = gridObj.getColumns().length;
for (let i: number = 0; i <= 1; i++) {
cells = rows[i].querySelectorAll('.e-rowcell');
if (i === 1) {
len = 2;
}
for (let j: number = 0; j < len; j++) {
expect(cells[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
});
it('multi cell - shift click testing', () => {
rows[2].querySelectorAll('.e-rowcell')[2].dispatchEvent(shiftEvt);
let cellIndex: number = 1;
let len: number = 5;
for (let i: number = 1; i <= 2; i++) {
cells = rows[i].querySelectorAll('.e-rowcell');
if (i === 1) {
cellIndex = 2;
len = 3;
}
for (let j: number = cellIndex; j < len; j++) {
expect(cells[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
});
it('cellSelecting event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.cellSelecting = spyFn;
selectionModule.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
expect(spyFn).toHaveBeenCalled();
});
it('cellSelected event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.cellSelected = spyFn;
selectionModule.selectCell({ rowIndex: 0, cellIndex: 1 }, true);
expect(spyFn).toHaveBeenCalled();
});
it('multi cell - selectCells testing', () => {
selectionModule.clearCellSelection();
selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [0] }, { rowIndex: 1, cellIndexes: [1] }, { rowIndex: 2, cellIndexes: [2] }])
for (let i: number = 0; i <= 2; i++) {
cells = rows[i].querySelectorAll('.e-rowcell');
expect(cells[i].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
expect(selectionModule.selectedRowCellIndexes.length).toBe(3);
});
it('Muliple Cell selection while refreshing grid testing', function (done) {
gridObj.dataBound = function () {
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
gridObj.refresh();
gridObj.dataBound = function () {
gridObj.selectCellsByRange({rowIndex: 0, cellIndex: 0},{rowIndex: 0, cellIndex: 2});
expect(gridObj.getCellFromIndex(0,2).classList.contains('e-cellselectionbackground')).toBeTruthy;
expect(gridObj.getSelectedRowCellIndexes()[0].cellIndexes.length).toBe(3);
selectionModule.clearCellSelection();
done();
}
};
gridObj.refresh();
gridObj.refresh();
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = shiftEvt = null;
});
});
describe('grid cell multiple seletion functionalities with Freeze pane', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let mRows: Element[];
let cells: NodeListOf<Element>;
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
let cellSelecting: (e?: Object) => void;
let cellSelected: (e?: Object) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
frozenColumns: 2,
frozenRows: 2,
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Cell' },
cellSelecting: cellSelecting,
cellSelected: cellSelected,
}, done);
});
it('single cell testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
mRows = gridObj.getMovableRows();
selectionModule.selectCell({ rowIndex: 2, cellIndex: 2 }, true);
expect(mRows[2].querySelectorAll('.e-rowcell')[2 - 2].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(1);
expect(rows[0].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('multi cell - addCellsToSelection testing', () => {
selectionModule.addCellsToSelection([{ rowIndex: 1, cellIndex: 1 }]);
expect(mRows[2].querySelectorAll('.e-rowcell')[2 - 2].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
});
it('multi cell - addRowsToSelection click testing', () => {
rows[3].firstChild.dispatchEvent(ctrlEvt);
expect(mRows[2].querySelectorAll('.e-rowcell')[2 - 2].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[3].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(3);
});
it('multi cell toogle - addRowsToSelection click testing', () => {
rows[3].firstChild.dispatchEvent(ctrlEvt);
expect(rows[3].querySelectorAll('.e-rowcell')[0].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('selection on same row - addRowsToSelection click testing', () => {
mRows[0].querySelectorAll('.e-rowcell')[1].dispatchEvent(ctrlEvt);
expect(mRows[0].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('clear cell selection testing', () => {
selectionModule.clearCellSelection();
expect(selectionModule.selectedRowIndexes.length).toBe(0);
expect(selectionModule.selectedRowCellIndexes.length).toBe(0);
});
it('multi cell - shift click testing', () => {
(rows[0].querySelectorAll('.e-rowcell')[1] as HTMLElement).click();
rows[1].querySelectorAll('.e-rowcell')[1].dispatchEvent(shiftEvt);
let cellIndex: number = 1;
let len: number = 2;
for (let i: number = 0; i <= 1; i++) {
cells = rows[i].querySelectorAll('.e-rowcell');
if (i === 1) {
cellIndex = 0;
len = 2;
}
for (let j: number = cellIndex; j < len; j++) {
expect(cells[j].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(selectionModule.selectedRowCellIndexes.length).toBe(2);
});
it('cellSelecting event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.cellSelecting = spyFn;
selectionModule.selectCell({ rowIndex: 2, cellIndex: 4 }, true);
expect(spyFn).toHaveBeenCalled();
});
it('cellSelected event call', () => {
let spyFn: (e?: Object) => void = jasmine.createSpy('begin');
gridObj.cellSelected = spyFn;
selectionModule.selectCell({ rowIndex: 0, cellIndex: 1 }, true);
expect(spyFn).toHaveBeenCalled();
});
it('multi cell - selectCells testing', () => {
selectionModule.clearCellSelection();
selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [0] }, { rowIndex: 1, cellIndexes: [1] }, { rowIndex: 2, cellIndexes: [2] }])
for (let i: number = 0; i <= 2; i++) {
if (i === 2) {
cells = mRows[i].querySelectorAll('.e-rowcell');
expect(cells[i - gridObj.frozenColumns].classList.contains('e-cellselectionbackground')).toBeTruthy();
} else {
cells = rows[i].querySelectorAll('.e-rowcell');
expect(cells[i].classList.contains('e-cellselectionbackground')).toBeTruthy();
}
}
expect(selectionModule.selectedRowCellIndexes.length).toBe(3);
});
it('Muliple Cell selection while refreshing grid testing in Freeze', function (done) {
gridObj.dataBound = function () {
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
gridObj.refresh();
gridObj.dataBound = function () {
gridObj.selectCellsByRange({rowIndex: 0, cellIndex: 0},{rowIndex: 0, cellIndex: 1});
expect(gridObj.getCellFromIndex(0,1).classList.contains('e-cellselectionbackground')).toBeTruthy;
expect(gridObj.getSelectedRowCellIndexes()[0].cellIndexes.length).toBe(2);
selectionModule.clearCellSelection();
done();
}
};
gridObj.refresh();
gridObj.refresh();
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = mRows = cells = ctrlEvt = shiftEvt = null;
});
});
});
describe('Grid Selection module', () => {
describe('clear selection cases', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let cell: HTMLElement;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('select cell and clear row selection testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
cell = rows[0].firstChild as HTMLElement;
selectionModule.selectCell({ rowIndex: 1, cellIndex: 0 }, true);
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].firstElementChild.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('row and cell toogle testing', () => {
selectionModule.clearSelection();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeTruthy();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('row and cell same row testing', () => {
selectionModule.clearSelection();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeTruthy();
(rows[0].querySelectorAll('.e-rowcell')[1] as HTMLElement).click();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(rows[0].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
(rows[0].querySelectorAll('.e-rowcell')[1] as HTMLElement).click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(rows[0].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeFalsy();
(rows[0].querySelectorAll('.e-rowcell')[1] as HTMLElement).click();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
expect(rows[0].querySelectorAll('.e-rowcell')[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('allowSelection false testing', () => {
gridObj.allowSelection = false;
gridObj.dataBind();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
gridObj.selectionSettings.type = 'Single'; //for coverage
gridObj.dataBind();
});
it('Row select false testing', () => {
(gridObj.element.querySelectorAll('.e-row')[0].firstChild as HTMLElement).click();
expect(gridObj.element.querySelectorAll('.e-row')[0].hasAttribute('aria-selected')).toBeFalsy();
});
it('keydown selection false testing', () => {
gridObj.allowSelection = true;
gridObj.dataBind();
(gridObj.element.querySelectorAll('.e-row')[0].firstChild as HTMLElement).click();
let preventDefault: Function = new Function();
let args: any = { action: 'downArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
//for coverage
(<any>gridObj.selectionModule).mouseDownHandler({ target: gridObj.element, preventDefault: () => { } });
gridObj.allowRowDragAndDrop = true;
gridObj.dataBind();
(<any>gridObj.selectionModule).mouseDownHandler({ target: gridObj.element, preventDefault: () => { } });
gridObj.isDestroyed = true;
(<any>gridObj.selectionModule).addEventListener();
gridObj.selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
(<any>gridObj.selectionModule).isTrigger = true;
gridObj.selectionModule.clearCellSelection();
(<any>gridObj.selectionModule).isTrigger = false;
gridObj.selectRow(1, true);
(<any>gridObj.selectionModule).isRowSelected = true;
(<any>gridObj.selectionModule).isTrigger = true;
gridObj.selectionModule.clearRowSelection();
(<any>gridObj.selectionModule).isTrigger = false;
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 0 }, { rowIndex: 1, cellIndex: 1 });
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [0] }]);
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.addCellsToSelection([{ rowIndex: 0, cellIndex: 0 }]);
gridObj.selectionSettings.mode = 'Row';
gridObj.dataBind();
(<any>gridObj.selectionModule).applyHomeEndKey(0, 0);
gridObj.allowRowDragAndDrop = true;
gridObj.dataBind();
(<any>gridObj.selectionModule).element = createElement('div');
(<any>gridObj.selectionModule).startIndex = 0;
(<any>gridObj.selectionModule).mouseMoveHandler({ target: gridObj.element, preventDefault: () => { }, clientX: 10, clientY: 10 });
gridObj.selectionModule.destroy();
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = cell = null;
});
});
describe('clear selection cases with Freeze pane', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let mRows: Element[];
let cell: HTMLElement;
beforeAll((done: Function) => {
gridObj = createGrid(
{
frozenColumns: 2,
frozenRows: 2,
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('select cell and clear row selection testing', () => {
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
mRows = gridObj.getMovableRows();
cell = rows[0].firstChild as HTMLElement;
selectionModule.selectCell({ rowIndex: 1, cellIndex: 0 }, true);
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeFalsy();
expect(rows[1].firstElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(rows[1].firstElementChild.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('row and cell toogle testing', () => {
selectionModule.clearSelection();
cell = mRows[0].children[1] as HTMLElement;
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeTruthy();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('row and cell same row testing', () => {
selectionModule.clearSelection();
cell.click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeTruthy();
(mRows[0].querySelectorAll('.e-rowcell')[2] as HTMLElement).click();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(mRows[0].querySelectorAll('.e-rowcell')[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
(mRows[0].querySelectorAll('.e-rowcell')[2] as HTMLElement).click();
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(mRows[0].querySelectorAll('.e-rowcell')[2].classList.contains('e-cellselectionbackground')).toBeFalsy();
(mRows[0].querySelectorAll('.e-rowcell')[2] as HTMLElement).click();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
expect(mRows[0].querySelectorAll('.e-rowcell')[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('keydown selection false testing', () => {
gridObj.allowSelection = true;
gridObj.dataBind();
(gridObj.element.querySelectorAll('.e-row')[0].firstChild as HTMLElement).click();
let preventDefault: Function = new Function();
let args: any = { action: 'downArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.element.querySelectorAll('.e-row')[0].hasAttribute('aria-selected')).toBeFalsy();
//for coverage
(<any>gridObj.selectionModule).mouseDownHandler({ target: gridObj.element, preventDefault: () => { } });
gridObj.allowRowDragAndDrop = true;
gridObj.dataBind();
(<any>gridObj.selectionModule).mouseDownHandler({ target: gridObj.element, preventDefault: () => { } });
gridObj.isDestroyed = true;
(<any>gridObj.selectionModule).addEventListener();
gridObj.selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
(<any>gridObj.selectionModule).isTrigger = true;
gridObj.selectionModule.clearCellSelection();
(<any>gridObj.selectionModule).isTrigger = false;
gridObj.selectRow(1, true);
(<any>gridObj.selectionModule).isRowSelected = true;
(<any>gridObj.selectionModule).isTrigger = true;
gridObj.selectionModule.clearRowSelection();
(<any>gridObj.selectionModule).isTrigger = false;
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.selectCell({ rowIndex: 1, cellIndex: 1 }, true);
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 0 }, { rowIndex: 1, cellIndex: 1 });
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [0] }]);
(<any>gridObj.selectionModule).prevECIdxs = undefined;
gridObj.selectionModule.addCellsToSelection([{ rowIndex: 0, cellIndex: 0 }]);
gridObj.selectionSettings.mode = 'Row';
gridObj.dataBind();
(<any>gridObj.selectionModule).applyHomeEndKey(0, 0);
gridObj.allowRowDragAndDrop = true;
gridObj.dataBind();
(<any>gridObj.selectionModule).element = createElement('div');
(<any>gridObj.selectionModule).startIndex = 0;
(<any>gridObj.selectionModule).mouseMoveHandler({ target: gridObj.element, preventDefault: () => { }, clientX: 10, clientY: 10 });
gridObj.selectionModule.destroy();
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = cell = mRows = null;
});
});
describe('Model changes', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let cell: HTMLElement;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: false,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('enable selection testing', () => {
gridObj.allowSelection = true;
gridObj.dataBind();
selectionModule = gridObj.selectionModule;
rows = gridObj.getRows();
cell = rows[0].firstChild as HTMLElement;
selectionModule.selectRows([0, 1]);
expect(cell.classList.contains('e-selectionbackground')).toBeTruthy();
});
it('selction type change row testing', () => {
gridObj.selectionSettings.type = 'Single';
gridObj.dataBind();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
gridObj.selectionSettings.type = 'Multiple';
gridObj.dataBind();
});
it('cell selection testing', () => {
selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 0 }, { rowIndex: 1, cellIndex: 0 });
expect(cell.classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('selction type change row testing', () => {
gridObj.selectionSettings.type = 'Single';
gridObj.dataBind();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('selection mode change to row', () => {
gridObj.selectionSettings.mode = 'Row';
gridObj.dataBind();
expect(cell.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('select a row with wrong row index', () => {
gridObj.selectRow(20, true);
gridObj.dataBind();
expect(gridObj.getContent().querySelectorAll('.e-selectionbackground').length).toBe(0);
});
it('selction type change row testing', () => {
gridObj.selectionSettings.type = 'Multiple';
gridObj.dataBind();
expect(cell.classList.contains('e-selectionbackground')).toBeFalsy();
});
it('select multiple row with wrong index', () => {
gridObj.selectRows([1, 3, 5, 15, 20]);
gridObj.dataBind();
//expect(gridObj.getContent().querySelectorAll('.e-selectionbackground').length).toBe(3 * gridObj.columns.length);
});
it('change selection mode row to cell', () => {
gridObj.selectionSettings.mode = 'Cell';
gridObj.dataBind();
expect(gridObj.getContent().querySelectorAll('.e-selectionbackground').length).toBe(0);
})
it('select a cell with wrong object ', () => {
gridObj.selectionModule.selectCell({ rowIndex: 0, cellIndex: 12 }, true);
gridObj.dataBind();
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(0);
});
it('select cells with wrong object ', () => {
gridObj.selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [12, 15] }, { rowIndex: 5, cellIndexes: [1, 2] }]);
gridObj.dataBind();
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(2);
});
it('select cells with selectCellsByRange method ', () => {
gridObj.selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 12 }, { rowIndex: 6, cellIndex: 12 });
gridObj.dataBind();
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(31);
});
afterAll(() => {
destroy(gridObj);
gridObj = selectionModule = rows = cell = null;
});
});
});
describe('Grid Touch Selection', () => {
describe('touch selection', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let gridPopUp: HTMLElement;
let spanElement: Element;
let androidPhoneUa: string = 'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JWR66Y) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.92 Safari/537.36';
beforeAll((done: Function) => {
Browser.userAgent = androidPhoneUa;
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('gridPopUp display testing', () => {
rows = gridObj.getRows();
selectionModule = gridObj.selectionModule;
gridPopUp = gridObj.element.querySelector('.e-gridpopup') as HTMLElement;
spanElement = gridPopUp.querySelector('span');
expect(gridPopUp.style.display).toBe('none');
});
it('single row testing', () => {
(gridObj.getRows()[0].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowIndexes.length).toBe(1);
expect(gridPopUp.style.display).toBe('');
expect(spanElement.classList.contains('e-rowselect')).toBeTruthy();
});
it('multi row testing', () => {
(spanElement as HTMLElement).click();
expect(spanElement.classList.contains('e-spanclicked')).toBeTruthy();
(gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowIndexes.length).toBe(2);
expect(gridPopUp.style.display).toBe('');
expect(spanElement.classList.contains('e-rowselect')).toBeTruthy();
});
it('gridpopup hide testing', () => {
(spanElement as HTMLElement).click();
expect(gridPopUp.style.display).toBe('none');
});
afterAll(() => {
destroy(gridObj);
let desktop: string = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36';
Browser.userAgent = desktop;
gridObj = selectionModule = rows = androidPhoneUa = spanElement = null;
});
});
describe('touch selection with Freeze pane', () => {
let gridObj: Grid;
let selectionModule: Selection;
let rows: Element[];
let mRows: Element[];
let gridPopUp: HTMLElement;
let spanElement: Element;
let androidPhoneUa: string = 'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JWR66Y) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.92 Safari/537.36';
beforeAll((done: Function) => {
Browser.userAgent = androidPhoneUa;
gridObj = createGrid(
{
frozenColumns: 2,
frozenRows: 2,
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('gridPopUp display testing', () => {
rows = gridObj.getRows();
mRows = gridObj.getMovableRows();
selectionModule = gridObj.selectionModule;
gridPopUp = gridObj.element.querySelector('.e-gridpopup') as HTMLElement;
spanElement = gridPopUp.querySelector('span');
expect(gridPopUp.style.display).toBe('none');
});
it('single row testing', () => {
(rows[0].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowIndexes.length).toBe(1);
expect(gridPopUp.style.display).toBe('');
expect(spanElement.classList.contains('e-rowselect')).toBeTruthy();
});
it('multi row testing', () => {
(spanElement as HTMLElement).click();
expect(spanElement.classList.contains('e-spanclicked')).toBeTruthy();
(mRows[2].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[0].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(mRows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(selectionModule.selectedRowIndexes.length).toBe(2);
expect(gridPopUp.style.display).toBe('');
expect(spanElement.classList.contains('e-rowselect')).toBeTruthy();
});
it('gridpopup hide testing', () => {
(spanElement as HTMLElement).click();
expect(gridPopUp.style.display).toBe('none');
});
afterAll(() => {
destroy(gridObj);
let desktop: string = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36';
Browser.userAgent = desktop;
gridObj = selectionModule = rows = androidPhoneUa = spanElement = null;
});
});
// select row/cell and navigate with grouped columns
describe('select Row/cell after grouping', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
let rowSelecting: EmitType<Object>;
let cellSelected: EmitType<Object>;
let cellSelecting: EmitType<Object>;
let previousRow: HTMLElement;
let previousRowIndex: number;
let previousRowCell: HTMLElement;
let previousRowCellIndex: Object;
let preventDefault: Function = new Function();
let rows: HTMLElement[];
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowGrouping: true,
groupSettings: { columns: ['EmployeeID', 'ShipCity'] },
allowSorting: true,
allowPaging: true,
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('initial check', () => {
expect(gridObj.element.querySelectorAll('.e-groupdroparea').length).toBe(1);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].children.length).toBe(2);
expect(gridObj.element.querySelectorAll('.e-groupdroparea')[0].querySelectorAll('.e-ungroupbutton').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-ascending').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell').length).toBe(2);
expect(gridObj.getContentTable().querySelectorAll('.e-indentcell').length > 0).toBeTruthy();
expect(gridObj.groupSettings.columns.length).toBe(2);
});
it('select a row', (done: Function) => {
let rowSelected = (args: Object) => {
expect((<HTMLTableCellElement>gridObj.getContent().querySelectorAll('.e-selectionbackground')[0]).innerHTML).
toEqual(gridObj.currentViewData['records'][0]['OrderID'].toString());
expect(JSON.stringify(args['data'])).toEqual(JSON.stringify(gridObj.getSelectedRecords()[0]));
expect(args['rowIndex']).toBe(gridObj.getSelectedRowIndexes()[0]);
expect(args['row']).toEqual(gridObj.getSelectedRows()[0]);
expect(args['previousRow']).toBeUndefined();
expect(args['previousRowIndex']).toBeUndefined();
previousRow = args['previousRow'];
previousRowIndex = args['previousRowIndex'];
expect(gridObj.getRows()[0].children[2].hasAttribute('aria-selected')).toBeTruthy();
done();
};
rowSelecting = (args: Object) => {
expect(JSON.stringify(args['data'])).not.toBeUndefined();
expect(args['rowIndex']).toBe(0);
expect(args['row']).toEqual(gridObj.getRows()[0]);
expect(args['previousRow']).toBeUndefined();
expect(args['previousRowIndex']).toBeUndefined();
expect(args['isCtrlPressed']).toBeFalsy();
expect(args['isShiftPressed']).toBeFalsy();
};
gridObj.rowSelected = rowSelected;
gridObj.rowSelecting = rowSelecting;
(<HTMLElement>gridObj.getRows()[0].children[2]).click();
});
it('Check selected records', () => {
let selectedData: Object[] = gridObj.getSelectedRecords();
expect((<HTMLTableCellElement>gridObj.getContent().querySelectorAll('.e-selectionbackground')[0]).innerHTML).
toEqual(selectedData[0]['OrderID'].toString());
gridObj.rowSelected = undefined;
gridObj.rowSelecting = undefined;
});
it('DeSelect a row', (done: Function) => {
gridObj.rowSelected = undefined;
gridObj.rowSelecting = undefined;
let rowDeSelecting: EmitType<Object> = (args: Object) => {
expect(args['data']).not.toEqual(undefined);
expect(args['rowIndex']).toEqual(0);
expect(args['row']).toEqual(gridObj.getRows()[0]);
};
let rowDeSelected: EmitType<Object> = (args: Object) => {
expect(args['data']).not.toEqual(undefined);
expect(args['rowIndex']).toEqual(0);
expect(args['row']).toEqual(gridObj.getRows()[0]);
gridObj.rowSelected = undefined;
gridObj.rowSelecting = undefined;
done();
};
gridObj.rowDeselecting = rowDeSelecting;
gridObj.rowDeselected = rowDeSelected;
gridObj.selectRow(0, true);
});
//key board handling with grouping in row selection
it('press up arrow', () => {
gridObj.rowDeselecting = undefined;
gridObj.rowDeselected = undefined;
gridObj.selectRow(0, true);
let args: any = { action: 'upArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[3].classList.contains('e-selectionbackground')).toBeFalsy();
expect(gridObj.getRows()[0].children[3].hasAttribute('aria-selected')).toBeFalsy();
});
it('press ctrl+home arrow', () => {
gridObj.rowSelected = undefined;
gridObj.rowSelecting = undefined;
let args: any = { action: 'ctrlHome', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[3].classList.contains('e-selectionbackground')).toBeFalsy();
expect(gridObj.getRows()[0].children[2].hasAttribute('aria-selected')).toBeFalsy();
expect(gridObj.getRows()[1].children[3].hasAttribute('aria-selected')).toBeFalsy();
});
it('press ctrl+end arrow', () => {
gridObj.rowSelected = undefined;
gridObj.rowSelecting = undefined;
let args: any = { action: 'ctrlEnd', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[3].classList.contains('e-selectionbackground')).toBeTruthy();
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[gridObj.columns.length - 1].hasAttribute('aria-selected')).toBeTruthy();
expect(gridObj.getRows()[0].children[2].hasAttribute('aria-selected')).toBeFalsy();
});
// it('press down arrow', () => {
// let args: any = { action: 'downArrow', preventDefault: preventDefault };
// gridObj.keyboardModule.keyAction(args);
// expect(gridObj.getRows()[gridObj.getRows().length - 1].children[3].classList.contains('e-selectionbackground')).toBeTruthy();
// });
it('select multiple row with selction type "single"', () => {
gridObj.selectRows([1, 2, 4]);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[3].classList.contains('e-selectionbackground')).toBeFalsy();
expect(gridObj.getRows()[4].children[3].classList.contains('e-selectionbackground')).toBeTruthy();
gridObj.selectionSettings.type = 'Multiple';
gridObj.clearSelection();
gridObj.selectRow(11);
gridObj.dataBind();
});
it('Shift plus click event', () => {
gridObj.getRows()[gridObj.getRows().length - 4].children[3].dispatchEvent(shiftEvt);
expect(gridObj.getRows()[gridObj.getRows().length - 1].querySelectorAll('.e-selectionbackground').length).toBe(6);
expect(gridObj.getRows()[gridObj.getRows().length - 2].querySelectorAll('.e-selectionbackground').length).toBe(6);
expect(gridObj.getRows()[gridObj.getRows().length - 3].querySelectorAll('.e-selectionbackground').length).toBe(6);
expect(gridObj.getRows()[gridObj.getRows().length - 4].querySelectorAll('.e-selectionbackground').length).toBe(6);
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(24);
});
it('ctrl plus click', () => {
gridObj.getRows()[1].children[3].dispatchEvent(ctrlEvt);
expect(gridObj.getRows()[1].querySelectorAll('.e-selectionbackground').length).toBe(6);
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(30);
expect(gridObj.getRows()[1].children[3].hasAttribute('aria-selected')).toBeTruthy();
});
it('clear row selections', () => {
gridObj.selectionModule.clearRowSelection();
expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(0);
});
it('select a cell', (done: Function) => {
cellSelecting = (args: Object) => {
expect(JSON.stringify(args['data'])).not.toBeUndefined();
expect(JSON.stringify(args['cellIndex'])).toEqual(JSON.stringify({ rowIndex: 0, cellIndex: 0 }));
expect(args['currentCell']).toEqual(gridObj.getRows()[0].children[2]);
expect(args['previousRowCellIndex']).toBeUndefined();
expect(args['previousRowCell']).toBeUndefined();
expect(args['isCtrlPressed']).toBeFalsy();
expect(args['isShiftPressed']).toBeFalsy();
};
cellSelected = (args: Object) => {
expect(JSON.stringify(args['data'])).not.toBeUndefined();
expect(JSON.stringify(args['cellIndex'])).toEqual(JSON.stringify({ rowIndex: 0, cellIndex: 0 }));
expect(args['currentCell']).toEqual(gridObj.getRows()[0].children[2]);
expect(JSON.stringify(args['previousRowCellIndex'])).toBeUndefined();
expect(args['previousRowCell']).toBeUndefined();
expect(JSON.stringify(args['selectedRowCellIndex'])).toEqual(JSON.stringify([{ rowIndex: 0, cellIndexes: [0] }]));
expect(gridObj.getRows()[0].children[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
previousRowCell = args['previousRowCell'];
previousRowCellIndex = args['selectedRowCellIndex'];
done();
};
gridObj.selectionSettings.mode = 'Cell';
gridObj.selectionSettings.type = 'Single';
gridObj.cellSelected = cellSelected;
gridObj.cellSelecting = cellSelecting;
gridObj.dataBind();
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
});
it('DeSelect a cell', (done: Function) => {
gridObj.cellSelected = undefined;
gridObj.cellSelecting = undefined;
let cellDeSelecting: EmitType<Object> = (args: Object) => {
expect(args['data']).not.toEqual(undefined);
expect(args['cellIndexes'][0]['cellIndexes'][0]).toEqual(0);
expect(args['cellIndexes'][0]['rowIndex']).toEqual(0);
expect(args['cells'][0]).toEqual(gridObj.getRows()[0].children[2]);
};
let cellDeSelected: EmitType<Object> = (args: Object) => {
expect(args['data']).not.toEqual(undefined);
expect(args['cellIndexes'][0]['cellIndexes'][0]).toEqual(0);
expect(args['cellIndexes'][0]['rowIndex']).toEqual(0);
expect(args['cells'][0]).toEqual(gridObj.getRows()[0].children[2]);
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
done();
};
gridObj.cellDeselecting = cellDeSelecting;
gridObj.cellDeselected = cellDeSelected;
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, true);
});
//key board handling with grouping in cell selection
it('press left arrow', () => {
gridObj.cellDeselecting = undefined;
gridObj.cellDeselected = undefined;
let args: any = { action: 'leftArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[2].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('press right arrow', (done: Function) => {
cellSelecting = (args: Object) => {
expect(JSON.stringify(args['data'])).not.toBeUndefined();
expect(JSON.stringify(args['cellIndex'])).toEqual(JSON.stringify({ rowIndex: 0, cellIndex: 1 }));
expect(args['currentCell']).toEqual(gridObj.getRows()[0].children[3]);
expect(JSON.stringify(args['previousRowCellIndex'])).toEqual(JSON.stringify({ rowIndex: 0, cellIndex: 0 }));
expect(args['previousRowCell']).toEqual(gridObj.getRows()[0].children[2]);
expect(args['isCtrlPressed']).toBeFalsy();
expect(args['isShiftPressed']).toBeFalsy();
};
cellSelected = (args: Object) => {
expect(JSON.stringify(args['data'])).not.toBeUndefined();
expect(JSON.stringify(args['cellIndex'])).toEqual(JSON.stringify({ rowIndex: 0, cellIndex: 1 }));
expect(args['currentCell']).toEqual(gridObj.getRows()[0].children[3]);
expect(JSON.stringify(args['previousRowCellIndex'])).toEqual(JSON.stringify({ rowIndex: 0, cellIndex: 0 }));
expect(args['previousRowCell']).toEqual(gridObj.getRows()[0].children[2]);
expect(JSON.stringify(args['selectedRowCellIndex'])).toEqual(JSON.stringify([{ rowIndex: 0, cellIndexes: [1] }]));
expect(gridObj.getRows()[0].children[3].classList.contains('e-cellselectionbackground')).toBeTruthy();
done();
};
gridObj.cellSelected = cellSelected;
gridObj.cellSelecting = cellSelecting;
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
});
it('press up arrow', () => {
gridObj.cellSelected = undefined;
gridObj.cellSelecting = undefined;
let args: any = { action: 'upArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[3].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('press down arrow', () => {
let args: any = { action: 'downArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[2].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('press ctrl+home arrow', () => {
let args: any = { action: 'ctrlHome', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[2].classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('press ctrl+end arrow', () => {
let args: any = { action: 'ctrlEnd', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].lastElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('press right arrow', () => {
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].lastElementChild.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('selct multiple cell with selection type "single" ', () => {
gridObj.selectionModule.selectCells([{ rowIndex: 0, cellIndexes: [1, 2, 3] }]);
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(0);
});
it('change selection Type as multiple', () => {
gridObj.selectionSettings.type = 'Multiple';
gridObj.dataBind();
expect(gridObj.getRows()[gridObj.getRows().length - 1].lastElementChild.classList.contains('e-cellselectionbackground')).toBeFalsy();
});
it('press shiftUp arrow', () => {
let args: any = { action: 'shiftUp', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(gridObj.getColumns().length + 1);
});
it('press shiftDown arrow', () => {
let args: any = { action: 'shiftDown', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].querySelectorAll('.e-cellselectionbackground').length).toBe(1);
});
it('press shiftLeft arrow', () => {
let args: any = { action: 'shiftLeft', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].querySelectorAll('.e-cellselectionbackground').length).toBe(3);
});
it('press shiftRight arrow', () => {
let args: any = { action: 'shiftRight', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].lastElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('press shift+click arrow', () => {
gridObj.getRows()[gridObj.getRows().length - 2].children[3].dispatchEvent(shiftEvt);
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(11);
});
it('press ctrl+click arrow', () => {
gridObj.getRows()[gridObj.getRows().length - 4].children[3].dispatchEvent(ctrlEvt);
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(12);
});
it('press ctrlPlusA ', () => {
let args: any = { action: 'ctrlPlusA', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(gridObj.getColumns().length * gridObj.getRows().length);
});
it('clear cell Selection', () => {
gridObj.selectionModule.clearCellSelection();
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
(gridObj.selectionModule as any).addRemoveClassesForRow(null, false, false);
(gridObj.selectionModule as any).isDragged = true;
(gridObj.selectionModule as any).isMultiCtrlRequest = false;
(gridObj.selectionModule as any).isMultiShiftRequest = false;
(gridObj.selectionModule as any).rowCellSelectionHandler(1, 1);
(gridObj.selectionModule as any).beforeFragAppend({ requrestType: 'virtualscroll' });
(gridObj.selectionModule as any).clearSelAfterRefresh({ requrestType: 'virtualscroll' });
});
it('ctrl cell selection', () => {
// check row object and idx
gridObj.selectionModule.addCellsToSelection([{ rowIndex: 0, cellIndex: 3 }]);
expect(gridObj.getRows()[0].children[5].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
gridObj = rowSelecting = cellSelected = rows = cellSelecting = preventDefault = null;
});
});
// navigate selected cells with hidden columns
describe('select Row/cell in show/hide', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
let columns: any;
let rowSelected: EmitType<Object>;
let rowSelecting: EmitType<Object>;
let cellSelected: EmitType<Object>;
let cellSelecting: EmitType<Object>;
let previousRow: HTMLElement;
let previousRowIndex: number;
let previousRowCell: HTMLElement;
let previousRowCellIndex: Object;
let preventDefault: Function = new Function();
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{ field: 'OrderID', headerText: 'Order ID', visible: false },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID', visible: false },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country', visible: false }],
allowPaging: true,
selectionSettings: { mode: 'Cell', type: 'Multiple' },
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('initial check', () => {
expect(gridObj.getHeaderContent().querySelectorAll('.e-headercell.e-hide').length).toBe(3);
expect(gridObj.getContentTable().querySelectorAll('.e-hide').length).toBe(36);
});
it('select a cell', (done: Function) => {
cellSelected = (args: Object) => {
expect(gridObj.getRows()[0].children[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[0].children[1].hasAttribute('aria-selected')).toBeTruthy();
done();
};
gridObj.cellSelected = cellSelected;
gridObj.selectCell({ rowIndex: 0, cellIndex: 1 }, true);
gridObj.dataBind();
});
//key board handling with hidden in cell selection
it('press left arrow', () => {
gridObj.cellSelected = undefined;
let args: any = { action: 'leftArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[0].children[1].hasAttribute('aria-selected')).toBeTruthy();
expect(gridObj.getRows()[0].children[1].hasAttribute('aria-label')).toBeTruthy();
});
it('press right arrow', () => {
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[3].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[0].children[3].hasAttribute('aria-selected')).toBeTruthy();
});
it('press up arrow', () => {
let args: any = { action: 'upArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[3].classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(gridObj.getRows()[0].children[3].hasAttribute('aria-selected')).toBeFalsy();
});
it('press down arrow', () => {
let args: any = { action: 'downArrow', preventDefault: preventDefault, target: document.activeElement };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[3].classList.contains('e-cellselectionbackground')).toBeTruthy();
});
it('press ctrl+home arrow', () => {
let args: any = { action: 'ctrlHome', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[0].children[1].hasAttribute('aria-selected')).toBeTruthy();
});
it('press ctrl+end arrow', () => {
let args: any = { action: 'ctrlEnd', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
it('press right arrow', () => {
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
it('change selection Type as multiple', () => {
gridObj.selectionSettings.type = 'Multiple';
gridObj.dataBind();
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
it('press shiftUp arrow', () => {
let args: any = { action: 'shiftUp', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(gridObj.getColumns().length + 1);
expect(gridObj.getRows()[gridObj.getRows().length - 2].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
it('press shiftDown arrow', () => {
let args: any = { action: 'shiftDown', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].querySelectorAll('.e-cellselectionbackground').length).toBe(1);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
it('press shiftLeft arrow', () => {
let args: any = { action: 'shiftLeft', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].querySelectorAll('.e-cellselectionbackground').length).toBe(2);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[3].hasAttribute('aria-selected')).toBeTruthy();
});
it('press shiftRight arrow', () => {
let args: any = { action: 'shiftRight', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
it('clear cell Selection', () => {
gridObj.selectionModule.clearCellSelection();
expect(gridObj.element.querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(gridObj.getRows()[gridObj.getRows().length - 1].children[4].hasAttribute('aria-selected')).toBeFalsy();
gridObj.selectionModule = null;
gridObj.getSelectedRows();
});
afterAll(() => {
destroy(gridObj);
gridObj = rowSelecting = cellSelected = cellSelecting = preventDefault = null;
});
});
// navigate selected cells with hidden columns
describe('cell span selection', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
let columns: any;
let rowSelected: EmitType<Object>;
let rowSelecting: EmitType<Object>;
let cellSelected: EmitType<Object>;
let cellSelecting: EmitType<Object>;
let previousRow: HTMLElement;
let previousRowIndex: number;
let previousRowCell: HTMLElement;
let previousRowCellIndex: Object;
let preventDefault: Function = new Function();
let shiftEvt: MouseEvent = document.createEvent('MouseEvent');
shiftEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, true, false, /* modifier keys */
0 /*left*/, null
);
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowPaging: true,
selectionSettings: { mode: 'Cell', type: 'Multiple' },
actionBegin: actionBegin,
actionComplete: actionComplete,
queryCellInfo: function (args: QueryCellInfoEventArgs) {
if (args.column.field === 'OrderID' && args.data['OrderID'] === 10248) {
args.colSpan = 2;
}
if (args.column.field === 'ShipCity' && args.data['ShipCity'] === 'Münster') {
args.colSpan = 2;
}
}
}, done);
});
it('select after spanned cell', (done: Function) => {
cellSelected = (args: Object) => {
expect(gridObj.getRows()[0].children[1].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[0].children[1].hasAttribute('aria-selected')).toBeTruthy();
expect(gridObj.getRows()[0].children[1].getAttribute('aria-colindex')).toBe('2');
gridObj.cellSelected = undefined;
done();
};
gridObj.cellSelected = cellSelected;
gridObj.selectCell({ rowIndex: 0, cellIndex: 2 }, true);
gridObj.dataBind();
});
it('press left arrow from adjacent cell of spanned cell', () => {
``
let args: any = { action: 'leftArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].children[0].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[0].children[0].hasAttribute('aria-selected')).toBeTruthy();
expect(gridObj.getRows()[0].children[0].hasAttribute('aria-label')).toBeTruthy();
});
it('press right arrow to select span cell from left adjacent cell', () => {
gridObj.selectCell({ rowIndex: 1, cellIndex: 3 }, true);
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[1].children[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[1].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
it('press right arrow from spanned cell', () => {
let args: any = { action: 'rightArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[2].children[0].classList.contains('e-cellselectionbackground')).toBeFalsy();
expect(gridObj.getRows()[2].children[0].hasAttribute('aria-selected')).toBeFalsy();
});
it('press up arrow', () => {
let args: any = { action: 'upArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[0].querySelector('.e-cellselectionbackground')).not.toBeNull();
});
it('press down arrow', () => {
let args: any = { action: 'downArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[1].querySelector('.e-cellselectionbackground')).not.toBeNull();
});
it('press shiftDown arrow', () => {
let args: any = { action: 'shiftDown', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[2].querySelectorAll('.e-cellselectionbackground')).not.toBeNull();
});
it('press shiftUp arrow', () => {
let args: any = { action: 'shiftUp', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContent().querySelectorAll('.e-cellselectionbackground').length).toBe(1);
});
it('press shiftLeft arrow', () => {
let args: any = { action: 'shiftLeft', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[1].querySelectorAll('.e-cellselectionbackground').length).toBe(2);
expect(gridObj.getRows()[1].querySelectorAll('[aria-selected]')).not.toBeNull();
});
it('press shiftRight arrow', () => {
let args: any = { action: 'shiftRight', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[1].querySelectorAll('.e-cellselectionbackground').length).toBe(1);
});
it('ctrl click', () => {
gridObj.getRows()[1].children[4].dispatchEvent(ctrlEvt);
gridObj.getRows()[0].children[0].dispatchEvent(ctrlEvt);
gridObj.getRows()[0].children[4].dispatchEvent(ctrlEvt);
expect(gridObj.getRows()[0].querySelectorAll('.e-cellselectionbackground').length).toBe(2);
expect(gridObj.getRows()[1].querySelectorAll('.e-cellselectionbackground').length).toBe(0);
expect(gridObj.getRows()[2].querySelectorAll('.e-cellselectionbackground').length).toBe(0);
});
it('press down arrow to spanned cell', () => {
gridObj.selectCell({ rowIndex: 0, cellIndex: 5 }, true);
let args: any = { action: 'downArrow', preventDefault: preventDefault };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getRows()[1].children[4].classList.contains('e-cellselectionbackground')).toBeTruthy();
expect(gridObj.getRows()[1].children[4].hasAttribute('aria-selected')).toBeTruthy();
});
afterAll((done) => {
destroy(gridObj);
setTimeout(function () {
done();
}, 1000);
gridObj = rowSelecting = cellSelected = cellSelecting = preventDefault = null;
});
});
describe('Grid Selection Issue Fixes', () =>{
let gridObj: Grid;
beforeAll((done) => {
gridObj = createGrid({
dataSource: data,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' }],
allowPaging: true,
selectedRowIndex: 0
}, done);
});
it('change selectedrowindex', () => {
gridObj.selectedRowIndex = 3,
gridObj.dataBind();
let rows = gridObj.getRows();
expect(rows[3].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[3].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
expect(gridObj.getSelectedRecords().length).toBe(1);
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
});
it('check de select', (done: Function) => {
gridObj.rowDeselected = () => {
expect(true).toBeTruthy();
done();
};
gridObj.selectRow(0, true);
});
it('EJ2-6930-Check all checkbox issue', () => {
gridObj.refreshHeader();
(<HTMLElement>gridObj.element.querySelector('.e-checkselectall')).click();
expect((<any>gridObj.element.querySelector('.e-checkselectall').nextSibling).classList.contains('e-check')).toBeTruthy();
});
it('EJ2-7517- Group Toogle button check', () => {
gridObj.groupSettings.showToggleButton = true;
gridObj.dataBind();
expect((<any>gridObj.element.querySelector('.e-headerchkcelldiv').querySelector('.e-grptogglebtn'))).toBeNull();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Cell Selection Issue Fixes', () =>{
let gridObj: Grid;
let cellSelected: EmitType<Object>;
beforeAll((done) => {
gridObj = createGrid({
dataSource: data,
allowPaging: true,
allowSelection: true,
selectionSettings: { mode: 'Cell' },
enableHover: false,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'OrderID', width: 180 },
{
headerText: 'Employee Image', textAlign: 'Center',
template: '<div>${CustomerID}</div>', width: 150
},
{ field: 'ShipPostalCode', headerText: 'ShipPostalCode', width: 195, textAlign: 'Right' },
{ field: 'ShipCity', headerText: 'ShipCity', width: 120 },
{ field: 'ShipCountry', headerText: 'ShipCountry', width: 130}
],
pageSettings: { pageCount: 2 },
cellSelected: cellSelected
}, done);
});
it('select the cell', () => {
expect(gridObj.getRows()[0].children[0].classList.contains('e-gridchkbox')).toBeTruthy();
});
it('select the cell', () => {
cellSelected = (args: {currentCell: any}) => {
expect(args.currentCell.classList.contains('e-cellselectionbackground')).toBeTruthy();
gridObj.cellSelected = undefined;
};
gridObj.cellSelected = cellSelected;
gridObj.selectCell({ rowIndex: 0, cellIndex: 2 }, true);
gridObj.dataBind();
});
afterAll(() => {
destroy(gridObj);
gridObj = cellSelected = null;
});
});
// describe('Grid checkbox selection functionality', () => {
// describe('grid checkbox selection functionality with persist selection', () => {
// let gridObj: Grid;
// let elem: HTMLElement = createElement('div', { id: 'Grid' });
// let selectionModule: Selection;
// let rows: Element[];
// let preventDefault: Function = new Function();
// let chkAllObj: HTMLElement;
// beforeAll((done: Function) => {
// let dataBound: EmitType<Object> = () => { done(); };
// document.body.appendChild(elem);
// gridObj = new Grid(
// {
// dataSource: data, dataBound: dataBound,
// columns: [
// { type: 'checkbox', width: 50 },
// { headerText: 'OrderID', isPrimaryKey: true, field: 'OrderID' },
// { headerText: 'CustomerID', field: 'CustomerID' },
// { headerText: 'EmployeeID', field: 'EmployeeID' },
// { headerText: 'ShipCountry', field: 'ShipCountry' },
// { headerText: 'ShipCity', field: 'ShipCity' },
// ],
// allowSelection: true,
// pageSettings: { pageSize: 5 },
// allowPaging: true,
// allowSorting: true,
// selectionSettings: { persistSelection: true }
// });
// gridObj.appendTo('#Grid');
// });
// it('checkbox selection with persist selection on paging', () => {
// selectionModule = gridObj.selectionModule;
// rows = gridObj.getRows();
// chkAllObj = gridObj.element.querySelector('.e-checkselectall') as HTMLElement;
// selectionModule.selectRows([1, 2]);
// expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[1].querySelector('.e-checkselect'))).toBeTruthy();
// expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[2].querySelector('.e-checkselect'))).toBeTruthy();
// expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(12);
// expect(selectionModule.selectedRecords.length).toBe(2);
// expect(selectionModule.selectedRowIndexes.length).toBe(2);
// expect(chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// gridObj.goToPage(2);
// gridObj.goToPage(1);
// expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[1].querySelector('.e-checkselect'))).toBeTruthy();
// expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[2].querySelector('.e-checkselect'))).toBeTruthy();
// expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(12);
// expect(selectionModule.selectedRecords.length).toBe(2);
// expect(selectionModule.selectedRowIndexes.length).toBe(2);
// expect(chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// (gridObj.element.querySelectorAll('.e-checkselect')[0] as HTMLElement).click();
// expect(chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// });
// it('checkbox selection with check all checkbox', () => {
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// expect(!chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// (gridObj.getCellFromIndex(0, 1) as HTMLElement).click();
// });
// it('checkbox selection through down and up keys', () => {
// let args: any = { action: 'downArrow', preventDefault: preventDefault };
// for (let i = 0; i < rows.length; i++) {
// args.target = (rows[i].querySelector('.e-checkselect') as HTMLElement);
// gridObj.keyboardModule.keyAction(args);
// }
// args.action = 'upArrow';
// for (let i = 0; i < rows.length; i++) {
// args.target = (rows[i].querySelector('.e-checkselect') as HTMLElement);
// gridObj.keyboardModule.keyAction(args);
// }
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// args.action = 'downArrow';
// args.target = (gridObj.element.querySelector('.e-checkselectall') as HTMLElement);
// gridObj.keyboardModule.keyAction(args);
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// expect(!chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// });
// it('checkbox selection through space key', () => {
// gridObj.element.focus();
// (<any>gridObj).focusModule.setActive(true);
// let args: any = { action: 'space', preventDefault: preventDefault };
// let chkBox: HTMLElement = (rows[2].querySelector('.e-checkselect') as HTMLElement);
// args.target = chkBox;
// gridObj.keyboardModule.keyAction(args);
// chkBox = (gridObj.element.querySelector('.e-checkselectall') as HTMLElement);
// args.target = chkBox;
// gridObj.keyboardModule.keyAction(args);
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// expect(!chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// });
// afterAll(() => {
// gridObj.destroy();
// remove(elem);
// });
// });
// describe('grid checkbox selection functionality with dialog editing', () => {
// let gridObj: Grid;
// let elem: HTMLElement = createElement('div', { id: 'Grid' });
// let selectionModule: Selection;
// let chkAllObj: HTMLElement;
// let rows: Element[];
// beforeAll((done: Function) => {
// let dataBound: EmitType<Object> = () => { gridObj.dataBound = null; gridObj.element.focus(); done(); };
// document.body.appendChild(elem);
// gridObj = new Grid(
// {
// dataSource: employeeSelectData, dataBound: dataBound,
// columns: [
// { type: 'checkbox', width: 50 },
// { field: 'EmployeeID', isPrimaryKey: true, headerText: 'Employee ID', textAlign: 'Right', width: 135, },
// { field: 'FirstName', headerText: 'Name', width: 125 },
// { field: 'Title', headerText: 'Title', width: 180 },
// ],
// allowSelection: true,
// toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
// editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog' },
// pageSettings: { pageSize: 5 },
// allowPaging: true,
// allowSorting: true,
// allowFiltering: true,
// selectionSettings: { persistSelection: true }
// });
// gridObj.appendTo('#Grid');
// });
// it('test checkbox selection with dialog editing', () => {
// (<any>gridObj.editModule).editModule.dblClickHandler({ target: (<any>gridObj.contentModule.getTable()).rows[0].cells[0] });
// gridObj.endEdit();
// expect(gridObj.selectionModule.selectedRecords.length === 0).toBeTruthy();
// });
// it('checkbox selection on adding new record with dialog editing', () => {
// chkAllObj = gridObj.element.querySelector('.e-checkselectall') as HTMLElement;
// (document.getElementsByClassName('e-add')[0] as HTMLElement).click();
// (document.getElementsByClassName('e-field')[0] as HTMLInputElement).click();
// (document.getElementsByClassName('e-field')[1] as HTMLInputElement).value = "222";
// (document.getElementsByClassName('e-field')[2] as HTMLInputElement).value = "Angier";
// (document.getElementsByClassName('e-field')[3] as HTMLInputElement).value = "Sales Manager";
// (document.getElementsByClassName('e-primary')[2] as HTMLElement).click();
// expect(!chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// });
// it('checkbox selection on adding new record with normal editing', () => {
// gridObj.editSettings.mode = 'Normal';
// gridObj.dataBind();
// expect(gridObj.editSettings.mode === 'Normal').toBeTruthy();
// (document.getElementsByClassName('e-add')[0] as HTMLElement).click();
// (document.getElementsByClassName('e-field')[0] as HTMLInputElement).click();
// (document.getElementsByClassName('e-field')[1] as HTMLInputElement).value = "222";
// (document.getElementsByClassName('e-field')[2] as HTMLInputElement).value = "Angier";
// (document.getElementsByClassName('e-field')[3] as HTMLInputElement).value = "Sales Manager";
// (gridObj.getCellFromIndex(2, 2) as HTMLElement).click();
// (document.getElementsByClassName('e-add')[0] as HTMLElement).click();
// (document.getElementsByClassName('e-field')[0] as HTMLInputElement).click();
// (document.getElementsByClassName('e-field')[1] as HTMLInputElement).value = "222";
// (document.getElementsByClassName('e-field')[2] as HTMLInputElement).value = "Fallen";
// (document.getElementsByClassName('e-field')[3] as HTMLInputElement).value = "Sales Manager";
// (gridObj.element.querySelectorAll('.e-checkselect')[1] as HTMLElement).click();
// });
// afterAll(() => {
// gridObj.destroy();
// remove(elem);
// });
// });
// describe('grid checkbox selection functionality without persist selection', () => {
// let gridObj: Grid;
// let elem: HTMLElement = createElement('div', { id: 'Grid' });
// let selectionModule: Selection;
// let rows: Element[];
// beforeAll((done: Function) => {
// let dataBound: EmitType<Object> = () => { done(); };
// document.body.appendChild(elem);
// gridObj = new Grid(
// {
// dataSource: employeeSelectData, dataBound: dataBound,
// columns: [
// { type: 'checkbox', width: 50 },
// { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 135, },
// { field: 'FirstName', headerText: 'Name', width: 125 },
// { field: 'Title', headerText: 'Title', width: 180 },
// ],
// allowSelection: true,
// editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog' },
// pageSettings: { pageSize: 5 },
// allowPaging: true,
// allowSorting: true,
// selectionSettings: { type: 'Multiple' }
// });
// gridObj.appendTo('#Grid');
// });
// it('Test checkbox selection', () => {
// selectionModule = gridObj.selectionModule;
// rows = gridObj.getRows();
// selectionModule.selectRows([1, 2]);
// expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[1].querySelector('.e-checkselect'))).toBeTruthy();
// expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[2].querySelector('.e-checkselect'))).toBeTruthy();
// expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(8);
// expect(selectionModule.selectedRecords.length).toBe(2);
// expect(selectionModule.selectedRowIndexes.length).toBe(2);
// gridObj.goToPage(2);
// gridObj.goToPage(1);
// });
// it('checkbox selection on editing', () => {
// (<any>gridObj.editModule).editModule.dblClickHandler({ target: gridObj.getCellFromIndex(0, 0) });
// gridObj.endEdit();
// expect(gridObj.selectionModule.selectedRecords.length === 1).toBeTruthy();
// });
// afterAll(() => {
// gridObj.destroy();
// remove(elem);
// });
// });
// describe('persist selection functionality without checkbox', () => {
// let gridObj: Grid;
// let elem: HTMLElement = createElement('div', { id: 'Grid' });
// let selectionModule: Selection;
// let rows: Element[];
// beforeAll((done: Function) => {
// let dataBound: EmitType<Object> = () => { done(); };
// document.body.appendChild(elem);
// gridObj = new Grid(
// {
// dataSource: data, dataBound: dataBound,
// columns: [
// { headerText: 'OrderID', isPrimaryKey: true, field: 'OrderID' },
// { headerText: 'CustomerID', field: 'CustomerID' },
// { headerText: 'EmployeeID', field: 'EmployeeID' },
// { headerText: 'ShipCountry', field: 'ShipCountry' },
// { headerText: 'ShipCity', field: 'ShipCity' },
// ],
// allowSelection: true,
// pageSettings: { pageSize: 5 },
// allowPaging: true,
// selectionSettings: { persistSelection: true }
// });
// gridObj.appendTo('#Grid');
// });
// it('persist selection', () => {
// selectionModule = gridObj.selectionModule;
// rows = gridObj.getRows();
// selectionModule.selectRow(1, true);
// expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(5);
// expect(selectionModule.selectedRecords.length).toBe(1);
// expect(selectionModule.selectedRowIndexes.length).toBe(1);
// gridObj.goToPage(2);
// gridObj.goToPage(1);
// expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(5);
// expect(selectionModule.selectedRecords.length).toBe(1);
// expect(selectionModule.selectedRowIndexes.length).toBe(1);
// });
// afterAll(() => {
// gridObj.destroy();
// remove(elem);
// });
// });
// describe('grid checkbox selection functionality and selection persistance with virtualization', () => {
// let gridObj: Grid;
// let elem: HTMLElement = createElement('div', { id: 'Grid' });
// let selectionModule: Selection;
// let rows: Element[];
// beforeAll((done: Function) => {
// let dataBound: EmitType<Object> = () => { done(); };
// document.body.appendChild(elem);
// gridObj = new Grid(
// {
// dataSource: data, dataBound: dataBound,
// columns: [
// { type: 'checkbox' },
// { headerText: 'OrderID', isPrimaryKey: true, field: 'OrderID' },
// { headerText: 'CustomerID', field: 'CustomerID' },
// { headerText: 'EmployeeID', field: 'EmployeeID' },
// { headerText: 'ShipCountry', field: 'ShipCountry' },
// { headerText: 'ShipCity', field: 'ShipCity' },
// ],
// allowSelection: true,
// enableVirtualization: true,
// selectionSettings: { persistSelection: true }
// });
// gridObj.appendTo('#Grid');
// });
// it('Test checkbox selection and persist selection', () => {
// selectionModule = gridObj.selectionModule;
// rows = gridObj.getRows();
// let chkAllObj: HTMLElement = gridObj.element.querySelector('.e-checkselectall') as HTMLElement;
// selectionModule.selectRows([1, 2]);
// expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[1].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[1].querySelector('.e-checkselect'))).toBeTruthy();
// expect(rows[2].hasAttribute('aria-selected')).toBeTruthy();
// expect(rows[2].firstElementChild.classList.contains('e-selectionbackground')).toBeTruthy();
// expect(!isNullOrUndefined(rows[2].querySelector('.e-checkselect'))).toBeTruthy();
// expect(gridObj.element.querySelectorAll('.e-selectionbackground').length).toBe(12);
// expect(selectionModule.selectedRecords.length).toBe(2);
// expect(selectionModule.selectedRowIndexes.length).toBe(2);
// expect(chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// });
// afterAll(() => {
// gridObj.destroy();
// remove(elem);
// });
// });
// describe('grid checkbox selection functionaly with datasource field', () => {
// let gridObj: Grid;
// let elem: HTMLElement = createElement('div', { id: 'Grid' });
// let selectionModule: Selection;
// let rows: Element[];
// let chkAllObj: HTMLElement;
// beforeAll((done: Function) => {
// let dataBound: EmitType<Object> = () => { done(); };
// document.body.appendChild(elem);
// gridObj = new Grid(
// {
// dataSource: employeeSelectData, dataBound: dataBound,
// columns: [
// { type: 'checkbox', field: 'IsAutoSelect' },
// { field: 'EmployeeID', isPrimaryKey: true, headerText: 'Employee ID', textAlign: 'Right', width: 135, },
// { field: 'FirstName', headerText: 'Name', width: 125 },
// { field: 'Title', headerText: 'Title', width: 180 },
// ],
// allowSelection: true,
// editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Normal' },
// pageSettings: { pageSize: 5 },
// allowPaging: true,
// selectionSettings: { persistSelection: true }
// });
// gridObj.appendTo('#Grid');
// });
// it('checkbox selection with persist selection on paging', (done: Function) => {
// setTimeout(
// () => {
// selectionModule = gridObj.selectionModule;
// chkAllObj = gridObj.element.querySelector('.e-checkselectall') as HTMLElement;
// rows = gridObj.getRows();
// gridObj.goToPage(2);
// gridObj.goToPage(1);
// expect(chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// done();
// },
// 200);
// });
// it('checkbox selection with check all checkbox', (done: Function) => {
// setTimeout(
// () => {
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// expect(!chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// done();
// },
// 500);
// });
// it('edit checkbox selection on editing', (done: Function) => {
// setTimeout(
// () => {
// (<any>gridObj.editModule).editModule.dblClickHandler({ target: gridObj.getCellFromIndex(0, 0) });
// let preventDefault: Function = new Function();
// let args: any = { action: 'tab', preventDefault: preventDefault };
// gridObj.keyboardModule.keyAction(args);
// (gridObj.element.querySelector('.e-edit-checkselect') as HTMLElement).click();
// (gridObj.element.querySelector('.e-edit-checkselect') as HTMLElement).click();
// gridObj.endEdit();
// (<any>gridObj.editModule).editModule.dblClickHandler({ target: gridObj.getCellFromIndex(0, 0) });
// (gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
// expect(!chkAllObj.nextElementSibling.classList.contains('e-stop')).toBeTruthy();
// done();
// },
// 500);
// });
// afterAll(() => {
// gridObj.destroy();
// remove(elem);
// });
// });
// });
describe('grid checkbox selection binding with data source', () => {
let gridObj: Grid;
let rowSelected: () => void;
beforeAll((done: Function) => {
let options: Object = {
dataSource: [{ 'UnitsInStock': 39, 'Discontinued': false },
{ 'UnitsInStock': 17, 'Discontinued': false },
{ 'UnitsInStock': 13, 'Discontinued': true },
{ 'UnitsInStock': 53, 'Discontinued': false },
{ 'UnitsInStock': 0, 'Discontinued': true },
{ 'UnitsInStock': 120, 'Discontinued': false }],
rowSelected: rowSelected,
columns: [
{ field: 'UnitsInStock', headerText: 'Units In Stock', width: 160, textAlign: 'Right' },
{
field: 'Discontinued', headerText: 'Discontinued', width: 150, textAlign: 'Center', type: 'checkbox',
},
],
allowSelection: true,
allowSorting: true,
}
gridObj = createGrid(options, done);
});
it('checkbox selection bind with datasource', (done: Function) => {
done();
// rowSelected = (): void => {
// // expect(gridObj.selectionModule.selectedRecords.length).toBe(2);
// // expect(gridObj.selectionModule.selectedRowIndexes.length).toBe(2);
// done();
// };
// gridObj.rowSelected = rowSelected;
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Grid Selection Issue Fixes', () =>{
let gridObj: Grid;
let rowSelected: () => void;
beforeAll((done) => {
gridObj = createGrid({
dataSource: data,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' }],
allowPaging: true,
rowSelected: rowSelected
}, done);
});
it('Selecting First row', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
gridObj.isCheckBoxSelection = false;
(<HTMLElement>gridObj.element.querySelectorAll('.e-row')[0].querySelector('.e-rowcell')).click();
});
it('Selecting Second row', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(<HTMLElement>gridObj.element.querySelectorAll('.e-row')[1].querySelector('.e-rowcell')).click();
});
it('Selecting Third row', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(2);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(<HTMLElement>gridObj.element.querySelectorAll('.e-row')[2].querySelector('.e-gridchkbox')
.querySelector('.e-checkbox-wrapper')).click();
});
it('multi row - ctrl click testing- selecting Fourth row', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(3);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(gridObj.selectionModule as any).clickHandler({target: gridObj.element.querySelectorAll('.e-row')[3]
.querySelectorAll('.e-rowcell')[2], ctrlKey: true});
});
it('Selecting First row', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
gridObj.isCheckBoxSelection = false;
(<HTMLElement>gridObj.element.querySelectorAll('.e-row')[0].querySelector('.e-rowcell')).click();
});
it('multi row - Shift click testing', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(4);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(gridObj.selectionModule as any)
.clickHandler({target: gridObj.element.querySelectorAll('.e-row')[3].querySelectorAll('.e-rowcell')[2], shiftKey: true});
});
it('Selecting First row', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
gridObj.isCheckBoxSelection = false;
(<HTMLElement>gridObj.element.querySelectorAll('.e-row')[0].querySelector('.e-rowcell')).click();
});
it('Shift + Clicking Checkbox in Fourth Row', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(2);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(gridObj.selectionModule as any)
.clickHandler({target: gridObj.element.querySelectorAll('.e-row')[3].querySelector('.e-gridchkbox')
.querySelector('.e-checkbox-wrapper'), shiftKey: true});
});
afterAll(() => {
destroy(gridObj);
});
});
});
describe('Row,cell Selecting in batch edit while adding record => ', () => {
let gridObj: Grid;
let preventDefault: Function = new Function();
let rowSelected: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
editSettings: {
allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch',
showConfirmDialog: false, showDeleteConfirmDialog: false
},
toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
allowPaging: true,
columns: [
{ field: 'OrderID', type: 'number', isPrimaryKey: true, visible: true, validationRules: { required: true } },
{ field: 'CustomerID', type: 'string' },
{ field: 'EmployeeID', type: 'number', allowEditing: false },
{ field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' },
],
rowSelected: rowSelected
}, done);
});
it('rowSelect event while adding new records in batchedit', () => {
rowSelected = (args?: any): void => {
expect(args.data.OrderID).toBe(0);
}
gridObj.rowSelected = rowSelected;
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
gridObj.editModule.saveCell();
expect(gridObj.selectionModule.getCurrentBatchRecordChanges().length).toBe(14);
});
it('rowSelect event while adding delete record in currentview data',() => {
gridObj.clearSelection();
gridObj.rowSelected = null;
gridObj.selectRow(5, true);
gridObj.editModule.deleteRecord();
expect(gridObj.selectionModule.getCurrentBatchRecordChanges().length).toBe(13);
});
it('recordClick event in Grid', () => {
gridObj.recordClick = (args: any): void => {
expect(args.rowIndex).toBe(2);
expect(args.cellIndex).toBe(1);
expect(args.column.field).toBe('CustomerID');
}
(gridObj.getContent().querySelectorAll('.e-row')[2].querySelectorAll('.e-rowcell')[1] as
HTMLElement).click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('enableSimpleMultiRowSelection property Testing => ', () => {
let gridObj: Grid;
let rows: Element[];
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
allowPaging: true,
selectionSettings: { type:'Multiple', enableSimpleMultiRowSelection: true},
columns: [
{ field: 'OrderID', type: 'number', isPrimaryKey: true, visible: true },
{ field: 'CustomerID', type: 'string' },
{ field: 'EmployeeID', type: 'number', allowEditing: false },
{ field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' },
]
}, done);
});
it('Multiple row selection without pressing ctrl/shift', () => {
gridObj.selectRow(0);
rows = gridObj.getRows();
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
gridObj.selectRow(1);
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
gridObj.selectRow(1);
expect(rows[0].hasAttribute('aria-selected')).toBeTruthy();
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
});
it('enableToggle Property check without pressing ctrl/shift', () => {
gridObj.selectionSettings.enableToggle = false;
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
});
it('enableToggle Property check by pressing ctrl/shift', () => {
rows[1].firstChild.dispatchEvent(ctrlEvt);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('enableToggle property Testing => ', () => {
let gridObj: Grid;
let rows: Element[];
let ctrlEvt: MouseEvent = document.createEvent('MouseEvent');
ctrlEvt.initMouseEvent(
'click',
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
true, false, false, false, /* modifier keys */
0 /*left*/, null
);
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
allowPaging: true,
selectionSettings: { type:'Multiple', enableToggle: false},
columns: [
{ type: 'checkbox', width: 50},
{ field: 'OrderID', type: 'number', isPrimaryKey: true, visible: true },
{ field: 'CustomerID', type: 'string' },
{ field: 'EmployeeID', type: 'number', allowEditing: false },
{ field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' },
]
}, done);
});
it('enableToggle(false) Property check without pressing ctrl/shift', () => {
rows = gridObj.getRows();
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
});
it('enableToggle(false) Property check by pressing ctrl key', () => {
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
rows[1].firstChild.dispatchEvent(ctrlEvt);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
gridObj.selectionSettings.enableToggle = true;
});
it('enableToggle(true) Property check without pressing ctrl/shift', () => {
expect(gridObj.selectionSettings.enableToggle).toBeTruthy();
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
});
it('enableToggle(true) Property check by pressing ctrl key', () => {
(rows[1].querySelector('.e-rowcell') as HTMLElement).click();
expect(rows[1].hasAttribute('aria-selected')).toBeTruthy();
rows[1].firstChild.dispatchEvent(ctrlEvt);
expect(rows[1].hasAttribute('aria-selected')).toBeFalsy();
});
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);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('grid checkbox selection functionalities with Freeze pane', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
frozenColumns: 2,
frozenRows: 1,
dataSource: data,
allowSelection: true,
allowPaging: true,
pageSettings: { pageSize: 6},
columns: [
{ type:'checkbox', width: 40},
{ headerText: 'OrderID', field: 'OrderID' },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
}, done);
});
it('checkbox type check', () =>{
let colType: string = 'checkbox';
expect(gridObj.getVisibleColumns()[0].type).toBe(colType);
});
it('Checkbox select all', () => {
(gridObj.element.querySelector('.e-headercelldiv').querySelectorAll('.e-frame.e-icons')[0] as any).click();
expect(gridObj.getSelectedRowIndexes().length).toBe(6);
expect(gridObj.element.querySelectorAll('.e-frame.e-icons.e-check').length).toBe(7);
});
it('checkbox deselect check', () => {
(gridObj.element.querySelector('.e-headercontent').querySelectorAll('.e-rowcell')[0] as any).click();
expect(gridObj.getSelectedRowIndexes().length).toBe(5);
expect(gridObj.element.querySelector('.e-headercelldiv').querySelectorAll('.e-stop').length).toBe(1);
(gridObj.element.querySelector('.e-headercelldiv').querySelectorAll('.e-frame.e-icons')[0] as any).click();
});
it('checkbox unselect all check', () => {
(gridObj.element.querySelector('.e-headercelldiv').querySelectorAll('.e-frame.e-icons')[0] as any).click();
expect(gridObj.element.querySelector('.e-headercelldiv').querySelectorAll('.e-uncheck').length).toBe(1);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('grid selection functionalities with Frozen rows', function () {
let gridObj: Grid;
beforeAll(function (done) {
gridObj = createGrid({
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID', isPrimaryKey: true },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
}, done);
});
it('Get rowindex from primarykey', function () {
gridObj.selectRow(gridObj.getRowIndexByPrimaryKey(10251));
gridObj.dataBind();
expect(gridObj.selectedRowIndex).toBe(3);
});
it('get rowIndex from rowdata', function () {
gridObj.selectRow(gridObj.getRowIndexByPrimaryKey({OrderID: 10253, CustomerID: "HANAR", EmployeeID: 3, ShipCity: "Rio de Janeiro",
ShipCountry: "Brazil"}));
gridObj.dataBind();
expect(gridObj.selectedRowIndex).toBe(5);
});
it('Primary key not in current page', function () {
let index = gridObj.getRowIndexByPrimaryKey(10358);
gridObj.selectRow(index);
gridObj.dataBind();
expect(index).toBe(-1);
});
afterAll(function () {
destroy(gridObj);
});
});
describe('selectRow with virtualScrolling', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: virtualData,
enableVirtualization: true,
height: 300,
columns: count500
}, done);
});
it('select 100th row in vitualized Grid', (done: Function) => {
let dataBound = () => {
expect(gridObj.getSelectedRecords().length).toBe(1);
done();
}
gridObj.dataBound = dataBound;
gridObj.selectRow(100);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('selectRow with virtualScrolling', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ headerText: 'OrderID', field: 'OrderID', isPrimaryKey: true },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
],
allowSelection: true,
selectionSettings:{mode:'Cell',type:'Multiple'},
}, done);
});
it('check cell select args', (done: Function) => {
let cellSelecting = (args: any) => {
expect(args['previousRowCell']).toBeUndefined();
expect(args['previousRowCellIndex']).toBeUndefined();
}
let cellSelected = (args: any) => {
expect(args['previousRowCell']).toBeUndefined();
expect(args['previousRowCellIndex']).toBeUndefined();
done();
}
gridObj.cellSelecting = cellSelecting;
gridObj.cellSelected = cellSelected;
gridObj.selectCell({ rowIndex: 0, cellIndex: 0 }, false);
});
it('check cell select args multiselect', (done: Function) => {
let cellSelecting = (args: any) => {
expect(args['previousRowCell']).toEqual(gridObj.getRows()[0].children[0]);
expect(args['previousRowCellIndex']).toEqual({ rowIndex: 0, cellIndex: 0 });
}
let cellSelected = (args: any) => {
expect(args['previousRowCell']).toEqual(gridObj.getRows()[0].children[0]);
expect(args['previousRowCellIndex']).toEqual({ rowIndex: 0, cellIndex: 0 });
done();
}
gridObj.cellSelecting = cellSelecting;
gridObj.cellSelected = cellSelected;
gridObj.selectionModule.addCellsToSelection([{ rowIndex: 0, cellIndex: 1 }]);
});
it('check cell select args multiselect with range', (done: Function) => {
let cellSelecting = (args: any) => {
expect(args['previousRowCell']).toEqual(gridObj.getRows()[0].children[1]);
expect(args['previousRowCellIndex']).toEqual({ rowIndex: 0, cellIndex: 1 });
}
let cellSelected = (args: any) => {
expect(args['previousRowCell']).toEqual(gridObj.getRows()[0].children[1]);
expect(args['previousRowCellIndex']).toEqual({ rowIndex: 0, cellIndex: 1 });
gridObj.clearCellSelection();
done();
}
gridObj.cellSelecting = cellSelecting;
gridObj.cellSelected = cellSelected;
gridObj.selectionModule.selectCellsByRange({ rowIndex: 1, cellIndex: 0 }, { rowIndex: 1, cellIndex: 3 });
});
it('check cell select args multiselect with cancel args', (done: Function) => {
let cellSelecting = (args: any) => {
args.cancel = true;
expect(gridObj.getSelectedRowCellIndexes.length).toBe(0);
done();
}
gridObj.cellSelecting = cellSelecting;
gridObj.selectionModule.selectCellsByRange({ rowIndex: 1, cellIndex: 0 }, { rowIndex: 1, cellIndex: 3 });
});
it('check row select args multiselect with cancel args', (done: Function) => {
let rowSelecting = (args: any) => {
args.cancel = true;
expect(gridObj.getSelectedRowIndexes.length).toBe(0);
expect(gridObj.getSelectedRows.length).toBe(0);
done();
}
gridObj.selectionSettings.mode = 'Row';
gridObj.rowSelecting = rowSelecting;
gridObj.selectionModule.selectRowsByRange(1,2);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-33599 selection does not maintain while calling setrowdata method', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
allowRowDragAndDrop: true,
columns: [
{ headerText: 'OrderID', field: 'OrderID', isPrimaryKey: true },
{ headerText: 'CustomerID', field: 'CustomerID' },
{ headerText: 'EmployeeID', field: 'EmployeeID' },
{ headerText: 'ShipCountry', field: 'ShipCountry' },
{ headerText: 'ShipCity', field: 'ShipCity' },
]
}, done);
});
it('selectrowdata', (done: Function) => {
gridObj.selectRow(0);
gridObj.setRowData(10248, { CustomerID: "aaa", Freight: 11 })
expect((<any>gridObj.getRows()[0]).cells[0].classList.contains('e-selectionbackground')).toBeTruthy();
done();
});
it('Check target in rowSelected event', (done: Function) => {
gridObj.rowSelected = (args: any) => {
expect(args.target).toBeNull();
gridObj.rowSelected = null;
done();
};
gridObj.clearSelection();
gridObj.selectRow(1);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('Checkbox state when Selecting in batch edit while adding record => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
editSettings: {
allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch',
showConfirmDialog: true, showDeleteConfirmDialog: false
},
toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
allowPaging: true,
columns: [
{ type: 'checkbox', width: 50},
{ field: 'OrderID', type: 'number', isPrimaryKey: true, visible: true },
{ field: 'CustomerID', type: 'string' },
{ field: 'EmployeeID', type: 'number', allowEditing: false },
{ field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' },
],
}, done);
});
it('Initial header checkbox state', () => {
let cBox: HTMLElement = gridObj.element.querySelector('.e-checkselectall').nextElementSibling as HTMLElement;
expect(cBox.classList.contains('e-check')).toBeFalsy();
expect(cBox.classList.contains('e-uncheck')).toBeFalsy();
expect(cBox.classList.contains('e-stop')).toBeFalsy();
})
it('Add new records, cancel and check state', (done: Function) => {
let batchCancel = (args: any): void => {
if (args.name === 'batchCancel') {
expect(gridObj.element.querySelector('.e-checkselectall').nextElementSibling.classList.contains('e-stop')).toBeFalsy();
gridObj.batchCancel = null;
done();
}
}
gridObj.batchCancel = batchCancel;
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
(gridObj.element.querySelector('.e-checkselectall') as HTMLElement).click();
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
expect(gridObj.element.querySelector('.e-checkselectall').nextElementSibling.classList.contains('e-stop')).toBeTruthy();
gridObj.editModule.batchCancel();
select('#' + gridObj.element.id + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('isInteracted property in rowSelecting and rowSelected events testing', () => {
let gridObj: Grid;
let rowSelecting: (args: any) => void;
let rowSelected: (args: any) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' },
{ field: 'ShipCity' }],
allowPaging: true,
pageSettings: { pageSize: 8, pageCount: 4, currentPage: 1 },
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('isInteracted property testing - Click', () => {
rowSelecting = (args: any) => {
expect(args.isInteracted).toBeTruthy();
};
rowSelected = (args: any) => {
expect(args.isInteracted).toBeTruthy();
};
gridObj.rowSelecting = rowSelecting;
gridObj.rowSelected = rowSelected;
(gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement).click();
});
it('isInteracted property testing - rowSelect method', () => {
rowSelecting = (args: any) => {
expect(args.isInteracted).toBeFalsy();
};
rowSelected = (args: any) => {
expect(args.isInteracted).toBeFalsy();
};
gridObj.rowSelecting = rowSelecting;
gridObj.rowSelected = rowSelected;
gridObj.selectRow(2);
});
afterAll(() => {
destroy(gridObj);
gridObj = rowSelecting = null;
gridObj = rowSelected = null;
});
});
describe('EJ2-38505 - Grid cell selection will be cleared when we press the left arrow', () => {
let gridObj: Grid;
let preventDefault: Function = new Function();
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' },
{ field: 'ShipCity' }],
frozenColumns: 2,
frozenRows: 2,
allowSelection: true,
selectionSettings: { type: 'Single', mode: 'Cell' },
}, done);
});
it('Ensure selection while pressing left arrow after selecting first cell in first row', () => {
let args: any = { action: 'leftArrow', preventDefault: preventDefault };
gridObj.selectionModule.selectCell({ rowIndex: 2, cellIndex: 0 }, true);
gridObj.keyboardModule.keyAction(args);
gridObj.keyboardModule.keyAction(args);
gridObj.keyboardModule.keyAction(args);
let rows: Element[] = gridObj.getRows();
expect(rows[2].firstElementChild.classList.contains('e-cellselectionbackground')).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('isInteracted checking after cancel the rowselecting event', () => {
let gridObj: Grid;
let rowSelecting: (args: any) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' },
{ field: 'ShipCity' }],
allowPaging: true,
pageSettings: { pageSize: 8, pageCount: 4, currentPage: 1 },
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('isInteracted property testing - Click', () => {
rowSelecting = (args: any) => {
args.cancel = true;
expect(args.isInteracted).toBeTruthy();
};
gridObj.rowSelecting = rowSelecting;
(gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement).click();
});
it('isInteracted property testing - selectRow method', () => {
rowSelecting = (args: any) => {
expect(args.target).toBeNull();
expect(args.isInteracted).toBeFalsy();
};
gridObj.rowSelecting = rowSelecting;
gridObj.selectRow(4);
});
it('isInteracted property testing - selectRows method', () => {
rowSelecting = (args: any) => {
expect(args.target).toBeNull();
expect(args.isInteracted).toBeFalsy();
};
gridObj.rowSelecting = rowSelecting;
gridObj.selectRows([2,3]);
});
it('isInteracted property testing - selectRowsByRange method', () => {
rowSelecting = (args: any) => {
expect(args.target).toBeNull();
expect(args.isInteracted).toBeFalsy();
expect(args.isInteracted).toBeDefined();
};
gridObj.rowSelecting = rowSelecting;
gridObj.selectRowsByRange(2,5);
});
afterAll(() => {
destroy(gridObj);
gridObj = rowSelecting = null;
});
});
describe('isInteracted property in rowSelecting and rowDeselected events indexes property testing', () => {
let gridObj: Grid;
let rowDeselected: (args: any) => void;
let rowSelected: (args: any) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' }],
allowPaging: true,
pageSettings: { pageSize: 8, pageCount: 4, currentPage: 1 },
allowSelection: true,
}, done);
});
it('isInteracted property testing in selectall - rowselected', () => {
rowSelected = (args: any) => {
expect(args.isInteracted).toBeTruthy();
gridObj.rowSelected = null;
};
gridObj.rowSelected = rowSelected;
(<HTMLElement>gridObj.element.querySelector('.e-checkselectall')).click();
});
it('isInteracted property testing in selectall - rowDeselected', () => {
rowDeselected = (args: any) => {
expect(args.isInteracted).toBeTruthy();
expect(args.rowIndexes).toBeDefined();
expect(args.cancel).toBeUndefined();
};
gridObj.rowDeselected = rowDeselected;
(<HTMLElement>gridObj.element.querySelector('.e-checkselectall')).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = rowSelected = null;
gridObj = rowDeselected = null;
});
});
describe('AutoFill Feature', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
enableAutoFill: true,
columns: [
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowPaging: true,
selectionSettings: { type: 'Multiple', mode: 'Cell', cellSelectionMode: 'Box' },
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch' },
}, done);
});
it('update cell', () => {
gridObj.selectionModule.selectCellsByRange({ rowIndex: 0, cellIndex: 1 },{ rowIndex: 0, cellIndex:4 });
(gridObj.selectionModule as any).startAFCell = gridObj.getRowByIndex(0).querySelectorAll('td')[1];
(gridObj.selectionModule as any).endAFCell = gridObj.getRowByIndex(2).querySelectorAll('td')[4];
(gridObj.selectionModule as any).updateStartEndCells();
(gridObj.selectionModule as any).selectLikeAutoFill(undefined,true);
gridObj.copy();
let value1: string = (document.querySelector('.e-clipboard') as HTMLInputElement).value.split(/\r?\n/)[0];
let value2: string = (document.querySelector('.e-clipboard') as HTMLInputElement).value.split(/\r?\n/)[1];
expect(value1 === value2).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('rowdeselect checking with persist selection and ResetOnRowClick', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
enableAutoFill: true,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowPaging: true,
selectionSettings: { persistSelection: true, checkboxMode: 'ResetOnRowClick' },
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true },
}, done);
});
it('selecting more than one row in checkbox and clicking in row element', () => {
(gridObj.element.querySelectorAll('.e-frame.e-icons')[1] as HTMLElement).click();
(gridObj.element.querySelectorAll('.e-frame.e-icons')[2] as HTMLElement).click();
let rowDeSelecting = (e: any) => {
expect(e.data.length).toBe(2);
};
let rowDeSelected = (e: any) => {
expect(e.data.length).toBe(2);
}
gridObj.rowDeselecting = rowDeSelecting;
gridObj.rowDeselected = rowDeSelected;
(gridObj.element.querySelectorAll('.e-rowcell.e-gridchkbox')[0] as HTMLElement).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
gridObj.rowDeselected = null;
gridObj.rowDeselecting = null;
});
});
describe('rowdeselect checking with persist selection and ResetOnRowClick', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowPaging: true,
selectionSettings: { persistSelection: true, checkboxMode: 'ResetOnRowClick' },
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true },
}, done);
});
it('selecting checkselectall ', () => {
(gridObj.element.querySelectorAll('.e-frame.e-icons')[0] as HTMLElement).click(); //selecting all row
let rowDeSelecting = (e: any) => {
expect(e.data.length).toBe(12);
};
let rowDeSelected = (e: any) => {
expect(e.data.length).toBe(12);
}
gridObj.rowDeselecting = rowDeSelecting;
gridObj.rowDeselected = rowDeSelected;
(gridObj.element.querySelectorAll('.e-rowcell.e-gridchkbox')[0] as HTMLElement).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
gridObj.rowDeselected = null;
gridObj.rowDeselecting = null;
});
describe('Ensure selection event arguments', () => {
let gridObj: Grid;
let start: number = 0;
let end: number = 3;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
allowPaging: true
}, done);
});
it('single row selecting', (done: Function) => {
let rowSelecting = (args: RowSelectingEventArgs) => {
let rows: Row<Column>[] = gridObj.getRowsObject();
expect(args.rowIndex).toBe(1);
expect(args.rowIndexes).toBeUndefined();
expect(args.data).toBe(rows[args.rowIndex].data);
expect(args.row).toBe(gridObj.getRowByIndex(args.rowIndex));
expect(args.foreignKeyData).toBe(rows[args.rowIndex].foreignKeyData);
gridObj.rowSelecting = null;
};
let rowSelected = (args: RowSelectEventArgs) => {
let rows: Row<Column>[] = gridObj.getRowsObject();
expect(args.rowIndex).toBe(1);
expect(args.rowIndexes).toBeUndefined();
expect(args.data).toBe(rows[args.rowIndex].data);
expect(args.row).toBe(gridObj.getRowByIndex(args.rowIndex));
expect(args.foreignKeyData).toBe(rows[args.rowIndex].foreignKeyData);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelecting = rowSelecting;
gridObj.rowSelected = rowSelected;
gridObj.selectRow(1);
});
it('single row de-selecting', (done: Function) => {
let rowDeselecting = (args: RowDeselectEventArgs) => {
let rows: Row<Column>[] = gridObj.getRowsObject();
expect(args.rowIndex).toBe(1);
expect(args.rowIndexes).toBeUndefined();
expect(args.data).toBe(rows[args.rowIndex].data);
expect(args.row).toBe(gridObj.getRowByIndex(args.rowIndex));
expect(args.foreignKeyData).toBe(rows[args.rowIndex].foreignKeyData);
gridObj.rowDeselecting = null;
};
let rowDeselected = (args: RowDeselectEventArgs) => {
let rows: Row<Column>[] = gridObj.getRowsObject();
expect(args.rowIndex).toBe(1);
expect(args.rowIndexes).toBeUndefined();
expect(args.data).toBe(rows[args.rowIndex].data);
expect(args.row).toBe(gridObj.getRowByIndex(args.rowIndex));
expect(args.foreignKeyData).toBe(rows[args.rowIndex].foreignKeyData);
gridObj.rowDeselected = null;
done();
};
gridObj.rowDeselecting = rowDeselecting;
gridObj.rowDeselected = rowDeselected;
gridObj.selectRow(1, true);
});
it('header checkbox selection', (done: Function) => {
let rowSelecting = (args: RowSelectingEventArgs) => {
expect(args.rowIndex).toBe(0);
expect(args.rowIndexes.length).toBe(gridObj.currentViewData.length);
expect((args.data as Object[]).length).toBe(gridObj.currentViewData.length);
expect((args.row as Element[]).length).toBe(gridObj.currentViewData.length);
expect((args.foreignKeyData as Object[]).length).toBe(gridObj.currentViewData.length);
gridObj.rowSelecting = null;
};
let rowSelected = (args: RowSelectEventArgs) => {
expect(args.rowIndex).toBe(0);
expect(args.rowIndexes.length).toBe(gridObj.currentViewData.length);
expect((args.data as Object[]).length).toBe(gridObj.currentViewData.length);
expect((args.row as Element[]).length).toBe(gridObj.currentViewData.length);
expect((args.foreignKeyData as Object[]).length).toBe(gridObj.currentViewData.length);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelecting = rowSelecting;
gridObj.rowSelected = rowSelected;
(<HTMLElement>gridObj.element.querySelector('.e-checkselectall')).click();
});
it('header checkbox de-selection', (done: Function) => {
let rowDeselecting = (args: RowDeselectEventArgs) => {
expect(args.rowIndex).toBe(0);
expect(args.rowIndexes.length).toBe(gridObj.currentViewData.length);
expect((args.data as Object[]).length).toBe(gridObj.currentViewData.length);
expect((args.row as Element[]).length).toBe(gridObj.currentViewData.length);
expect((args.foreignKeyData as Object[]).length).toBe(gridObj.currentViewData.length);
gridObj.rowDeselecting = null;
};
let rowDeselected = (args: RowDeselectEventArgs) => {
expect(args.rowIndex).toBe(0);
expect(args.rowIndexes.length).toBe(gridObj.currentViewData.length);
expect((args.data as Object[]).length).toBe(gridObj.currentViewData.length);
expect((args.row as Element[]).length).toBe(gridObj.currentViewData.length);
expect((args.foreignKeyData as Object[]).length).toBe(gridObj.currentViewData.length);
gridObj.rowDeselected = null;
done();
};
gridObj.rowDeselecting = rowDeselecting;
gridObj.rowDeselected = rowDeselected;
(<HTMLElement>gridObj.element.querySelector('.e-checkselectall')).click();
});
it('select multiple rows by selectRowsByRange method', (done: Function) => {
let rowSelecting = (args: RowSelectingEventArgs) => {
expect(args.rowIndex).toBe(0);
expect(args.rowIndexes.length).toBe(end + 1);
expect((args.data as Object[]).length).toBe(end + 1);
expect((args.row as Element[]).length).toBe(end + 1);
expect((args.foreignKeyData as Object[]).length).toBe(end + 1);
gridObj.rowSelecting = null;
};
let rowSelected = (args: RowSelectEventArgs) => {
expect(args.rowIndex).toBe(0);
expect(args.rowIndexes.length).toBe(end + 1);
expect((args.data as Object[]).length).toBe(end + 1);
expect((args.row as Element[]).length).toBe(end + 1);
expect((args.foreignKeyData as Object[]).length).toBe(end + 1);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelecting = rowSelecting;
gridObj.rowSelected = rowSelected;
gridObj.selectRowsByRange(start, end);
gridObj.clearSelection();
});
it('EJ2-41198 => rowIndexes property single row deselected in header checkbox', (done: Function) => {
let rowDeselected = (args: RowDeselectEventArgs) => {
expect(args.rowIndexes.length).toBe(1);
done();
};
gridObj.rowDeselected = rowDeselected;
(gridObj.element.querySelectorAll('.e-frame.e-icons')[2] as HTMLElement).click();
(gridObj.element.querySelectorAll('.e-frame.e-icons')[2] as HTMLElement).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
gridObj.rowDeselected = null;
gridObj.rowDeselecting = null;
gridObj.rowSelecting = null;
gridObj.rowSelected = null;
});
});
describe('EJ2-41468 - row data in rowSelected event args is not maintained properly with Batch edit mode', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data.slice(0,5),
columns: [
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'ShipCity', headerText: 'Ship City' },
{ field: 'ShipCountry', headerText: 'Ship Country' }],
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode:'Batch', newRowPosition:'Bottom' },
allowPaging: true,
pageSettings: { pageCount: 5 },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
}, done);
});
it('Adding new record in bottom ', () => {
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
});
it('Check selected data', () => {
let rowSelected = (e: RowSelectEventArgs) => {
expect(e.data["OrderID"].toString()).toBe(dataCell.innerText);
}
gridObj.rowSelected = rowSelected;
let dataCell: HTMLElement = (gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement);
dataCell.click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
gridObj.rowDeselected = null;
});
});
describe('EJ2-41692 - Row drag issue when field-based checkbox column is present', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: 'Verified', headerText: 'Verified', type:'checkbox' },],
height:700,
}, done);
});
it('dataBind', () => {
gridObj.dataBind();
});
it('checkbox records ', () => {
expect(gridObj.getSelectedRows().length >= 1).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-42056 - initial selection with persistSelection enabled', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
selectedRowIndex: 1,
selectionSettings: { persistSelection: true },
columns: [
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' }
],
height: 700,
}, done);
});
it('checking initial selection ', (done: Function) => {
expect(gridObj.getSelectedRows().length).toBe(1);
done();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-42056 - enable toggle with persist selection', () => {
let gridObj: Grid;
let rowSelected: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
rowSelected: rowSelected,
selectionSettings: { persistSelection: true, enableToggle:false },
columns: [
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' }
],
height: 700,
}, done);
});
it('checking select row with toggle', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.element.querySelectorAll('.e-row')[3].getAttribute('aria-selected')).toBe('true');
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
gridObj.selectRow(3, false);
});
it('checking select row with enabletoggle', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.element.querySelectorAll('.e-row')[3].getAttribute('aria-selected')).toBe('true');
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
gridObj.selectRow(3, false);
});
it('row selection with enable toggle and persistence', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.element.querySelectorAll('.e-row')[1].getAttribute('aria-selected')).toBe('true');
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement).click();
});
it('checking the row deselect', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.element.querySelectorAll('.e-row')[1].getAttribute('aria-selected')).toBe('true');
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(gridObj.getRows()[1].querySelector('.e-rowcell') as HTMLElement).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
});
describe(' EJ242851 => Column Selection testing', () => {
let gridObj: Grid;
let preventDefault: Function = new Function();
let selectionModule: Selection;
beforeAll((done: Function) => {
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)
}
gridObj = createGrid(
{
dataSource: data,
allowSorting: true,
columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' },
{ field: 'ShipCity' }, { field: 'ShipCountry' }],
allowPaging: true,
pageSettings: { pageSize: 8, pageCount: 4, currentPage: 1 },
allowSelection: true,
selectionSettings: { type: 'Multiple', allowColumnSelection: true },
}, done);
});
it('select Column method testing', () => {
selectionModule = gridObj.selectionModule;
selectionModule.selectColumn(1);
expect(gridObj.element.querySelector('e-selectionbackground')).toBeNull();
expect((gridObj.element.querySelector('.e-cellselectionbackground') as HTMLTableCellElement)).toBeNull();
expect(gridObj.element.querySelector('.e-columnselection')).not.toBeNull();
});
it('select Column by range method testing', () => {
gridObj.clearSelection();
selectionModule.selectColumnsByRange(1, 3);
expect(gridObj.getSelectedColumnsUid().length).toBe(3);
expect(gridObj.element.querySelector('.e-row').querySelectorAll('.e-columnselection').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-columnselection').length).toBe(3);
});
it('select Column by Collection method testing', () => {
gridObj.clearSelection();
selectionModule.selectColumns([2,5]);
expect(gridObj.getSelectedColumnsUid().length).toBe(2);
expect(gridObj.element.querySelector('.e-row').querySelectorAll('.e-columnselection').length).toBe(2);
expect(gridObj.getHeaderContent().querySelectorAll('.e-columnselection').length).toBe(2);
});
it('select Column with Existing method testing', () => {
selectionModule.selectColumnWithExisting(3);
expect(gridObj.getSelectedColumnsUid().length).toBe(3);
expect(gridObj.element.querySelector('.e-row').querySelectorAll('.e-columnselection').length).toBe(3);
expect(gridObj.getHeaderContent().querySelectorAll('.e-columnselection').length).toBe(3);
});
it('check select event', (done: Function) => {
let columnSelecting: EmitType<Object> = (args: Object) => {
expect(args['isInteracted']).toBeFalsy();
expect(args['columnIndex']).toEqual(0);
expect(args['headerCell']).toEqual(gridObj.getHeaderContent().querySelector('.e-headercell'));
};
let columnSelected: EmitType<Object> = (args: Object) => {
expect(args['isInteracted']).toBeFalsy();
expect(args['columnIndex']).toEqual(0);
expect(args['headerCell']).toEqual(gridObj.getHeaderContent().querySelector('.e-headercell'));
gridObj.columnSelected = null;
gridObj.columnSelecting = null;
done();
};
gridObj.columnSelecting = columnSelecting;
gridObj.columnSelected = columnSelected;
selectionModule.selectColumn(0);
});
it('check deselect event', (done: Function) => {
gridObj.columnDeselected = undefined;
gridObj.columnDeselecting = undefined;
let columnDeselecting: EmitType<Object> = (args: Object) => {
expect(args['isInteracted']).toBeFalsy();
expect(args['columnIndex']).toEqual(0);
expect(args['headerCell']).toEqual(gridObj.getHeaderContent().querySelector('.e-headercell'));
};
let columnDeselected: EmitType<Object> = (args: Object) => {
expect(args['isInteracted']).toBeFalsy();
expect(args['columnIndex']).toEqual(0);
expect(args['headerCell']).toEqual(gridObj.getHeaderContent().querySelector('.e-headercell'));
gridObj.columnDeselected = null;
gridObj.columnDeselecting = null;
done();
};
gridObj.columnDeselecting = columnDeselecting;
gridObj.columnDeselected = columnDeselected;
selectionModule.clearColumnSelection();
});
afterAll(() => {
destroy(gridObj);
gridObj = preventDefault = selectionModule = null;
});
});
describe('EJ2-44995 - isInteracted property in rowDeselecting and rowDeselected events with Selectall and paging', () => {
let gridObj: Grid;
let rowDeselecting: (args: any) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{type:'checkbox'},{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' },
{ field: 'ShipCity' }],
allowPaging: true,
pageSettings: { pageSize: 8, pageCount: 4, currentPage: 1 },
allowSelection: true,
selectionSettings: { type: 'Multiple', mode: 'Both' },
}, done);
});
it('isInteracted property testing - Click', (done: Function) => {
rowDeselecting = (args: any) => {
expect(args.isInteracted).toBeTruthy();
done();
};
gridObj.rowDeselecting = rowDeselecting;
let selectAll: HTMLElement = (<HTMLElement>gridObj.element.querySelector('.e-checkselectall'));
selectAll.click();
selectAll.click();
});
it('isInteracted property testing - clearSelection method', (done: Function) => {
rowDeselecting = (args: any) => {
expect(args.isInteracted).toBeFalsy();
done();
};
gridObj.rowDeselecting = rowDeselecting;
(<HTMLElement>gridObj.element.querySelector('.e-checkselectall')).click();
gridObj.clearSelection();
});
afterAll(() => {
destroy(gridObj);
gridObj = rowDeselecting = null;
});
});
describe('EJ2-45406 - rowDeselect events with persistSelection', () => {
let gridObj: Grid;
let rowDeselecting: (args: any) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [{type:'checkbox'},{ field: 'OrderID', isPrimaryKey: true }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' },
{ field: 'ShipCity' }],
allowPaging: true,
pageSettings: { pageSize: 8, pageCount: 4, currentPage: 1 },
allowSelection: true,
selectionSettings: { persistSelection: true },
}, done);
});
it('rowDeselecting event testing - Click', (done: Function) => {
rowDeselecting = (args: any) => {
done();
};
gridObj.rowDeselecting = rowDeselecting;
(<HTMLElement>gridObj.element.querySelector('.e-row .e-checkselect')).click();
gridObj.clearSelection();
});
it('isInteracted property testing - clearSelection method', (done: Function) => {
rowDeselecting = (args: any) => {
done();
};
gridObj.rowDeselecting = rowDeselecting;
(<HTMLElement>gridObj.element.querySelectorAll('.e-rowcell')[1]).click();
gridObj.clearSelection();
});
afterAll(() => {
destroy(gridObj);
gridObj = rowDeselecting = null;
});
});
describe('EJ2-45650 - Persist Checkbox selection not working properly with frozen column', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
selectionSettings: { persistSelection: true },
columns: [
{ type: "checkbox", headerText: 'Check', width: 120 },
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID', freeze: 'Right' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: "ShipCity", headerText: "Ship City", width: 250 , freeze: 'Left' },
],
height: 700,
}, done);
});
it('checking Deselect row with persistSelection and frozen column', () => {
let chkBox: any = gridObj.element.querySelectorAll('.e-checkselect')[0] as HTMLElement;
chkBox.click();
chkBox.click();
expect(chkBox.nextSibling.classList.contains('e-uncheck')).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-45836 - The rowSelected event is triggered when rowselectig cancel is true in multiselection', () => {
let gridObj: Grid;
let check: boolean = true;
let rowSelecting: (e?: Object) => void;
let rowSelected: (e?: Object) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
selectionSettings: { type: "Multiple", enableSimpleMultiRowSelection: true },
rowSelecting: rowSelecting,
rowSelected: rowSelected,
columns: [
{ type: "checkbox", width: 120 },
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID', freeze: 'Right' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: "ShipCity", headerText: "Ship City", width: 250, freeze: 'Left' },
],
height: 700,
}, done);
});
it('checking rowselected event should not call when rowselecting cancel is true', () => {
let rowSelecting = (e: any) => {
e.cancel = true;
};
let rowSelected = (e: any) => {
check = false;
};
gridObj.rowSelecting = rowSelecting;
gridObj.rowSelected = rowSelected;
(gridObj.element.querySelectorAll('.e-rowcell')[0] as any).click();
expect(check).toBe(true);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-46492 - Preventing row deselection in the rowDeselecting event is not working', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
selectionSettings: { type: "Multiple" },
columns: [
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID', freeze: 'Right' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: "ShipCity", headerText: "Ship City", width: 250, freeze: 'Left' },
],
height: 700,
}, done);
});
it('checking rowDeselected event is not Working', () => {
let rowDeselecting = (e: any) => {
e.cancel = true;
};
gridObj.rowDeselecting = rowDeselecting;
(gridObj.element.querySelectorAll('.e-rowcell')[0] as any).click();
(gridObj.element.querySelectorAll('.e-rowcell')[0] as any).click();
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-46492 - Preventing row deselection in the rowDeselecting event is not working', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
selectionSettings: { type: "Multiple" },
columns: [
{ type: "checkbox"},
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: "ShipCity", headerText: "Ship City", width: 250 },
],
height: 700,
}, done);
});
it('checking rowDeselected with check column is not Working', () => {
let chkBox: any = gridObj.element.querySelectorAll('.e-checkselect')[0] as HTMLElement;
let rowDeselecting = (e: any) => {
e.cancel = true;
};
gridObj.rowDeselecting = rowDeselecting;
(gridObj.element.querySelectorAll('.e-rowcell')[0] as any).click();
(gridObj.element.querySelectorAll('.e-rowcell')[0] as any).click();
expect(chkBox.nextSibling.classList.contains('e-check')).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-48271 - Selected Row Index issue after deselection with checkbox', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
columns: [
{ type: "checkbox"},
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: "ShipCity", headerText: "Ship City", width: 250 },
],
height: 700,
}, done);
});
it('checking selected row Index in rowDeselected ', () => {
let rowDeselected = (e: any) => {
expect(gridObj.selectedRowIndex).toBe(6);
gridObj.rowDeselected= null;
};
gridObj.rowDeselected = rowDeselected;
gridObj.selectRows([0,4,2,6]);
expect(gridObj.selectedRowIndex).toBe(6);
(gridObj.element.querySelectorAll('.e-rowcell')[4] as any).click();
});
it('checking selected row Index in rowDeselected with last row', () => {
let rowDeselected = (e: any) => {
expect(gridObj.selectedRowIndex).toBe(2);
gridObj.rowDeselected= null;
};
gridObj.rowDeselected = rowDeselected;
(gridObj.element.querySelectorAll('.e-rowcell')[6] as any).click();
});
it('clear all Rows', () => {
let rowDeselected = (e: any) => {
expect(gridObj.selectedRowIndex).toBe(-1);
gridObj.rowDeselected= null;
};
gridObj.rowDeselected = rowDeselected;
gridObj.clearSelection();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-56885 - Previously selected data is not returned in selection events when select rows with CTRL key', () => {
let gridObj: Grid;
let rowSelecting: (e?: Object) => void;
let rowSelected: (e?: Object) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
selectionSettings: { type: 'Multiple' },
columns: [
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' },
{ field: "ShipCity", headerText: "Ship City", width: 250 },
],
height: 700,
}, done);
});
it('Selecting first row', (done: Function) => {
rowSelected = (): void => {
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(gridObj.getRows()[0].querySelector('.e-rowcell') as HTMLElement).click();
});
it('multi row - ctrl click testing- selecting second row', (done: Function) => {
rowSelected = (args?: any) => {
expect(args.data.length).toBe(2);
expect(args.row.length).toBe(2);
gridObj.rowSelected = null;
done();
};
rowSelecting = (args?: any) => {
expect(args.data.length).toBe(2);
expect(args.row.length).toBe(2);
gridObj.rowSelecting = null;
};
gridObj.rowSelecting = rowSelecting;
gridObj.rowSelected = rowSelected;
(gridObj.selectionModule as any).clickHandler({target: gridObj.getRows()[1].querySelector('.e-rowcell'), ctrlKey: true});
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-59308 Preventing keyboard actions when allow keyboard set to false', () =>{
let gridObj: Grid;
let rowSelected: () => void;
let rows: Element[];
let preventDefault: Function = new Function();
beforeAll((done: Function) => {
gridObj = createGrid({
dataSource: data,
allowKeyboard: false,
columns: [
{ type: 'checkbox', width: 50 },
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'CustomerID' },
{ field: 'EmployeeID', headerText: 'Employee ID' }],
allowPaging: true,
rowSelected: rowSelected
}, done);
});
it('checkbox selection through ctrl click testing', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(<HTMLElement>gridObj.element.querySelectorAll('.e-row')[0].querySelector('.e-rowcell')).click();
(gridObj.selectionModule as any).clickHandler({target: gridObj.element.querySelectorAll('.e-row')[3]
.querySelectorAll('.e-rowcell')[2], ctrlKey: true});
});
it('Selecting First row', (done: Function) => {
gridObj.rowSelected = rowSelected;
gridObj.isCheckBoxSelection = false;
(<HTMLElement>gridObj.element.querySelectorAll('.e-row')[0].querySelector('.e-rowcell')).click();
done();
});
it('checkbox selection through Shift click testing', (done: Function) => {
rowSelected = (): void => {
expect(gridObj.getSelectedRowIndexes().length).toBe(1);
gridObj.rowSelected = null;
done();
};
gridObj.rowSelected = rowSelected;
(gridObj.selectionModule as any)
.clickHandler({target: gridObj.element.querySelectorAll('.e-row')[3].querySelectorAll('.e-rowcell')[2], shiftKey: true});
});
it('checkbox selection through space key testing', () => {
let args: any = { action: 'space', preventDefault: preventDefault };
rows = gridObj.getRows();
let chkBox: HTMLElement = (rows[2].querySelector('.e-checkselect') as HTMLElement);
chkBox.click();
args.target = chkBox;
gridObj.keyboardModule.keyAction(args);
expect(chkBox.nextElementSibling.classList.contains('e-check')).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
});
}); | the_stack |
import * as fs from 'fs-extra';
import * as path from 'path';
import _ from 'lodash';
import { Template, ResourceBase } from 'cloudform-types';
import { JSONUtilities } from 'amplify-cli-core';
import { diff as getDiffs, Diff as DeepDiff } from 'deep-diff';
import { readFromPath } from './fileUtils';
import { InvalidMigrationError, InvalidGSIMigrationError, DestructiveMigrationError } from '../errors';
import { TRANSFORM_CONFIG_FILE_NAME } from '..';
type Diff = DeepDiff<DiffableProject, DiffableProject>;
export type DiffRule = (diff: Diff, currentBuild: DiffableProject, nextBuild: DiffableProject) => void;
export type ProjectRule = (diffs: Diff[], currentBuild: DiffableProject, nextBuild: DiffableProject) => void;
interface DiffableProject {
stacks: {
[stackName: string]: Template;
};
root: Template;
}
/**
* Calculates a diff between the last saved cloud backend's build directory
* and the most recent build.
*/
export const sanityCheckProject = async (
currentCloudBackendDir: string,
buildDirectory: string,
rootStackName: string,
diffRules: DiffRule[],
projectRule: ProjectRule[],
): Promise<void> => {
const cloudBackendDirectoryExists = fs.existsSync(currentCloudBackendDir);
const buildDirectoryExists = fs.existsSync(buildDirectory);
if (cloudBackendDirectoryExists && buildDirectoryExists) {
const current = await loadDiffableProject(currentCloudBackendDir, rootStackName);
const next = await loadDiffableProject(buildDirectory, rootStackName);
const diffs = getDiffs(current, next);
sanityCheckDiffs(diffs, current, next, diffRules, projectRule);
}
};
export const sanityCheckDiffs = (
diffs: Diff[],
current: DiffableProject,
next: DiffableProject,
diffRules: DiffRule[],
projectRules: ProjectRule[],
): void => {
// Project rules run on the full set of diffs, the current build, and the next build.
// Loop through the diffs and call each DiffRule.
// We loop once so each rule does not need to loop.
if (diffs) {
for (const diff of diffs) {
for (const rule of diffRules) {
rule(diff, current, next);
}
}
for (const projectRule of projectRules) {
projectRule(diffs, current, next);
}
}
};
/**
* Throws a helpful error when a customer is trying to complete an invalid migration.
* Users are unable to update a KeySchema after the table has been deployed.
* @param diffs The set of diffs between currentBuild and nextBuild.
* @param currentBuild The last deployed build.
* @param nextBuild The next build.
*/
export const getCantEditKeySchemaRule = (iterativeUpdatesEnabled: boolean = false) => {
const cantEditKeySchemaRule = (diff: Diff): void => {
if (diff.kind === 'E' && diff.path.length === 8 && diff.path[5] === 'KeySchema') {
// diff.path = [ "stacks", "Todo.json", "Resources", "TodoTable", "Properties", "KeySchema", 0, "AttributeName"]
const stackName = path.basename(diff.path[1], '.json');
const tableName = diff.path[3];
if (iterativeUpdatesEnabled) {
throw new DestructiveMigrationError(
'Editing the primary key of a model requires replacement of the underlying DynamoDB table.',
[],
[tableName],
);
}
throw new InvalidMigrationError(
`Attempting to edit the key schema of the ${tableName} table in the ${stackName} stack. `,
'Adding a primary @key directive to an existing @model. ',
'Remove the @key directive or provide a name e.g @key(name: "ByStatus", fields: ["status"]).',
);
}
};
return cantEditKeySchemaRule;
};
/**
* Throws a helpful error when a customer is trying to complete an invalid migration.
* Users are unable to add LSIs after the table has been created.
* @param diffs The set of diffs between currentBuild and nextBuild.
* @param currentBuild The last deployed build.
* @param nextBuild The next build.
*/
export const getCantAddLSILaterRule = (iterativeUpdatesEnabled: boolean = false) => {
const cantAddLSILaterRule = (diff: Diff): void => {
if (
// When adding a LSI to a table that has 0 LSIs.
(diff.kind === 'N' && diff.path.length === 6 && diff.path[5] === 'LocalSecondaryIndexes') ||
// When adding a LSI to a table that already has at least one LSI.
(diff.kind === 'A' && diff.path.length === 6 && diff.path[5] === 'LocalSecondaryIndexes' && diff.item.kind === 'N')
) {
// diff.path = [ "stacks", "Todo.json", "Resources", "TodoTable", "Properties", "LocalSecondaryIndexes" ]
const stackName = path.basename(diff.path[1], '.json');
const tableName = diff.path[3];
if (iterativeUpdatesEnabled) {
throw new DestructiveMigrationError(
'Adding an LSI to a model requires replacement of the underlying DynamoDB table.',
[],
[tableName],
);
}
throw new InvalidMigrationError(
`Attempting to add a local secondary index to the ${tableName} table in the ${stackName} stack. ` +
'Local secondary indexes must be created when the table is created.',
"Adding a @key directive where the first field in 'fields' is the same as the first field in the 'fields' of the primary @key.",
"Change the first field in 'fields' such that a global secondary index is created or delete and recreate the model.",
);
}
};
return cantAddLSILaterRule;
};
/**
* Throws a helpful error when a customer is trying to complete an invalid migration.
* Users are unable to change GSI KeySchemas after they are created.
* @param diffs The set of diffs between currentBuild and nextBuild.
* @param currentBuild The last deployed build.
* @param nextBuild The next build.
*/
export const cantEditGSIKeySchemaRule = (diff: Diff, currentBuild: DiffableProject, nextBuild: DiffableProject): void => {
const throwError = (indexName: string, stackName: string, tableName: string): void => {
throw new InvalidGSIMigrationError(
`Attempting to edit the global secondary index ${indexName} on the ${tableName} table in the ${stackName} stack. `,
'The key schema of a global secondary index cannot be changed after being deployed.',
'If using @key, first add a new @key, run `amplify push`, ' +
'and then remove the old @key. If using @connection, first remove the @connection, run `amplify push`, ' +
'and then add the new @connection with the new configuration.',
);
};
if (
// implies a field was changed in a GSI after it was created.
// Path like:["stacks","Todo.json","Resources","TodoTable","Properties","GlobalSecondaryIndexes",0,"KeySchema",0,"AttributeName"]
(diff.kind === 'E' && diff.path.length === 10 && diff.path[5] === 'GlobalSecondaryIndexes' && diff.path[7] === 'KeySchema') ||
// implies a field was added to a GSI after it was created.
// Path like: [ "stacks", "Comment.json", "Resources", "CommentTable", "Properties", "GlobalSecondaryIndexes", 0, "KeySchema" ]
(diff.kind === 'A' && diff.path.length === 8 && diff.path[5] === 'GlobalSecondaryIndexes' && diff.path[7] === 'KeySchema')
) {
// This error is symptomatic of a change to the GSI array but does not necessarily imply a breaking change.
const pathToGSIs = diff.path.slice(0, 6);
const oldIndexes = _.get(currentBuild, pathToGSIs);
const newIndexes = _.get(nextBuild, pathToGSIs);
const oldIndexesDiffable = _.keyBy(oldIndexes, 'IndexName');
const newIndexesDiffable = _.keyBy(newIndexes, 'IndexName');
const innerDiffs = getDiffs(oldIndexesDiffable, newIndexesDiffable) || [];
// We must look at this inner diff or else we could confuse a situation
// where the user adds a GSI to the beginning of the GlobalSecondaryIndexes list in CFN.
// We re-key the indexes list so we can determine if a change occurred to an index that
// already exists.
for (const innerDiff of innerDiffs) {
// path: ["AGSI","KeySchema",0,"AttributeName"]
if (innerDiff.kind === 'E' && innerDiff.path.length > 2 && innerDiff.path[1] === 'KeySchema') {
const indexName = innerDiff.path[0];
const stackName = path.basename(diff.path[1], '.json');
const tableName = diff.path[3];
throwError(indexName, stackName, tableName);
} else if (innerDiff.kind === 'A' && innerDiff.path.length === 2 && innerDiff.path[1] === 'KeySchema') {
// Path like - ["gsi-PostComments", "KeySchema" ]
const indexName = innerDiff.path[0];
const stackName = path.basename(diff.path[1], '.json');
const tableName = diff.path[3];
throwError(indexName, stackName, tableName);
}
}
}
};
/**
* Throws a helpful error when a customer is trying to complete an invalid migration.
* Users are unable to add and remove GSIs at the same time.
* @param diffs The set of diffs between currentBuild and nextBuild.
* @param currentBuild The last deployed build.
* @param nextBuild The next build.
*/
export const cantAddAndRemoveGSIAtSameTimeRule = (diff: Diff, currentBuild: DiffableProject, nextBuild: DiffableProject): void => {
const throwError = (stackName: string, tableName: string): void => {
throw new InvalidGSIMigrationError(
`Attempting to add and remove a global secondary index at the same time on the ${tableName} table in the ${stackName} stack. `,
'You may only change one global secondary index in a single CloudFormation stack update. ',
'If using @key, change one @key at a time. ' +
'If using @connection, add the new @connection, run `amplify push`, ' +
'and then remove the new @connection with the new configuration.',
);
};
if (
// implies a field was changed in a GSI after it was created.
// Path like:["stacks","Todo.json","Resources","TodoTable","Properties","GlobalSecondaryIndexes", ... ]
diff.kind === 'E' &&
diff.path.length > 6 &&
diff.path[5] === 'GlobalSecondaryIndexes'
) {
// This error is symptomatic of a change to the GSI array but does not necessarily imply a breaking change.
const pathToGSIs = diff.path.slice(0, 6);
const oldIndexes = _.get(currentBuild, pathToGSIs);
const newIndexes = _.get(nextBuild, pathToGSIs);
const oldIndexesDiffable = _.keyBy(oldIndexes, 'IndexName');
const newIndexesDiffable = _.keyBy(newIndexes, 'IndexName');
const innerDiffs = getDiffs(oldIndexesDiffable, newIndexesDiffable) || [];
let sawDelete = false;
let sawNew = false;
for (const diff of innerDiffs) {
// A path of length 1 means an entire GSI was created or deleted.
if (diff.path.length === 1 && diff.kind === 'D') {
sawDelete = true;
}
if (diff.path.length === 1 && diff.kind === 'N') {
sawNew = true;
}
}
if (sawDelete && sawNew) {
const stackName = path.basename(diff.path[1], '.json');
const tableName = diff.path[3];
throwError(stackName, tableName);
}
}
};
export const cantBatchMutateGSIAtUpdateTimeRule = (diff: Diff, currentBuild: DiffableProject, nextBuild: DiffableProject): void => {
// path indicating adding new gsis or removing gsis from table
// ['stacks', 'Book.json', 'Resources', 'BookTable', 'Properties', 'GlobalSecondaryIndexes']
if ((diff.kind === 'D' || diff.kind === 'N') && diff.path.length === 6 && diff.path.slice(-1)[0] === 'GlobalSecondaryIndexes') {
const tableName = diff.path[3];
const stackName = diff.path[1];
throw new InvalidGSIMigrationError(
`Attempting to add and remove a global secondary index at the same time on the ${tableName} table in the ${stackName} stack. `,
'You may only change one global secondary index in a single CloudFormation stack update. ',
'If using @key, change one @key at a time. ' +
'If using @connection, add the new @connection, run `amplify push`, ' +
'and then remove the new @connection with the new configuration.',
);
}
};
/**
* Throws a helpful error when a customer is trying to complete an invalid migration.
* Users are unable to add multiple GSIs at the same time in update stage.
* @param diffs The set of diffs between currentBuild and nextBuild.
* @param currentBuild The last deployed build.
* @param nextBuild The next build.
*/
export const cantMutateMultipleGSIAtUpdateTimeRule = (diffs: Diff[], currentBuild: DiffableProject, nextBuild: DiffableProject): void => {
const throwError = (stackName: string, tableName: string): void => {
throw new InvalidGSIMigrationError(
`Attempting to mutate more than 1 global secondary index at the same time on the ${tableName} table in the ${stackName} stack. `,
'You may only mutate one global secondary index in a single CloudFormation stack update. ',
'If using @key, include one @key at a time. ' +
'If using @connection, just add one new @connection which is using @key, run `amplify push`, ',
);
};
if (diffs) {
// update flow counting the tables which need more than one gsi update
const seenTables: Set<String> = new Set();
for (const diff of diffs) {
if (
// implies a field was changed in a GSI after it was created if it ends in GSI
// Path like: ["stacks","Todo.json","Resources","TodoTable","Properties","GlobalSecondaryIndexes" ]
diff.kind === 'A' &&
diff.path.length >= 6 &&
diff.path.slice(-1)[0] === 'GlobalSecondaryIndexes'
) {
const diffTableName = diff.path[3];
if ((diff.item.kind === 'N' || diff.item.kind === 'D') && !seenTables.has(diffTableName)) {
seenTables.add(diffTableName);
} else if (seenTables.has(diffTableName)) {
const stackName = path.basename(diff.path[1], '.json');
throwError(stackName, diffTableName);
}
}
}
}
};
/**
* Throws a helpful error when a customer is trying to complete an invalid migration.
* Users are unable to change LSI KeySchemas after they are created.
* @param diffs The set of diffs between currentBuild and nextBuild.
* @param currentBuild The last deployed build.
* @param nextBuild The next build.
*/
export const getCantEditLSIKeySchemaRule = (iterativeUpdatesEnabled: boolean = false) => {
const cantEditLSIKeySchemaRule = (diff: Diff, currentBuild: DiffableProject, nextBuild: DiffableProject): void => {
if (
// ["stacks","Todo.json","Resources","TodoTable","Properties","LocalSecondaryIndexes",0,"KeySchema",0,"AttributeName"]
diff.kind === 'E' &&
diff.path.length === 10 &&
diff.path[5] === 'LocalSecondaryIndexes' &&
diff.path[7] === 'KeySchema'
) {
// This error is symptomatic of a change to the GSI array but does not necessarily imply a breaking change.
const pathToGSIs = diff.path.slice(0, 6);
const oldIndexes = _.get(currentBuild, pathToGSIs);
const newIndexes = _.get(nextBuild, pathToGSIs);
const oldIndexesDiffable = _.keyBy(oldIndexes, 'IndexName');
const newIndexesDiffable = _.keyBy(newIndexes, 'IndexName');
const innerDiffs = getDiffs(oldIndexesDiffable, newIndexesDiffable) || [];
// We must look at this inner diff or else we could confuse a situation
// where the user adds a LSI to the beginning of the LocalSecondaryIndex list in CFN.
// We re-key the indexes list so we can determine if a change occurred to an index that
// already exists.
for (const innerDiff of innerDiffs) {
// path: ["AGSI","KeySchema",0,"AttributeName"]
if (innerDiff.kind === 'E' && innerDiff.path.length > 2 && innerDiff.path[1] === 'KeySchema') {
const indexName = innerDiff.path[0];
const stackName = path.basename(diff.path[1], '.json');
const tableName = diff.path[3];
if (iterativeUpdatesEnabled) {
throw new DestructiveMigrationError('Editing an LSI requires replacement of the underlying DynamoDB table.', [], [tableName]);
}
throw new InvalidMigrationError(
`Attempting to edit the local secondary index ${indexName} on the ${tableName} table in the ${stackName} stack. `,
'The key schema of a local secondary index cannot be changed after being deployed.',
'When enabling new access patterns you should: 1. Add a new @key 2. run amplify push ' +
'3. Verify the new access pattern and remove the old @key.',
);
}
}
}
};
return cantEditLSIKeySchemaRule;
};
export const getCantRemoveLSILater = (iterativeUpdatesEnabled: boolean = false) => {
const cantRemoveLSILater = (diff: Diff, currentBuild: DiffableProject, nextBuild: DiffableProject) => {
const throwError = (stackName: string, tableName: string): void => {
if (iterativeUpdatesEnabled) {
throw new DestructiveMigrationError('Removing an LSI requires replacement of the underlying DynamoDB table.', [], [tableName]);
}
throw new InvalidMigrationError(
`Attempting to remove a local secondary index on the ${tableName} table in the ${stackName} stack.`,
'A local secondary index cannot be removed after deployment.',
'In order to remove the local secondary index you need to delete or rename the table.',
);
};
// if removing more than one lsi
if (diff.kind === 'D' && diff.lhs && diff.path.length === 6 && diff.path[5] === 'LocalSecondaryIndexes') {
const tableName = diff.path[3];
const stackName = path.basename(diff.path[1], '.json');
throwError(stackName, tableName);
}
// if removing one lsi
if (diff.kind === 'A' && diff.item.kind === 'D' && diff.path.length === 6 && diff.path[5] === 'LocalSecondaryIndexes') {
const tableName = diff.path[3];
const stackName = path.basename(diff.path[1], '.json');
throwError(stackName, tableName);
}
};
return cantRemoveLSILater;
};
export const cantHaveMoreThan500ResourcesRule = (diffs: Diff[], currentBuild: DiffableProject, nextBuild: DiffableProject): void => {
const stackKeys = Object.keys(nextBuild.stacks);
for (const stackName of stackKeys) {
const stack = nextBuild.stacks[stackName];
if (stack && stack.Resources && Object.keys(stack.Resources).length > 500) {
throw new InvalidMigrationError(
`The ${stackName} stack defines more than 500 resources.`,
'CloudFormation templates may contain at most 500 resources.',
'If the stack is a custom stack, break the stack up into multiple files in stacks/. ' +
'If the stack was generated, you have hit a limit and can use the StackMapping argument in ' +
`${TRANSFORM_CONFIG_FILE_NAME} to fine tune how resources are assigned to stacks.`,
);
}
}
};
export const cantRemoveTableAfterCreation = (_: Diff, currentBuild: DiffableProject, nextBuild: DiffableProject): void => {
const getNestedStackLogicalIds = (proj: DiffableProject) =>
Object.entries(proj.root.Resources || [])
.filter(([_, meta]) => meta.Type === 'AWS::CloudFormation::Stack')
.map(([name]) => name);
const currentModels = getNestedStackLogicalIds(currentBuild);
const nextModels = getNestedStackLogicalIds(nextBuild);
const removedModels = currentModels
.filter(currModel => !nextModels.includes(currModel))
.filter(stackLogicalId => stackLogicalId !== 'ConnectionStack');
if (removedModels.length > 0) {
throw new DestructiveMigrationError(
'Removing a model from the GraphQL schema will also remove the underlying DynamoDB table.',
removedModels,
[],
);
}
};
const loadDiffableProject = async (path: string, rootStackName: string): Promise<DiffableProject> => {
const project = await readFromPath(path);
const currentStacks = project.stacks || {};
const diffableProject: DiffableProject = {
stacks: {},
root: {},
};
for (const key of Object.keys(currentStacks)) {
diffableProject.stacks[key] = JSONUtilities.parse(project.stacks[key]);
}
if (project[rootStackName]) {
diffableProject.root = JSONUtilities.parse(project[rootStackName]);
}
return diffableProject;
}; | the_stack |
import * as z from "zod";
import chalk from "chalk";
import { Api, Client, Model } from "@core/types";
import { Graph } from "@core/types/client/graph";
import { exit } from "../../lib/process";
import { Argv } from "yargs";
import { dispatch, initCore } from "../../lib/core";
import { BaseArgs } from "../../types";
import {
logAndExitIfActionFailed,
sortByPredefinedOrder,
} from "../../lib/args";
import { OrgRole } from "@core/types/rbac";
import { graphTypes, authz } from "@core/lib/graph";
import { fetchScimCandidates } from "../../lib/scim_client_helpers";
import { autoModeOut, getPrompt } from "../../lib/console_io";
import { tryApplyDetectedAppOverride } from "../../app_detection";
const isEmailValidator = (value: string): boolean => {
try {
z.string().email().parse(value);
} catch (err) {
console.error(chalk.red.bold(err.message));
return false;
}
return true;
};
export const command = ["invite [email] [first-name] [last-name] [org-role]"];
export const desc = "Invite someone to the organization.";
export const builder = (yargs: Argv<BaseArgs>) =>
yargs
.positional("email", {
type: "string",
})
.positional("first-name", {
type: "string",
})
.positional("last-name", {
type: "string",
})
.positional("org-role", {
type: "string",
})
.option("saml", {
type: "boolean",
describe: "set provider to saml",
});
export const handler = async (
argv: BaseArgs & {
email?: string;
"first-name"?: string;
"last-name"?: string;
"org-role"?: string;
saml?: boolean;
}
): Promise<void> => {
const prompt = getPrompt();
let { state, auth } = await initCore(argv, true);
// override account from ENVKEY
if (tryApplyDetectedAppOverride(auth.userId, argv)) {
return handler(argv);
}
let scimProvider: Model.ScimProvisioningProvider | undefined;
let firstName: string | undefined = argv["first-name"];
let lastName: string | undefined = argv["last-name"];
let email: string | undefined = argv["email"];
let orgRoleId: string | undefined = argv["org-role"]
? authz
.getInvitableOrgRoles(state.graph, auth.userId)
?.find((or) =>
[
or.id.toLowerCase(),
or.defaultName?.toLowerCase(),
or.name.toLowerCase(),
].includes(argv["org-role"]!.toLowerCase())
)?.id
: undefined;
let candidateId: string | undefined;
const scimProvisioningProviders = graphTypes(
state.graph
).scimProvisioningProviders;
const now = Date.now();
if (!authz.canInviteAny(state.graph, auth.userId)) {
return exit(1, chalk.red(`You don't have permission to invite a user.`));
}
const selectOrgRole = orgRoleId
? undefined
: {
type: "select",
name: "orgRoleId",
message: "Organization Role:",
required: true,
initial: 0,
choices: sortByPredefinedOrder(
["Basic User", "Org Admin", "Org Owner"],
authz.getInvitableOrgRoles(state.graph, auth.userId),
"defaultName"
).map((or) => ({
name: or.id,
message: `${chalk.bold(or.name)} - ${or.description}`,
})),
};
const { license, org } = graphTypes(state.graph);
const licenseExpired = license.expiresAt != -1 && now > license.expiresAt;
const exceededDeviceLimit =
license.maxDevices != -1 && org.deviceLikeCount >= license.maxDevices;
const exeededActiveUserLimit =
license.maxUsers &&
license.maxUsers != -1 &&
org.activeUserOrInviteCount &&
license.maxUsers != -1 &&
org.activeUserOrInviteCount >= license.maxUsers;
if (exceededDeviceLimit || exeededActiveUserLimit || licenseExpired) {
let message: string;
if (licenseExpired) {
message = chalk.red(
`Your org's ${
license.provisional ? "provisional " : ""
}license has expired.`
);
} else if (exceededDeviceLimit) {
message = `Your org has reached its limit of ${
license.maxDevices
} device${license.maxDevices == 1 ? "" : "s"}.`;
} else {
message = `Your org has reached its limit of ${license.maxUsers} user${
license.maxUsers == 1 ? "" : "s"
}.`;
}
message += "\n";
if (
authz.hasOrgPermission(state.graph, auth.userId, "org_manage_billing")
) {
message += `To invite more users, ${
licenseExpired ? "renew" : "upgrade"
} your org's license.`;
} else {
message += `To invite more users, ask an admin to ${
licenseExpired ? "renew" : "upgrade"
} your org's license.`;
}
return exit(1, message);
}
let payload:
| Pick<Api.Net.ApiParamTypes["CreateInvite"], "user" | "scim">[]
| undefined;
let externalAuthProviderId: string | undefined;
const samlProviders = graphTypes(state.graph).externalAuthProviders.filter(
(p) => p.provider === "saml"
);
const hasSaml = samlProviders.length > 0;
let provider: "saml" | "email" | undefined =
argv["saml"] && hasSaml ? "saml" : undefined;
if (hasSaml) {
if (!provider) {
// user may have used saml flag to auto-select
({ provider } = await prompt<{ provider: "saml" | "email" }>({
type: "select",
name: "provider",
message: "Select auth method for the user",
choices: ["saml", "email"],
required: true,
}));
}
if (provider === "saml") {
if (samlProviders.length === 1) {
externalAuthProviderId = samlProviders[0].id;
} else {
({ externalAuthProviderId } = await prompt<{
externalAuthProviderId: string;
}>({
type: "select",
name: "externalAuthProviderId",
message: "Choose from your configured SAML providers",
choices: samlProviders.map((p) => ({
name: p.id,
message: p.nickname,
})),
required: true,
}));
}
console.log(
"Using SAML provider",
samlProviders.find((p) => p.id === externalAuthProviderId)!.nickname
);
}
} else {
provider = "email";
}
if (scimProvisioningProviders.length > 0) {
const { choice } = await prompt<{ choice: "email" | "scim" }>({
type: "select",
required: true,
name: "choice",
message: "How would you like to invite users?",
choices: [
{
name: "scim",
message: "From list of provisioned users (SCIM)",
},
{
name: "email",
message: "Using email",
},
],
});
if (choice === "scim") {
if (scimProvisioningProviders.length == 1) {
scimProvider = scimProvisioningProviders[0];
} else {
// multiple providers
const { scimProviderId } = await prompt<{ scimProviderId: string }>({
type: "select",
name: "scimProviderId",
message: "Choose the SCIM provider",
required: true,
choices: scimProvisioningProviders.map((s) => ({
name: s.id,
message: s.nickname,
})),
});
scimProvider = state.graph[
scimProviderId
] as Model.ScimProvisioningProvider;
}
}
}
if (scimProvider) {
const candidates = await fetchScimCandidates(scimProvider.id);
if (!candidates?.length) {
return exit(1, "Nobody available to invite from SCIM.");
}
({ candidateId, orgRoleId } = await prompt<{
candidateId: string;
orgRoleId: string;
}>([
{
type: "autocomplete",
name: "candidateId",
message: "Choose somebody",
required: true,
choices: candidates.map((c) => ({
name: c.id,
message: `${c.email} (${c.scimUserName}, ${c.scimExternalId}) ${
c.scimDisplayName || ""
} - ${c.firstName} ${c.lastName}`,
})),
},
selectOrgRole as any,
]));
const candidate = candidates.find((c) => c.id === candidateId)!;
firstName = candidate.firstName;
lastName = candidate.lastName;
email = candidate.email;
// end invite from scim
} else if (!email || !firstName || !lastName || !orgRoleId) {
// not scimProvider, or no users available to invite from scim.
// default behavior
({ email, firstName, lastName, orgRoleId } = await prompt<{
email: string;
firstName: string;
lastName: string;
orgRoleId: string;
}>([
{
type: "input",
name: "firstName",
message: "First name:",
initial: argv["first-name"] || "",
required: true,
},
{
type: "input",
name: "lastName",
message: "Last name:",
initial: argv["last-name"] || "",
required: true,
},
{
type: "input",
name: "email",
message: "Email:",
initial: argv["email"] || "",
validate: isEmailValidator,
},
selectOrgRole as any,
]));
}
payload = [
{
user: {
provider,
externalAuthProviderId,
email: email!,
uid: email,
firstName: firstName!,
lastName: lastName!,
orgRoleId: orgRoleId!,
},
},
];
if (candidateId && scimProvider) {
payload[0].scim = { candidateId, providerId: scimProvider.id };
}
const res = await dispatch({
type: Client.ActionType.INVITE_USERS,
payload,
});
await logAndExitIfActionFailed(res, "Invitation failed.");
state = res.state;
const [{ identityHash, encryptionKey, user }] = state.generatedInvites;
if (!identityHash || !encryptionKey) {
return exit(
1,
"Invitation failed. " + JSON.stringify(state.generatedInvites)
);
}
const outOfBandEncToken = [identityHash, encryptionKey].join("_");
console.log(
`\nAn EnvKey invitation has been sent to ${firstName} by email.\nYou also need to send ${firstName} an ${chalk.bold(
"Encryption Token"
)} by any reasonably private channel (like Slack, Twitter, Skype, or Facebook.`
);
console.log("\n", chalk.bold("Encryption Token:\n"));
console.log(outOfBandEncToken);
const hasNoDefaultApps = !(state.graph[orgRoleId] as OrgRole).autoAppRoleId;
if (hasNoDefaultApps) {
console.log(
chalk.italic(
`${firstName} doesn't have access to any apps yet. Use ${chalk.bold(
"envkey apps grant-access"
)} to give them access.`
)
);
}
autoModeOut({
orgUserId: user.id,
orgRoleId,
encryptionToken: outOfBandEncToken,
});
return exit();
};
const expectedInputFormat = JSON.stringify(
[
{
firstName: "Alice",
lastName: "Smith",
email: "alice@example.com",
role: "Basic User or Org Admin or Org Owner",
},
],
null,
2
); | the_stack |
import useSWR from "swr";
import { mutate } from "swr";
import * as Rails from "@rails/ujs";
import dayjs from "dayjs";
import { dequal } from "dequal";
import { CACHE_BUSTER } from "./meta";
import { useState, useEffect } from "react";
const API_CONFERENCE = `/api/conference?p=${CACHE_BUSTER}`;
export class ApiError extends Error {
public localError: Error;
public remoteError: object | null;
constructor(localError: Error, remoteError: object | null, ...params: any[]) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ApiError);
}
const j = JSON.stringify(remoteError);
this.name = localError.name;
this.message = `${localError.message}, ${j}`;
this.localError = localError;
this.remoteError = remoteError;
}
}
export async function request(path: string, method: string, query: object | null, payload: object | null) {
let url = path;
const headers = new Headers();
const opts: RequestInit = {
method: method,
headers: headers,
credentials: "include",
};
if (query) {
const queryParams = [];
for (const [k, v] of Object.entries(query)) {
const snakeK = k.replace(/([A-Z])/g, (c) => `_${c.toLowerCase()}`);
queryParams.push(`${snakeK}=${encodeURIComponent(v as string)}`);
}
url += `?${queryParams.join("&")}`;
}
headers.append("X-Csrf-Token", Rails.csrfToken() || "");
headers.append("Accept", "application/json");
if (payload) {
opts.body = JSON.stringify(payload);
headers.append("Content-Type", "application/json");
}
const resp = await fetch(url, opts);
if (!resp.ok) {
const contentType = resp.headers.get("Content-Type");
let err;
if (contentType && contentType.match(/^application\/json(;.+)?$/)) {
err = new ApiError(new Error(`${path} returned error ${resp.status}`), await resp.json());
} else {
const text = (await resp.text()).slice(0, 280);
err = new ApiError(new Error(`${path} returned error ${resp.status}: ${text}`), null);
}
console.error(err.localError, err.remoteError);
throw err;
}
return resp;
}
function mergeConferenceData(target: GetConferenceResponse, other: GetConferenceResponse) {
//console.log("mergeConferenceData", JSON.parse(JSON.stringify({ target, other })));
Object.entries(other.conference.tracks).forEach(([trackSlug, otherTrack]) => {
//console.log(`mergeConferenceData: track ${trackSlug}`);
if (!target.conference.tracks[trackSlug]) return;
const mergeCard = (key: "card" | "card_candidate") => {
const targetCard: TrackCard | null = target.conference.tracks[trackSlug][key];
const otherCard: TrackCard | null = otherTrack[key];
if (!otherCard) return;
if (!targetCard || targetCard.ut < otherCard.ut) {
//console.log("mergeConferenceData/mergeCard: otherCard", { trackSlug, key, targetCard, otherCard });
target.conference.tracks[trackSlug][key] = otherCard;
} else {
//console.log("mergeConferenceData/mergeCard: targetCard", { trackSlug, key, targetCard, otherCard });
}
};
mergeCard("card");
mergeCard("card_candidate");
//console.log("mergeConferenceData: merged cards");
const mergeSpotlight = () => {
const knownSpotlights = new Map<number, ChatSpotlight>();
const targetSpotlights = new Map(target.conference.tracks[trackSlug].spotlights.map((s) => [s.id, s]));
const otherSpotlights = new Map(target.conference.tracks[trackSlug].spotlights.map((s) => [s.id, s]));
[
[targetSpotlights, otherSpotlights],
[otherSpotlights, targetSpotlights],
].forEach(([a, b]) => {
a.forEach((sA, id) => {
if (knownSpotlights.has(id)) return;
const sB = b.get(id);
if (!sB) return;
knownSpotlights.set(id, sA.updated_at < sB.updated_at ? sB : sA);
});
});
[targetSpotlights, otherSpotlights].forEach((ss) => {
ss.forEach((s, id) => {
if (!knownSpotlights.has(id)) knownSpotlights.set(id, s);
});
});
target.conference.tracks[trackSlug].spotlights = Array.from(knownSpotlights.values());
};
mergeSpotlight();
//console.log("mergeConferenceData: merged spotlights");
const mergePresence = () => {
Object.entries(otherTrack.presences).forEach(([, otherPresence]) => {
const targetPresence = target.conference.tracks[trackSlug].presences[otherPresence.kind];
if (!targetPresence) {
target.conference.tracks[trackSlug].presences[otherPresence.kind] = otherPresence;
} else if (targetPresence && targetPresence.at <= otherPresence.at) {
target.conference.tracks[trackSlug].presences[otherPresence.kind] = otherPresence;
}
});
};
mergePresence();
//console.log("mergeConferenceData: merged presences");
//
const mergeViewerCount = () => {
if (otherTrack.viewerCount && !target.conference.tracks[trackSlug].viewerCount) {
target.conference.tracks[trackSlug].viewerCount = otherTrack.viewerCount;
}
};
mergeViewerCount();
});
}
function determineEarliestCandidateActivationAt(data: GetConferenceResponse) {
const timestamps = data.conference.track_order
.map((slug) => data.conference.tracks[slug]?.card_candidate?.at)
.filter((v): v is number => !!v);
if (timestamps.length < 1) return undefined;
const at = Math.min(...timestamps);
if (at == Infinity || at == NaN) return undefined;
return at;
}
export function consumeIvsMetadata(metadata: IvsMetadata) {
mutate(
API_CONFERENCE,
(known: GetConferenceResponse) => {
known = JSON.parse(JSON.stringify(known));
let updated = false;
metadata.i?.forEach((item) => {
console.log(item);
if (item.c) {
const cardUpdate = item.c;
const cardKey = cardUpdate.candidate ? "card_candidate" : "card";
if (cardUpdate.clear) {
const track = known.conference.tracks[cardUpdate.clear];
if (track?.[cardKey]) {
console.log("Clearing card", { key: cardKey, cardUpdate });
track[cardKey] = null;
updated = true;
}
} else if (cardUpdate.card) {
const track = known.conference.tracks[cardUpdate.card.track];
if (track) {
console.log("Updating card", { key: cardKey, cardUpdate });
track[cardKey] = cardUpdate.card;
updated = true;
}
}
}
if (item.p) {
const presence = item.p;
const track = known.conference.tracks[presence.track];
if (track) {
const was = track.presences[presence.kind]?.at ?? 0;
console.log("Updating stream presence", { presence, was });
track.presences[presence.kind] = presence;
updated = true;
}
}
if (item.n) {
const track = known.conference.tracks[item.n.track];
if (track) {
console.log("Updating viewerCount", item.n);
track.viewerCount = item.n;
updated = true;
}
}
});
if (updated) known.requested_at = 0;
return known;
},
false,
);
}
export function consumeChatAdminControl(adminControl: ChatAdminControl) {
console.log("consumeChatAdminControl", adminControl);
if (adminControl.pin) {
mutate(
`/api/tracks/${encodeURIComponent(adminControl.pin.track)}/chat_message_pin`,
{ track: adminControl.pin.track, pin: adminControl.pin },
false,
);
}
if (adminControl.spotlights) {
const spotlights = adminControl.spotlights;
mutate(
API_CONFERENCE,
(known: GetConferenceResponse) => {
known = JSON.parse(JSON.stringify(known));
spotlights.forEach((spotlight) => {
const track = known.conference.tracks[spotlight.track];
if (!track) return;
const idx = track.spotlights.findIndex((v) => v.id === spotlight.id);
if (idx !== -1) {
track.spotlights[idx] = spotlight;
} else {
track.spotlights.push(spotlight);
}
});
return known;
},
false,
);
}
if (adminControl.presences) {
const presences = adminControl.presences;
mutate(
API_CONFERENCE,
(known2: GetConferenceResponse) => {
const known = JSON.parse(JSON.stringify(known2));
presences.forEach((presence) => {
const track = known.conference.tracks[presence.track];
if (track) {
const was = track.presences[presence.kind]?.at ?? 0;
if (was < presence.at) {
console.log("Updating stream presence (chat)", presence);
track.presences[presence.kind] = presence;
}
}
});
return known;
},
false,
);
}
}
function activateCandidateTrackCard(data: GetConferenceResponse) {
console.log("Start activating candidate TrackCard");
const now = dayjs().unix();
let updated = false;
for (const [, track] of Object.entries(data.conference.tracks)) {
const candidate = track.card_candidate;
if (!candidate) continue;
if (now >= candidate.at) {
console.log(`Activating candidate TrackCard for track=${track.slug}`, track.card_candidate);
updated = true;
track.card = candidate;
track.card_candidate = null;
} else {
console.log(`Skipping candidate activation for track=${track.slug}`, track.card_candidate);
}
}
if (updated) {
console.log("Mutating /api/conference due to candidate TrackCard activation");
mutate(API_CONFERENCE, { ...data }, false);
}
}
export async function swrFetcher(url: string) {
return (await request(url, "GET", null, null)).json();
}
export interface Attendee {
id: number;
name: string;
avatar_url: string;
is_ready: boolean;
is_staff: boolean;
is_speaker: boolean;
is_committer: boolean;
is_sponsor?: boolean;
presentation_slugs?: string[];
}
export interface Conference {
default_track: string;
track_order: TrackSlug[];
tracks: { [key: string]: Track };
}
export type TrackSlug = string;
export interface Track {
slug: TrackSlug;
name: string;
interpretation: boolean;
chat: boolean;
card: TrackCard | null;
card_candidate: TrackCard | null;
spotlights: ChatSpotlight[];
presences: { [key: string]: StreamPresence }; // key:kind
viewerCount?: ViewerCount;
}
export interface TrackCard extends TrackCardHeader, TrackCardContent {}
export interface TrackCardHeader {
track: TrackSlug;
at: number;
ut: number;
}
export interface TrackCardContent {
interpretation?: boolean;
topic?: Topic | null;
speakers?: Speaker[] | null;
screen?: ScreenControl;
upcoming_topics?: UpcomingTopic[];
}
export interface Topic {
title: string | null;
author: string | null;
description: string | null;
labels: string[];
}
export interface Speaker {
name: string;
github_id: string | null;
twitter_id: string | null;
avatar_url: string;
}
export interface ScreenControl {
filler?: boolean;
heading?: string;
next_schedule?: ScreenNextSchedule;
footer?: string;
}
export interface ScreenNextSchedule {
at: number;
title: string;
absolute_only?: boolean;
}
export interface UpcomingTopic {
track: TrackSlug;
at: number;
topic?: Topic | null;
speakers: Speaker[] | null;
}
export interface ChatSpotlight {
id: number;
track: TrackSlug;
starts_at: number;
ends_at: number;
handles: ChatHandle[];
updated_at: number;
}
export interface TrackStreamOptions {
interpretation: boolean;
caption: boolean;
chat: boolean;
}
export type TrackStreamOptionsState = [TrackStreamOptions, (x: TrackStreamOptions) => void];
export interface StreamInfo {
slug: TrackSlug;
type: string;
url: string;
expiry: number;
}
export type ChannelArn = string;
export interface TrackChatInfo {
channel_arn: ChannelArn;
caption_channel_arn?: ChannelArn;
}
export interface AwsCredentials {
access_key_id: string;
secret_access_key: string;
session_token: string;
}
export interface GetSessionResponse {
attendee: Attendee | null;
control: boolean;
}
export interface GetAppVersionResponse {
commit: string;
release: string;
}
export type ChatSessionTracksBag = { [key: string]: TrackChatInfo | null };
export interface GetChatSessionResponse {
expiry: number;
grace: number;
app_arn: string;
user_arn: string;
app_user_arn: string;
aws_credentials: AwsCredentials;
tracks: ChatSessionTracksBag;
}
export interface GetConferenceResponse {
requested_at: number;
stale_after: number;
conference: Conference;
}
export interface CreateSessionResponse {
attendee: Attendee;
}
export interface UpdateAttendeeResponse {
attendee: Attendee;
}
export interface GetStreamResponse {
stream?: StreamInfo;
}
export interface GetChatMessagePinResponse {
track: TrackSlug;
pin: ChatMessagePin | null;
}
export interface ChatMessage {
channel: ChannelArn;
content: string | null;
sender: ChatSender;
timestamp: number; // millis
id: string;
redacted: boolean;
adminControl: ChatAdminControl | null;
}
export interface ChatAdminControl {
flush?: boolean;
pin?: ChatMessagePin;
caption?: ChatCaption;
spotlights?: ChatSpotlight[];
presences?: StreamPresence[];
promo?: boolean;
}
export interface ChatCaption {
result_id: string;
is_partial: boolean;
transcript: string;
}
// XXX: Determined and given at ChatSession
export interface ChatSenderFlags {
isAdmin?: boolean;
isAnonymous?: boolean;
isStaff?: boolean;
isSpeaker?: boolean;
isCommitter?: boolean;
}
export type ChatHandle = string;
export interface ChatSender extends ChatSenderFlags {
handle: ChatHandle;
name: string;
version: string;
}
export interface ChatMessagePin {
at: number;
track: TrackSlug;
message: ChatMessage | null;
}
export interface IvsMetadata {
i: IvsMetadataItem[];
}
export interface IvsMetadataItem {
c?: IvsCardUpdate;
p?: StreamPresence;
n?: ViewerCount;
}
export interface IvsCardUpdate {
candidate?: boolean;
clear?: TrackSlug;
card: TrackCard | null;
}
export interface StreamPresence {
track: TrackSlug;
kind: "main" | "interpretation";
online: boolean;
at: number;
}
export interface ViewerCount {
track: TrackSlug;
count: number;
expiry: number;
}
export interface GetConferenceSponsorshipsResponse {
conference_sponsorships: ConferenceSponsorship[];
}
export interface ConferenceSponsorship {
id: number;
sponsor_app_id: string;
avatar_url: string;
name: string;
large_display: boolean;
promo: string | null;
}
export const Api = {
useSession() {
return useSWR<GetSessionResponse, ApiError>("/api/session", swrFetcher, {
revalidateOnFocus: false,
});
},
useAppVersion() {
return useSWR<GetAppVersionResponse, ApiError>("/api/app_version", swrFetcher, {
revalidateOnFocus: true,
revalidateOnReconnect: true,
focusThrottleInterval: 60000,
refreshInterval: 90 * 1000, // TODO:
});
},
useConference() {
// TODO: Error handling
const swr = useSWR<GetConferenceResponse, ApiError>(API_CONFERENCE, swrFetcher, {
revalidateOnFocus: true,
revalidateOnReconnect: true,
//focusThrottleInterval: 15 * 1000, // TODO:
compare(knownData, newData) {
if (!knownData || !newData) return false;
try {
mergeConferenceData(newData, knownData);
} catch (e) {
console.warn(e);
throw e;
}
const res = dequal(newData, knownData);
return false; //res;
},
});
// Schedule candidate TrackCard activation
const { data } = swr;
useEffect(() => {
if (!data) return;
const earliestCandidateActivationAt = determineEarliestCandidateActivationAt(data);
if (!earliestCandidateActivationAt) return;
const timeout = (earliestCandidateActivationAt - dayjs().unix()) * 1000 + 500;
console.log(
`Scheduling candidate TrackCard activation; earliest will happen at ${dayjs(
new Date(earliestCandidateActivationAt * 1000),
).toISOString()}, in ${timeout / 1000}s`,
);
const timer = setTimeout(() => activateCandidateTrackCard(data), timeout);
return () => clearTimeout(timer);
}, [data]);
return swr;
},
// XXX: this is not an API
useTrackStreamOptions(): TrackStreamOptionsState {
const browserStateKey = "rk-takeout-app--TrackStreamOption";
let options: TrackStreamOptions = { interpretation: false, caption: false, chat: true };
const browserState = window.localStorage?.getItem(browserStateKey);
if (browserState) {
try {
options = JSON.parse(browserState);
} catch (e) {
console.warn(e);
}
if (!options.hasOwnProperty("chat")) {
options.chat = true;
}
} else {
const acceptJapanese = navigator.languages.findIndex((v) => /^ja($|-)/.test(v)) !== -1;
options.interpretation = !acceptJapanese;
}
const [state, setState] = useState(options);
return [
state,
(x: TrackStreamOptions) => {
try {
window.localStorage?.setItem(browserStateKey, JSON.stringify(x));
} catch (e) {
console.warn(e);
}
setState(x);
},
];
},
async createSession(email: string, reference: string): Promise<CreateSessionResponse> {
const resp = await request("/api/session", "POST", null, {
email,
reference,
});
mutate("/api/session");
return resp.json();
},
async updateAttendee(name: string, gravatar_email: string): Promise<UpdateAttendeeResponse> {
const resp = await request("/api/attendee", "PUT", null, {
name,
gravatar_email,
});
mutate("/api/session");
return resp.json();
},
useStream(slug: TrackSlug, interpretation: boolean) {
return useSWR<GetStreamResponse, ApiError>(
`/api/streams/${slug}?interpretation=${interpretation ? "1" : "0"}`,
swrFetcher,
{
revalidateOnFocus: true,
revalidateOnReconnect: true,
focusThrottleInterval: 60 * 15 * 1000,
compare(knownData, newData) {
// Accept new data only if expired
if (!knownData?.stream || !newData?.stream) return false;
const now = dayjs().unix() + 180;
return !(knownData.stream.expiry < newData.stream.expiry && knownData.stream.expiry <= now);
},
},
);
},
useChatSession(attendeeId: number | undefined) {
// attendeeId for cache buster
return useSWR<GetChatSessionResponse, ApiError>(
attendeeId ? `/api/chat_session?i=${attendeeId}&p=${CACHE_BUSTER}` : null,
swrFetcher,
{
revalidateOnFocus: true,
revalidateOnReconnect: true,
focusThrottleInterval: 60 * 40 * 1000,
refreshInterval: 60 * 80 * 1000,
refreshWhenHidden: false,
refreshWhenOffline: false,
},
);
},
useChatMessagePin(track: TrackSlug | undefined) {
return useSWR<GetChatMessagePinResponse, ApiError>(
track ? `/api/tracks/${encodeURIComponent(track)}/chat_message_pin` : null,
swrFetcher,
{
revalidateOnFocus: true,
revalidateOnReconnect: true,
focusThrottleInterval: 60 * 1000,
},
);
},
async sendChatMessage(track: TrackSlug, message: string, asAdmin?: boolean) {
const resp = await request(`/api/tracks/${encodeURIComponent(track)}/chat_messages`, "POST", null, {
message,
as_admin: !!asAdmin,
});
return resp.json();
},
async pinChatMessage(track: TrackSlug, chatMessage: ChatMessage | null) {
const resp = await request(`/api/tracks/${encodeURIComponent(track)}/chat_admin_message_pin`, "PUT", null, {
chat_message: chatMessage,
});
return resp.json();
},
async createCaptionChatMembership(track: TrackSlug) {
const resp = await request(`/api/tracks/${encodeURIComponent(track)}/caption_chat_membership`, "POST", null, {});
return resp.json();
},
async deleteCaptionChatMembership(track: TrackSlug) {
const resp = await request(`/api/tracks/${encodeURIComponent(track)}/caption_chat_membership`, "DELETE", null, {});
return resp.json();
},
useConferenceSponsorships() {
return useSWR<GetConferenceSponsorshipsResponse, ApiError>(
`/api/conference_sponsorships?p=${CACHE_BUSTER}`,
swrFetcher,
);
},
};
export default Api; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormPurchase_Order_Receipt {
interface tab_fstab_receipt_products_Sections {
fstab_products_section_related: DevKit.Controls.Section;
}
interface tab_fstab_receipt_products extends DevKit.Controls.ITab {
Section: tab_fstab_receipt_products_Sections;
}
interface Tabs {
fstab_receipt_products: tab_fstab_receipt_products;
}
interface Body {
Tab: Tabs;
msdyn_DateReceived: DevKit.Controls.Date;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
msdyn_Note: DevKit.Controls.String;
/** Unique identifier for Purchase Order associated with Purchase Order Receipt. */
msdyn_PurchaseOrder: DevKit.Controls.Lookup;
/** Unique identifier for User associated with Purchase Order Receipt. */
msdyn_ReceivedBy: DevKit.Controls.Lookup;
/** Unique identifier for Ship Via associated with Purchase Order Receipt. */
msdyn_ShipVia: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Purchase Order Receipt */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
nav_msdyn_msdyn_purchaseorderreceipt_msdyn_purchaseorderreceiptproduct_PurchaseOrderReceipt: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
RECEIPT_PRODUCTS: DevKit.Controls.Grid;
}
}
class FormPurchase_Order_Receipt extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Purchase_Order_Receipt
* @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 Purchase_Order_Receipt */
Body: DevKit.FormPurchase_Order_Receipt.Body;
/** The Footer section of form Purchase_Order_Receipt */
Footer: DevKit.FormPurchase_Order_Receipt.Footer;
/** The Navigation of form Purchase_Order_Receipt */
Navigation: DevKit.FormPurchase_Order_Receipt.Navigation;
/** The Grid of form Purchase_Order_Receipt */
Grid: DevKit.FormPurchase_Order_Receipt.Grid;
}
namespace FormPurchase_Order_Receipt_Mobile {
interface tab_fstab_general_Sections {
fstab_general_section_general: DevKit.Controls.Section;
}
interface tab_fstab_other_Sections {
tab_3_section_1: DevKit.Controls.Section;
tab_3_section_2: DevKit.Controls.Section;
tab_3_section_3: DevKit.Controls.Section;
}
interface tab_fstab_sub_grids_Sections {
fstab_sub_grids_section: DevKit.Controls.Section;
fstab_sub_grids_section_2: DevKit.Controls.Section;
fstab_sub_grids_section_3: DevKit.Controls.Section;
}
interface tab_fstab_general extends DevKit.Controls.ITab {
Section: tab_fstab_general_Sections;
}
interface tab_fstab_other extends DevKit.Controls.ITab {
Section: tab_fstab_other_Sections;
}
interface tab_fstab_sub_grids extends DevKit.Controls.ITab {
Section: tab_fstab_sub_grids_Sections;
}
interface Tabs {
fstab_general: tab_fstab_general;
fstab_other: tab_fstab_other;
fstab_sub_grids: tab_fstab_sub_grids;
}
interface Body {
Tab: Tabs;
msdyn_DateReceived: DevKit.Controls.Date;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
msdyn_Note: DevKit.Controls.String;
/** Unique identifier for Purchase Order associated with Purchase Order Receipt. */
msdyn_PurchaseOrder: DevKit.Controls.Lookup;
/** Unique identifier for User associated with Purchase Order Receipt. */
msdyn_ReceivedBy: DevKit.Controls.Lookup;
/** Unique identifier for Ship Via associated with Purchase Order Receipt. */
msdyn_ShipVia: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface Navigation {
nav_msdyn_msdyn_purchaseorderreceipt_msdyn_purchaseorderreceiptproduct_PurchaseOrderReceipt: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
RECEIPT_PRODUCTS: DevKit.Controls.Grid;
}
}
class FormPurchase_Order_Receipt_Mobile extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Purchase_Order_Receipt_Mobile
* @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 Purchase_Order_Receipt_Mobile */
Body: DevKit.FormPurchase_Order_Receipt_Mobile.Body;
/** The Navigation of form Purchase_Order_Receipt_Mobile */
Navigation: DevKit.FormPurchase_Order_Receipt_Mobile.Navigation;
/** The Grid of form Purchase_Order_Receipt_Mobile */
Grid: DevKit.FormPurchase_Order_Receipt_Mobile.Grid;
}
class msdyn_purchaseorderreceiptApi {
/**
* DynamicsCrm.DevKit msdyn_purchaseorderreceiptApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
msdyn_DateReceived_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
msdyn_Note: DevKit.WebApi.StringValue;
/** Unique identifier for Purchase Order associated with Purchase Order Receipt. */
msdyn_PurchaseOrder: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_purchaseorderreceiptId: DevKit.WebApi.GuidValue;
/** Unique identifier for User associated with Purchase Order Receipt. */
msdyn_ReceivedBy: DevKit.WebApi.LookupValue;
/** Unique identifier for Ship Via associated with Purchase Order Receipt. */
msdyn_ShipVia: DevKit.WebApi.LookupValue;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Contains the ID of the process associated with the entity. */
processid: DevKit.WebApi.GuidValue;
/** Contains the ID of the stage where the entity is located. */
stageid: DevKit.WebApi.GuidValue;
/** Status of the Purchase Order Receipt */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Purchase Order Receipt */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows a comma-separated list of string values that represent the unique identifiers of stages in a business process flow instance in the order that they occur. */
traversedpath: DevKit.WebApi.StringValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_purchaseorderreceipt {
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Purchase Order Receipt','Purchase Order Receipt - Mobile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import * as vscode from "vscode";
// import Bracket from "./bracket";
import BracketClose from "./bracketClose";
import { IStackElement } from "./IExtensionGrammar";
import LanguageConfig from "./languageConfig";
import LineState from "./lineState";
import Settings from "./settings";
import TextLine from "./textLine";
import { ignoreBracketsInToken, LineTokens } from "./vscodeFiles";
// import { TextDocumentContentChangeEvent } from "vscode";
import { glo, IEditorInfo, updateAllControlledEditors } from "../extension";
import { nukeAllDecs, nukeJunkDecorations } from "../utils2";
// let refresherTimeout: NodeJS.Timeout | undefined = undefined;
let leakCleanTimeoutStarted = false;
export default class DocumentDecoration {
public readonly settings: Settings;
// This program caches lines, and will only analyze linenumbers including or above a modified line
public lines: TextLine[] = [];
private readonly document: vscode.TextDocument;
private readonly languageConfig: LanguageConfig;
private scopeDecorations: vscode.TextEditorDecorationType[] = [];
private scopeSelectionHistory: vscode.Selection[][] = [];
constructor(
document: vscode.TextDocument,
config: LanguageConfig,
settings: Settings,
) {
this.settings = settings;
this.document = document;
this.languageConfig = config;
}
public dispose() {
this.disposeScopeDecorations();
}
// Lines are stored in an array, if line is requested outside of array bounds
// add emptys lines until array is correctly sized
public getLine(index: number, state: IStackElement): TextLine {
if (index < this.lines.length) {
return this.lines[index];
} else {
if (this.lines.length === 0) {
this.lines.push(
new TextLine(
state,
new LineState(this.settings, this.languageConfig),
0,
),
);
}
if (index < this.lines.length) {
return this.lines[index];
}
if (index === this.lines.length) {
const previousLine = this.lines[this.lines.length - 1];
const newLine = new TextLine(
state,
previousLine.cloneState(),
index,
);
this.lines.push(newLine);
return newLine;
}
throw new Error("Cannot look more than one line ahead");
}
}
public tokenizeDocument(editorInfo: IEditorInfo): {
char: string;
type: number;
inLineIndexZero: number;
lineZero: number;
}[] {
// console.log("Tokenizing " + this.document.fileName);
// One document may be shared by multiple editors (side by side view)
const editors: vscode.TextEditor[] =
vscode.window.visibleTextEditors.filter(
(e) => this.document === e.document,
);
if (editors.length === 0) {
console.warn(
"No editors associated with document: " +
this.document.fileName,
);
// if (refresherTimeout) {
// clearTimeout(refresherTimeout); // maybe it's better without it
// }
// refresherTimeout = setTimeout(() => {
// console.log("before if");
if (!leakCleanTimeoutStarted) {
// console.log("after if");
leakCleanTimeoutStarted = true;
setTimeout(() => {
leakCleanTimeoutStarted = false;
// junkDecors3dArr.push(editorInfo.decors);
nukeJunkDecorations();
nukeAllDecs();
updateAllControlledEditors({
alsoStillVisibleAndHist: true,
});
}, 20000);
}
return [];
}
// console.time("tokenizeDocument");
this.lines = [];
const lineIndex = this.lines.length;
const lineCount = this.document.lineCount;
if (lineIndex < lineCount) {
// console.log("Reparse from line: " + (lineIndex + 1));
for (let i = lineIndex; i < lineCount; i++) {
const newLine = this.tokenizeLine(i, editorInfo);
this.lines.push(newLine);
}
}
// console.log("Coloring document");
// IMPORTANT
let myBrackets: {
char: string;
type: number;
inLineIndexZero: number;
lineZero: number;
}[] = [];
for (const line of this.lines) {
const brackets = line.getAllBrackets();
for (const bracket of brackets) {
myBrackets.push({
char: bracket.token.character,
type: bracket.token.type,
inLineIndexZero: bracket.token.range.start.character,
lineZero: bracket.token.range.start.line,
});
}
}
// console.log("myBrackets:", myBrackets);
return myBrackets;
// IMPORTANT GO GO GO
// this.colorDecorations(editors);
// console.timeEnd("tokenizeDocument");
}
private tokenizeLine(index: number, editorInfo: IEditorInfo) {
// const originalLine = this.document.lineAt(index).text;
const monoLine = editorInfo.monoText.slice(
editorInfo.textLinesMap[index],
editorInfo.textLinesMap[index + 1],
);
// console.log(`originalLine->${originalLine}`);
// tabsIntoSpaces
// let tabsize = 4;
// if (typeof editorInfo.editorRef.options.tabSize === "number") {
// tabsize = editorInfo.editorRef.options.tabSize;
// }
// let preparedLineText = originalLine;
// if (this.document.eol === 2) {
// preparedLineText = preparedLineText.replace(/\r/g, ``); // may be needed, LF, CRLF
// }
// preparedLineText = tabsIntoSpaces(preparedLineText, tabsize);
// if (glo.trySupportDoubleWidthChars) {
// preparedLineText = preparedLineText.replace(
// doubleWidthCharsReg,
// "Z_",
// );
// }
const newText = monoLine;
const previousLineRuleStack =
index > 0 ? this.lines[index - 1].getRuleStack() : undefined;
const previousLineState =
index > 0
? this.lines[index - 1].cloneState()
: new LineState(this.settings, this.languageConfig);
const tokenized = this.languageConfig.grammar.tokenizeLine2(
newText,
previousLineRuleStack,
);
const tokens = tokenized.tokens;
const lineTokens = new LineTokens(tokens, newText);
const matches = new Array<{ content: string; index: number }>();
const count = lineTokens.getCount();
for (let i = 0; i < count; i++) {
const tokenType = lineTokens.getStandardTokenType(i);
if (!ignoreBracketsInToken(tokenType)) {
const searchStartOffset = tokens[i * 2];
const searchEndOffset =
i < count ? tokens[(i + 1) * 2] : newText.length;
const currentTokenText = newText.substring(
searchStartOffset,
searchEndOffset,
);
let result: RegExpExecArray | null;
// tslint:disable-next-line:no-conditional-assignment
while (
(result =
this.languageConfig.regex.exec(currentTokenText)) !==
null
) {
matches.push({
content: result[0],
index: result.index + searchStartOffset,
});
}
}
}
const newLine = new TextLine(
tokenized.ruleStack,
previousLineState,
index,
);
for (const match of matches) {
const lookup = this.languageConfig.bracketToId.get(match.content);
if (lookup) {
newLine.AddToken(
match.content,
match.index,
lookup.key,
lookup.open,
);
}
}
return newLine;
}
private disposeScopeDecorations() {
for (const decoration of this.scopeDecorations) {
decoration.dispose();
}
this.scopeDecorations = [];
}
private searchScopeForwards(
position: vscode.Position,
): BracketClose | undefined {
for (let i = position.line; i < this.lines.length; i++) {
const endBracket = this.lines[i].getClosingBracket(position);
if (endBracket) {
return endBracket;
}
}
}
private calculateColumnFromCharIndex(
lineText: string,
charIndex: number,
tabSize: number,
): number {
let spacing = 0;
for (let index = 0; index < charIndex; index++) {
if (lineText.charAt(index) === "\t") {
spacing += tabSize - (spacing % tabSize);
} else {
spacing++;
}
}
return spacing;
}
private calculateCharIndexFromColumn(
lineText: string,
column: number,
tabSize: number,
): number {
let spacing = 0;
for (let index = 0; index <= column; index++) {
if (spacing >= column) {
return index;
}
if (lineText.charAt(index) === "\t") {
spacing += tabSize - (spacing % tabSize);
} else {
spacing++;
}
}
return spacing;
}
} | the_stack |
import sver from 'sver';
const { Semver, SemverRange } = sver;
import { Log } from '../common/log.js';
import { Resolver } from "../trace/resolver.js";
import { ExactPackage, newPackageTarget, PackageTarget } from "./package.js";
import { isURL, importedFrom } from "../common/url.js";
import { JspmError, throwInternalError } from "../common/err.js";
import { nodeBuiltinSet } from '../providers/node.js';
import { Provider } from '../providers/index.js';
import { parseUrlPkg } from '../providers/jspm.js';
export interface PackageProvider {
provider: string;
layer: string;
}
export interface PackageInstall {
name: string;
pkgUrl: string;
}
export interface PackageInstallRange {
name: string;
pkgUrl: string;
target: PackageTarget;
}
export type InstallTarget = PackageTarget | URL;
export interface LockFile {
exists: boolean;
resolutions: LockResolutions;
}
export interface LockResolutions {
[pkgUrl: string]: Record<string, string>;
}
export interface InstalledRanges {
[exactName: string]: PackageInstallRange[];
}
function addInstalledRange (installedRanges: InstalledRanges, name: string, pkgUrl: string, target: PackageTarget) {
const ranges = getInstalledRanges(installedRanges, target);
for (const range of ranges) {
if (range.name === name && range.pkgUrl === pkgUrl)
return;
}
ranges.push({ name, pkgUrl, target });
}
function getInstalledRanges (installedRanges: InstalledRanges, target: PackageTarget): PackageInstallRange[] {
return installedRanges[target.registry + ':' + target.name] = installedRanges[target.registry + ':' + target.name] || [];
}
export interface InstallOptions {
// default base for relative installs
baseUrl: URL;
// create a lockfile if it does not exist
lock?: LockFile;
// do not modify the lockfile
freeze?: boolean;
// force use latest versions for everything we touch
latest?: boolean;
// if a resolution is not in its expected range
// / expected URL (usually due to manual user edits),
// force override a new install
reset?: boolean;
// stdlib target
stdlib?: string;
// whether to prune the dependency installs
prune?: boolean;
// save flags
save?: boolean;
saveDev?: boolean;
savePeer?: boolean;
saveOptional?: boolean;
// dependency resolutions overrides
resolutions?: Record<string, string>;
defaultProvider?: string;
providers?: Record<string, string>;
}
function pruneResolutions (resolutions: LockResolutions, to: [string, string][]): LockResolutions {
const newResolutions: LockResolutions = {};
for (const [name, parent] of to) {
const resolution = resolutions[parent][name];
newResolutions[parent] = newResolutions[parent] || {};
newResolutions[parent][name] = resolution;
}
return newResolutions;
}
function getResolution (resolutions: LockResolutions, name: string, pkgUrl: string): string | undefined {
if (!pkgUrl.endsWith('/'))
throwInternalError(pkgUrl);
resolutions[pkgUrl] = resolutions[pkgUrl] || {};
return resolutions[pkgUrl][name];
}
function stringResolution (resolution: string, subpath: string | null) {
if (!resolution.endsWith('/'))
throwInternalError(resolution);
return subpath ? resolution.slice(0, -1) + '|' + subpath : resolution;
}
export function setResolution (resolutions: LockResolutions, name: string, pkgUrl: string, resolution: string, subpath: string | null) {
if (!pkgUrl.endsWith('/'))
throwInternalError(pkgUrl);
resolutions[pkgUrl] = resolutions[pkgUrl] || {};
const strResolution = stringResolution(resolution, subpath);
if (resolutions[pkgUrl][name] === strResolution)
return false;
resolutions[pkgUrl][name] = strResolution;
return true;
}
export class Installer {
opts: InstallOptions;
installedRanges: InstalledRanges = {};
installs: LockResolutions;
installing = false;
newInstalls = false;
currentInstall = Promise.resolve();
// @ts-ignore
stdlibTarget: InstallTarget;
installBaseUrl: string;
added = new Map<string, InstallTarget>();
hasLock = false;
defaultProvider = { provider: 'jspm', layer: 'default' };
providers: Record<string, string>;
resolutions: Record<string, string>;
log: Log;
resolver: Resolver;
constructor (baseUrl: URL, opts: InstallOptions, log: Log, resolver: Resolver) {
this.log = log;
this.resolver = resolver;
this.resolutions = opts.resolutions || {};
this.installBaseUrl = baseUrl.href;
this.opts = opts;
let resolutions: LockResolutions = {};
if (opts.lock)
({ resolutions, exists: this.hasLock } = opts.lock);
if (opts.defaultProvider)
this.defaultProvider = {
provider: opts.defaultProvider.split('.')[0],
layer: opts.defaultProvider.split('.')[1] || 'default'
};
this.providers = opts.providers || {};
this.installs = resolutions;
if (opts.stdlib) {
if (isURL(opts.stdlib) || opts.stdlib[0] === '.') {
this.stdlibTarget = new URL(opts.stdlib, baseUrl);
if (this.stdlibTarget.href.endsWith('/'))
this.stdlibTarget.pathname = this.stdlibTarget.pathname.slice(0, -1);
}
else {
this.stdlibTarget = newPackageTarget(opts.stdlib, this.installBaseUrl);
}
}
}
async startInstall (): Promise<(success: boolean) => Promise<false | { pjsonChanged: boolean, lock: LockResolutions }>> {
if (this.installing)
return this.currentInstall.then(() => this.startInstall());
let finishInstall: (success: boolean) => Promise<false | { pjsonChanged: boolean, lock: LockResolutions }>;
this.installing = true;
this.newInstalls = false;
this.added = new Map<string, InstallTarget>();
this.currentInstall = new Promise(resolve => {
finishInstall = async (success: boolean) => {
if (!success) {
this.installing = false;
resolve();
return false;
}
// const save = this.opts.save || this.opts.saveDev || this.opts.savePeer || this.opts.saveOptional || this.hasLock || this.opts.lock;
// // update the package.json dependencies
// let pjsonChanged = false;
// const saveField: DependenciesField = this.opts.saveDev ? 'devDependencies' : this.opts.savePeer ? 'peerDependencies' : this.opts.saveOptional ? 'optionalDependencies' : 'dependencies';
// if (saveField && save) {
// pjsonChanged = await updatePjson(this.resolver, this.installBaseUrl, async pjson => {
// pjson[saveField!] = pjson[saveField!] || {};
// for (const [name, target] of this.added) {
// if (target instanceof URL) {
// if (target.protocol === 'file:') {
// pjson[saveField!]![name] = 'file:' + path.relative(fileURLToPath(this.installBaseUrl), fileURLToPath(target));
// }
// else {
// pjson[saveField!]![name] = target.href;
// }
// }
// else {
// let versionRange = target.ranges.map(range => range.toString()).join(' || ');
// if (versionRange === '*') {
// const pcfg = await this.resolver.getPackageConfig(this.installs[this.installBaseUrl][target.name]);
// if (pcfg)
// versionRange = '^' + pcfg?.version;
// }
// pjson[saveField!]![name] = (target.name === name ? '' : target.registry + ':' + target.name + '@') + versionRange;
// }
// }
// });
// }
// // prune the lockfile to the include traces only
// // this is done after pjson updates to include any adds
// if (this.opts.prune || pjsonChanged) {
// const deps = await this.resolver.getDepList(this.installBaseUrl, true);
// // existing deps is any existing builtin resolutions
// const existingBuiltins = new Set(Object.keys(this.installs[this.installBaseUrl] || {}).filter(name => nodeBuiltinSet.has(name)));
// await this.lockInstall([...new Set([...deps, ...existingBuiltins])], this.installBaseUrl, true);
// }
this.installing = false;
resolve();
return { pjsonChanged: false, lock: this.installs };
};
});
return finishInstall!;
}
async lockInstall (installs: string[], pkgUrl = this.installBaseUrl, prune = true) {
const visited = new Set<string>();
const visitInstall = async (name: string, pkgUrl: string): Promise<void> => {
if (visited.has(name + '##' + pkgUrl))
return;
visited.add(name + '##' + pkgUrl);
const installUrl = await this.install(name, pkgUrl);
const installPkgUrl = installUrl.split('|')[0] + (installUrl.indexOf('|') === -1 ? '' : '/');
const deps = await this.resolver.getDepList(installPkgUrl);
const existingDeps = Object.keys(this.installs[installPkgUrl] || {});
await Promise.all([...new Set([...deps, ...existingDeps])].map(dep => visitInstall(dep, installPkgUrl)));
};
await Promise.all(installs.map(install => visitInstall(install, pkgUrl)));
if (prune) {
const pruneList: [string, string][] = [...visited].map(item => {
const [name, pkgUrl] = item.split('##');
return [name, pkgUrl];
});
this.installs = pruneResolutions(this.installs, pruneList);
}
}
replace (target: InstallTarget, replacePkgUrl: string, provider: PackageProvider): boolean {
let targetUrl: string;
if (target instanceof URL) {
targetUrl = target.href;
}
else {
const pkg = this.getBestMatch(target);
if (!pkg) {
if (this.installs[replacePkgUrl])
return false;
throw new Error('No installation found to replace.');
}
targetUrl = this.resolver.pkgToUrl(pkg, provider);
}
let replaced = false;
for (const pkgUrl of Object.keys(this.installs)) {
for (const name of Object.keys(this.installs[pkgUrl])) {
if (this.installs[pkgUrl][name] === targetUrl) {
this.installs[pkgUrl][name] = replacePkgUrl;
replaced = true;
}
}
if (pkgUrl === targetUrl) {
this.installs[replacePkgUrl] = this.installs[pkgUrl];
delete this.installs[pkgUrl];
replaced = true;
}
}
return replaced;
}
async installTarget (pkgName: string, target: InstallTarget, pkgScope: string, pjsonPersist: boolean, subpath: string | null, parentUrl: string): Promise<string> {
if (this.opts.freeze)
throw new JspmError(`"${pkgName}" is not installed in the jspm lockfile, imported from ${parentUrl}.`, 'ERR_NOT_INSTALLED');
if (pjsonPersist) {
if (pkgScope === this.installBaseUrl && pkgScope.startsWith('file:')) {
this.added.set(pkgName, target);
}
else {
this.log('info', `Package ${pkgName} not declared in package.json dependencies${importedFrom(parentUrl)}.`);
}
}
if (target instanceof URL) {
this.log('install', `${pkgName} ${pkgScope} -> ${target.href}`);
const pkgUrl = target.href + (target.href.endsWith('/') ? '' : '/');
this.newInstalls = setResolution(this.installs, pkgName, pkgScope, pkgUrl, subpath);
return stringResolution(pkgUrl, subpath);
}
let provider = this.defaultProvider;
for (const name of Object.keys(this.providers)) {
if (target.name.startsWith(name) && (target.name.length === name.length || target.name[name.length] === '/')) {
provider = { provider: this.providers[name], layer: 'default' };
const layerIndex = provider.provider.indexOf('.');
if (layerIndex !== -1) {
provider.layer = provider.provider.slice(layerIndex + 1);
provider.provider = provider.provider.slice(0, layerIndex);
}
break;
}
}
if (this.opts.freeze) {
const existingInstall = this.getBestMatch(target);
if (existingInstall) {
this.log('install', `${pkgName} ${pkgScope} -> ${existingInstall.registry}:${existingInstall.name}@${existingInstall.version}`);
const pkgUrl = this.resolver.pkgToUrl(existingInstall, provider);
this.newInstalls = setResolution(this.installs, pkgName, pkgScope, pkgUrl, subpath);
addInstalledRange(this.installedRanges, pkgName, pkgScope, target);
return stringResolution(pkgUrl, subpath);
}
}
const latest = await this.resolver.resolveLatestTarget(target, false, provider, parentUrl);
const installed = getInstalledRanges(this.installedRanges, target);
const restrictedToPkg = this.tryUpgradePackagesTo(latest, target, installed, provider);
// cannot upgrade to latest -> stick with existing resolution (if compatible)
if (restrictedToPkg && !this.opts.latest) {
if (restrictedToPkg instanceof URL)
this.log('install', `${pkgName} ${pkgScope} -> ${restrictedToPkg.href}`);
else
this.log('install', `${pkgName} ${pkgScope} -> ${restrictedToPkg.registry}:${restrictedToPkg.name}@${restrictedToPkg.version}`);
const pkgUrl = restrictedToPkg instanceof URL ? restrictedToPkg.href : this.resolver.pkgToUrl(restrictedToPkg, provider);
this.newInstalls = setResolution(this.installs, pkgName, pkgScope, pkgUrl, subpath);
addInstalledRange(this.installedRanges, pkgName, pkgScope, target);
return stringResolution(pkgUrl, subpath);
}
this.log('install', `${pkgName} ${pkgScope} -> ${latest.registry}:${latest.name}@${latest.version}`);
const pkgUrl = this.resolver.pkgToUrl(latest, provider);
this.newInstalls = setResolution(this.installs, pkgName, pkgScope, pkgUrl, subpath);
addInstalledRange(this.installedRanges, pkgName, pkgScope, target);
return stringResolution(pkgUrl, subpath);
}
async install (pkgName: string, pkgUrl: string, nodeBuiltins = true, parentUrl: string = this.installBaseUrl): Promise<string> {
if (!this.installing)
throwInternalError('Not installing');
if (!this.opts.reset) {
const existingUrl = this.installs[pkgUrl]?.[pkgName];
if (existingUrl && !this.opts.reset)
return existingUrl;
}
if (this.resolutions[pkgName]) {
return this.installTarget(pkgName, newPackageTarget(this.resolutions[pkgName], this.opts.baseUrl.href, pkgName), pkgUrl, false, null, parentUrl);
}
const pcfg = await this.resolver.getPackageConfig(pkgUrl) || {};
// node.js core
if (nodeBuiltins && nodeBuiltinSet.has(pkgName)) {
return this.installTarget(pkgName, this.stdlibTarget, pkgUrl, false, 'nodelibs/' + pkgName, parentUrl);
}
// package dependencies
const installTarget = pcfg.dependencies?.[pkgName] || pcfg.peerDependencies?.[pkgName] || pcfg.optionalDependencies?.[pkgName] || pkgUrl === this.installBaseUrl && pcfg.devDependencies?.[pkgName];
if (installTarget) {
const target = newPackageTarget(installTarget, pkgUrl, pkgName);
return this.installTarget(pkgName, target, pkgUrl, false, null, parentUrl);
}
// import map "imports"
if (this.installs[this.installBaseUrl]?.[pkgName])
return this.installs[this.installBaseUrl][pkgName];
// global install fallback
const target = newPackageTarget('*', pkgUrl, pkgName);
const exactInstall = await this.installTarget(pkgName, target, pkgUrl, true, null, parentUrl);
return exactInstall;
}
private getBestMatch (matchPkg: PackageTarget): ExactPackage | null {
let bestMatch: ExactPackage | null = null;
for (const pkgUrl of Object.keys(this.installs)) {
const pkg = this.resolver.parseUrlPkg(pkgUrl);
if (pkg && this.inRange(pkg.pkg, matchPkg)) {
if (bestMatch)
bestMatch = Semver.compare(new Semver(bestMatch.version), pkg.pkg.version) === -1 ? pkg.pkg : bestMatch;
else
bestMatch = pkg.pkg;
}
}
return bestMatch;
}
private inRange (pkg: ExactPackage, target: PackageTarget) {
return pkg.registry === target.registry && pkg.name === target.name && target.ranges.some(range => range.has(pkg.version, true));
}
// upgrade any existing packages to this package if possible
private tryUpgradePackagesTo (pkg: ExactPackage, target: PackageTarget, installed: PackageInstallRange[], provider: PackageProvider): ExactPackage | URL | undefined {
if (this.opts.freeze) return;
const pkgVersion = new Semver(pkg.version);
let compatible = true;
for (const { target } of installed) {
if (target.ranges.every(range => !range.has(pkgVersion)))
compatible = false;
}
if (compatible) {
for (const { name, pkgUrl } of installed) {
const [resolution, curSubpath] = getResolution(this.installs, name, pkgUrl).split('|');
const parsed = parseUrlPkg(resolution);
if (parsed) {
const { pkg: { version } } = parseUrlPkg(resolution);
if (version !== pkg.version)
this.newInstalls = setResolution(this.installs, name, pkgUrl, this.resolver.pkgToUrl(pkg, provider), curSubpath);
}
else {
this.newInstalls = setResolution(this.installs, name, pkgUrl, resolution, curSubpath);
}
}
}
else {
// get the latest installed version instead that fulfills target (TODO: sort)
for (const { name, pkgUrl } of installed) {
const resolution = getResolution(this.installs, name, pkgUrl).split('|')[0];
const parsed = parseUrlPkg(resolution);
if (parsed) {
const { pkg: { version } } = parseUrlPkg(resolution);
if (target.ranges.some(range => range.has(version)))
return { registry: pkg.registry, name: pkg.name, version };
}
else {
return new URL(resolution.endsWith('/') ? resolution : resolution + '/');
}
}
}
}
} | the_stack |
import * as fs from 'fs-extra';
import * as path from 'path';
import * as portfinder from 'portfinder';
import * as prettier from 'prettier';
import * as urlJoin from 'url-join';
import * as webpack from 'webpack';
import { pri } from '../../../node';
import { analyseProject } from '../../../utils/analyse-project';
import { createEntry } from '../../../utils/create-entry';
import { globalState } from '../../../utils/global-state';
import { logInfo, spinner } from '../../../utils/log';
import { WrapContent } from '../../../utils/webpack-plugin-wrap-content';
import { getPluginsByOrder } from '../../../utils/plugins';
import { prettierConfig } from '../../../utils/prettier-config';
import * as projectState from '../../../utils/project-state';
import { tempJsEntryPath, tempPath } from '../../../utils/structor-config';
import { runWebpack, bundleDlls } from '../../../utils/webpack';
import { runWebpackDevServer } from '../../../utils/webpack-dev-server';
import dashboardClientServer from './dashboard/server/client-server';
import dashboardServer from './dashboard/server/index';
import { dllOutPath, dllFileName, dllMainfestName, libraryStaticPath } from './dll';
const dashboardBundleFileName = 'main';
export const projectDev = async (options: any) => {
if (options && options.debugDashboard) {
await debugDashboard();
} else {
await debugProject(options);
}
};
async function debugDashboard() {
const analyseInfo = await spinner('Analyse project', async () => {
const scopeAnalyseInfo = await analyseProject();
await createEntry();
return scopeAnalyseInfo;
});
const freePort = await portfinder.getPortPromise();
const dashboardServerPort = await portfinder.getPortPromise({ port: freePort + 1 });
// Start dashboard server
dashboardServer({ serverPort: dashboardServerPort, analyseInfo });
// Create dashboard entry
const dashboardEntryFilePath = createDashboardEntry();
// Serve dashboard
await runWebpackDevServer({
mode: 'development',
autoOpenBrowser: true,
hot: pri.sourceConfig.hotReload,
publicPath: '/static/',
entryPath: dashboardEntryFilePath,
devServerPort: freePort,
outFileName: 'main.[hash].js',
htmlTemplatePath: path.join(__dirname, '../../../../template-dashboard.ejs'),
htmlTemplateArgs: {
dashboardServerPort,
},
});
}
async function debugProject(options?: any) {
const freePort = pri.sourceConfig.devPort || (await portfinder.getPortPromise());
const dashboardServerPort = await portfinder.getPortPromise({ port: freePort + 1 });
const dashboardClientPort = await portfinder.getPortPromise({ port: freePort + 2 });
const pipeConfig = async (config: webpack.Configuration) => {
const dllHttpPath = urlJoin(
`${globalState.sourceConfig.useHttps ? 'https' : 'http'}://${pri.sourceConfig.host}:${freePort}`,
libraryStaticPath,
);
config.plugins.push(
new WrapContent(
`
var dllScript = document.createElement("script");
dllScript.src = "${dllHttpPath}";
dllScript.onload = runEntry;
document.body.appendChild(dllScript);
function runEntry() {
`,
'}',
),
);
return config;
};
debugProjectPrepare(dashboardClientPort);
await pri.project.ensureProjectFiles();
await pri.project.checkProjectFiles();
const analyseInfo = await spinner('Analyse project', async () => {
const scopeAnalyseInfo = await analyseProject();
await createEntry();
return scopeAnalyseInfo;
});
await bundleDlls({ dllOutPath, dllFileName, dllMainfestName });
// Bundle dashboard if plugins changed or dashboard bundle not exist.
const dashboardDistDir = path.join(pri.projectRootPath, tempPath.dir, 'static/dashboard-bundle');
if (!fs.existsSync(path.join(dashboardDistDir, `${dashboardBundleFileName}.js`))) {
const dashboardEntryFilePath = createDashboardEntry();
const status = await runWebpack({
mode: 'production',
publicPath: '/bundle/',
entryPath: dashboardEntryFilePath,
distDir: dashboardDistDir,
outFileName: 'main.[hash].js', // dashboard has no css file
pipeConfig,
});
projectState.set('dashboardHash', status.hash);
}
const stdoutOfAnyType = process.stdout as any;
try {
stdoutOfAnyType.clearLine(0);
} catch {
//
}
logInfo('\nStart dev server.\n');
// Start dashboard server
dashboardServer({ serverPort: dashboardServerPort, analyseInfo });
if (globalState.sourceConfig.useHttps) {
logInfo('you should set chrome://flags/#allow-insecure-localhost, to trust local certificate.');
}
// Start dashboard client production server
dashboardClientServer({
serverPort: dashboardServerPort,
clientPort: dashboardClientPort,
staticRootPath: path.join(pri.projectRootPath, tempPath.dir, 'static'),
hash: projectState.get('dashboardHash'),
});
// Serve project
await runWebpackDevServer({
mode: options?.mode ?? 'development',
autoOpenBrowser: true,
hot: pri.sourceConfig.hotReload,
publicPath: globalState.sourceConfig.publicPath,
entryPath: {
[path.basename(pri.sourceConfig.outFileName, '.js')]: path.join(
globalState.projectRootPath,
path.format(tempJsEntryPath),
),
...pri.sourceConfig.entries,
},
outFileName: '[name].js',
devServerPort: freePort,
...(pri.sourceConfig.useHtmlTemplate && {
htmlTemplatePath: path.join(__dirname, '../../../../template-project.ejs'),
htmlTemplateArgs: {
dashboardServerPort,
},
}),
pipeConfig,
});
}
function debugProjectPrepare(dashboardClientPort: number) {
pri.project.onCreateEntry((__, entry) => {
if (pri.isDevelopment) {
entry.pipeEnvironmentBody(envText => {
return `
${envText}
priStore.globalState = ${JSON.stringify(globalState)}
`;
});
// Jump page from iframe dashboard event.
entry.pipeAppClassDidMount(entryDidMount => {
return `
${entryDidMount}
window.addEventListener("message", event => {
const data = event.data
switch(data.type) {
case "changeRoute":
customHistory.push(data.path)
break
default:
}
}, false)
`;
});
// React hot loader
entry.pipeAppHeader(header => {
return `
${header}
import { hot } from "react-hot-loader/root"
import { setConfig } from "react-hot-loader"
`;
});
entry.pipeAppBody(str => {
return `
setConfig({
ignoreSFC: true, // RHL will be __completely__ disabled for SFC
pureRender: true, // RHL will not change render method
})
${str}
`;
});
entry.pipe.set('appExportName', () => {
return 'hot(App)';
});
// Load webui iframe
entry.pipeEntryRender(str => {
return `
${str}
const webUICss = \`
#pri-help-button {
position: fixed;
display: flex;
justify-content: center;
align-items: center;
width: 140px;
height: 30px;
transform: rotate(90deg);
font-size: 14px;
right: -55px;
top: calc(50% - 15px);
border: 1px solid #ddd;
border-top: none;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
color: #666;
z-index: 10001;
cursor: pointer;
transition: all .2s;
background-color: white;
user-select: none;
}
#pri-help-button.active {
right: 744px !important;
}
#pri-help-button:hover {
color: black;
}
#pri-help-iframe {
position: fixed;
right: -810px;
z-index: 10000;
background-color: white;
width: 800px;
top: 0;
height: 100%;
border: 0;
outline: 0;
box-shadow: -1px 0 1px #d4d4d4;
transition: right .2s;
}
#pri-help-iframe.active {
right: 0 !important;
}
\`
const webUIStyle = document.createElement('style')
webUIStyle.type = "text/css"
if ((webUIStyle as any).styleSheet){
(webUIStyle as any).styleSheet.cssText = webUICss
} else {
webUIStyle.appendChild(document.createTextNode(webUICss))
}
document.head.appendChild(webUIStyle)
// Add dashboard iframe
const dashboardIframe = document.createElement("iframe")
dashboardIframe.id = "pri-help-iframe"
dashboardIframe.src = "//${pri.sourceConfig.host}:${dashboardClientPort}"
document.body.appendChild(dashboardIframe)
// Add dashboard button
const dashboardButton = document.createElement("div")
dashboardButton.id = "pri-help-button"
dashboardButton.innerText = "Toggle dashboard"
dashboardButton.onclick = () => {
const activeClassName = "active"
const isShow = dashboardIframe.classList.contains(activeClassName)
if (isShow) {
dashboardIframe.classList.remove(activeClassName)
dashboardButton.classList.remove(activeClassName)
} else {
dashboardIframe.classList.add(activeClassName)
dashboardButton.classList.add(activeClassName)
}
}
document.body.appendChild(dashboardButton)
`;
});
}
});
if (pri.majorCommand === 'dev') {
pri.build.pipeConfig(config => {
if (!pri.isDevelopment) {
return config;
}
config.plugins.push(
new webpack.DllReferencePlugin({
context: '.',
// eslint-disable-next-line import/no-dynamic-require,global-require
manifest: require(path.join(dllOutPath, dllMainfestName)),
}),
);
return config;
});
}
}
function createDashboardEntry() {
const dashboardEntryMainPath = path.join(__dirname, 'dashboard/client/index');
const dashboardEntryFilePath = path.join(pri.projectRootPath, tempPath.dir, 'dashboard/main.tsx');
const webUiEntries: string[] = [];
Array.from(getPluginsByOrder()).forEach(() => {
// try {
// const packageJsonPath = require.resolve(path.join(plugin.pathOrModuleName, 'package.json'), {
// paths: [__dirname, globalState.projectRootPath]
// });
// const packageJson = fs.readJsonSync(packageJsonPath, { throws: false });
// const webEntry = _.get(packageJson, 'pri.web-entry', null);
// if (webEntry) {
// const webEntrys: string[] = typeof webEntry === 'string' ? [webEntry] : webEntry;
// webEntrys.forEach(eachWebEntry => {
// const webEntryAbsolutePath = path.resolve(path.parse(packageJsonPath).dir, eachWebEntry);
// const parsedPath = path.parse(webEntryAbsolutePath);
// const importPath = path.join(parsedPath.dir, parsedPath.name);
// webUiEntries.push(`
// const plugin${webUiEntries.length} = require("${importPath}").default`);
// });
// }
// } catch (error) {
// //
// }
});
fs.outputFileSync(
dashboardEntryFilePath,
prettier.format(
`
const dashboard = require("${dashboardEntryMainPath}").default
${
webUiEntries.length > 0
? `
${webUiEntries.join('\n')}
dashboard([${webUiEntries
.map((each, index) => {
return `plugin${index}`;
})
.join(',')}])
`
: `
dashboard()
`
}
`,
{ ...prettierConfig, parser: 'typescript' },
),
);
return dashboardEntryFilePath;
} | the_stack |
import { GraphQLClientRequest } from './client/types';
import { replaceImagesInMarkdown } from './utils/replaceImages';
import { getTeamProjects } from './utils/getTeamProjects';
import { Importer, ImportResult, Comment } from './types';
import linearClient from './client';
import chalk from 'chalk';
import * as inquirer from 'inquirer';
import _ from 'lodash';
interface ImportAnswers {
newTeam: boolean;
includeComments?: boolean;
includeProject?: string;
selfAssign?: boolean;
targetAssignee?: string;
targetProjectId?: boolean;
targetTeamId?: string;
teamName?: string;
}
interface QueryResponse {
teams: {
nodes: {
id: string;
name: string;
key: string;
projects: {
nodes: {
id: string;
name: string;
key: string;
}[];
};
}[];
};
users: {
nodes: {
id: string;
name: string;
active: boolean;
}[];
};
viewer: {
id: string;
};
}
interface TeamInfoResponse {
team: {
labels: {
nodes: {
id: string;
name: string;
}[];
};
states: {
nodes: {
id: string;
name: string;
}[];
};
};
}
interface LabelCreateResponse {
issueLabelCreate: {
issueLabel: {
id: string;
};
success: boolean;
};
}
/**
* Import issues into Linear via the API.
*/
export const importIssues = async (apiKey: string, importer: Importer) => {
const linear = linearClient(apiKey);
const importData = await importer.import();
const queryInfo = (await linear(`
query {
teams {
nodes {
id
name
key
projects {
nodes {
id
name
}
}
}
}
viewer {
id
}
users {
nodes {
id
name
active
}
}
}
`)) as QueryResponse;
const teams = queryInfo.teams.nodes;
const users = queryInfo.users.nodes.filter(user => user.active);
const me = queryInfo.viewer.id;
// Prompt the user to either get or create a team
const importAnswers = await inquirer.prompt<ImportAnswers>([
{
type: 'confirm',
name: 'newTeam',
message: 'Do you want to create a new team for imported issues?',
default: true,
},
{
type: 'input',
name: 'teamName',
message: 'Name of the team:',
default: importer.defaultTeamName || importer.name,
when: (answers: ImportAnswers) => {
return answers.newTeam;
},
},
{
type: 'list',
name: 'targetTeamId',
message: 'Import into team:',
choices: async () => {
return teams.map((team: { id: string; name: string; key: string }) => ({
name: `[${team.key}] ${team.name}`,
value: team.id,
}));
},
when: (answers: ImportAnswers) => {
return !answers.newTeam;
},
},
{
type: 'confirm',
name: 'includeProject',
message: 'Do you want to import to a specific project?',
when: (answers: ImportAnswers) => {
// if no team is selected then don't show projects screen
if (!answers.targetTeamId) return false;
const projects = getTeamProjects(answers.targetTeamId, teams);
return projects.length > 0;
},
},
{
type: 'list',
name: 'targetProjectId',
message: 'Import into project:',
choices: async (answers: ImportAnswers) => {
const projects = getTeamProjects(answers.targetTeamId as string, teams);
return projects.map((project: { id: string; name: string }) => ({
name: project.name,
value: project.id,
}));
},
when: (answers: ImportAnswers) => {
return answers.includeProject;
},
},
{
type: 'confirm',
name: 'includeComments',
message: 'Do you want to include comments in the issue description?',
when: () => {
return !!importData.issues.find(
issue => issue.comments && issue.comments.length > 0
);
},
},
{
type: 'confirm',
name: 'selfAssign',
message: 'Do you want to assign these issues to yourself?',
default: true,
},
{
type: 'list',
name: 'targetAssignee',
message: 'Assign to user:',
choices: () => {
const map = users.map((user: { id: string; name: string }) => ({
name: user.name,
value: user.id,
}));
map.push({ name: '[Unassigned]', value: '' });
return map;
},
when: (answers: ImportAnswers) => {
return !answers.selfAssign;
},
},
]);
let teamKey: string;
let teamId: string;
if (importAnswers.newTeam) {
// Create a new team
const teamResponse = await linear(
`mutation createIssuesTeam($name: String!) {
teamCreate(input: { name: $name }) {
success
team {
id
name
key
}
}
}
`,
{
name: importAnswers.teamName as string,
}
);
teamKey = teamResponse.teamCreate.team.key;
teamId = teamResponse.teamCreate.team.id;
} else {
// Use existing team
teamKey = teams.find(team => team.id === importAnswers.targetTeamId)!.key;
teamId = importAnswers.targetTeamId as string;
}
const teamInfo = (await linear(`query {
team(id: "${teamId}") {
labels {
nodes {
id
name
}
}
states {
nodes {
id
name
}
}
}
}`)) as TeamInfoResponse;
const issueLabels = teamInfo.team.labels.nodes;
const workflowStates = teamInfo.team.states.nodes;
const existingLabelMap = {} as { [name: string]: string };
for (const label of issueLabels) {
const labelName = label.name.toLowerCase();
if (!existingLabelMap[labelName]) {
existingLabelMap[labelName] = label.id;
}
}
const projectId = importAnswers.targetProjectId;
// Create labels and mapping to source data
const labelMapping = {} as { [id: string]: string };
for (const labelId of Object.keys(importData.labels)) {
const label = importData.labels[labelId];
const labelName = _.truncate(label.name.trim(), { length: 20 });
let actualLabelId = existingLabelMap[labelName.toLowerCase()];
if (!actualLabelId) {
const labelResponse = (await linear(
`
mutation createLabel($teamId: String!, $name: String!, $description: String, $color: String) {
issueLabelCreate(input: { name: $name, description: $description, color: $color, teamId: $teamId }) {
issueLabel {
id
}
success
}
}
`,
{
name: labelName,
description: label.description,
color: label.color,
teamId,
}
)) as LabelCreateResponse;
actualLabelId = labelResponse.issueLabelCreate.issueLabel.id;
existingLabelMap[labelName.toLowerCase()] = actualLabelId;
}
labelMapping[labelId] = actualLabelId;
}
const existingStateMap = {} as { [name: string]: string };
for (const state of workflowStates) {
const stateName = state.name.toLowerCase();
if (!existingStateMap[stateName]) {
existingStateMap[stateName] = state.id;
}
}
const existingUserMap = {} as { [name: string]: string };
for (const user of users) {
const userName = user.name.toLowerCase();
if (!existingUserMap[userName]) {
existingUserMap[userName] = user.id;
}
}
// Create issues
for (const issue of importData.issues) {
const issueDescription = issue.description
? await replaceImagesInMarkdown(
linear,
issue.description,
importData.resourceURLSuffix
)
: undefined;
const description =
importAnswers.includeComments && issue.comments
? await buildComments(
linear,
issueDescription || '',
issue.comments,
importData
)
: issueDescription;
const labelIds = issue.labels
? issue.labels.map(labelId => labelMapping[labelId])
: undefined;
const stateId = !!issue.status
? existingStateMap[issue.status.toLowerCase()]
: undefined;
const existingAssigneeId: string | undefined = !!issue.assigneeId
? existingUserMap[issue.assigneeId.toLowerCase()]
: undefined;
const assigneeId: string | undefined =
existingAssigneeId || importAnswers.selfAssign
? me
: !!importAnswers.targetAssignee &&
importAnswers.targetAssignee.length > 0
? importAnswers.targetAssignee
: undefined;
await linear(
`
mutation createIssue(
$teamId: String!,
$projectId: String,
$title: String!,
$description: String,
$priority: Int,
$labelIds: [String!]
$stateId: String
$assigneeId: String
) {
issueCreate(input: {
teamId: $teamId,
projectId: $projectId,
title: $title,
description: $description,
priority: $priority,
labelIds: $labelIds
stateId: $stateId
assigneeId: $assigneeId
}) {
success
}
}
`,
{
teamId,
projectId,
title: issue.title,
description,
priority: issue.priority,
labelIds,
stateId,
assigneeId,
}
);
}
console.error(
chalk.green(
`${importer.name} issues imported to your backlog: https://linear.app/team/${teamKey}/backlog`
)
);
};
// Build comments into issue description
const buildComments = async (
client: GraphQLClientRequest,
description: string,
comments: Comment[],
importData: ImportResult
) => {
const newComments: string[] = [];
for (const comment of comments) {
const user = importData.users[comment.userId];
const date = comment.createdAt
? comment.createdAt.toISOString().split('T')[0]
: undefined;
const body = await replaceImagesInMarkdown(
client,
comment.body || '',
importData.resourceURLSuffix
);
newComments.push(`**${user.name}**${' ' + date}\n\n${body}\n`);
}
return `${description}\n\n---\n\n${newComments.join('\n\n')}`;
}; | the_stack |
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
orbCount: number;
}
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheTowerOfZot,
timelineFile: 'the_tower_of_zot.txt',
initData: () => {
return {
orbCount: 0,
};
},
triggers: [
{
id: 'Zot Minduruva Bio',
type: 'StartsUsing',
// 62CA in the final phase.
netRegex: NetRegexes.startsUsing({ id: ['62A9', '62CA'], source: 'Minduruva' }),
netRegexDe: NetRegexes.startsUsing({ id: ['62A9', '62CA'], source: 'Rug' }),
netRegexFr: NetRegexes.startsUsing({ id: ['62A9', '62CA'], source: 'Anabella' }),
netRegexJa: NetRegexes.startsUsing({ id: ['62A9', '62CA'], source: 'ラグ' }),
response: Responses.tankBuster(),
},
{
id: 'Zot Minduruva Transmute Counter',
type: 'StartsUsing',
// 629A = Transmute Fire III
// 631B = Transmute Blizzard III
// 631C = Transmute Thunder III
// 631D = Transmute Bio III
netRegex: NetRegexes.startsUsing({ id: ['629A', '631[BCD]'], source: 'Minduruva', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: ['629A', '631[BCD]'], source: 'Rug', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: ['629A', '631[BCD]'], source: 'Anabella', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: ['629A', '631[BCD]'], source: 'ラグ', capture: false }),
// FIXME: if this is `run` then data.orbCount has an off-by-one (one less) count in the emulator.
// `run` must happen synchronously before other triggers if the trigger is not asynchronous.
// It's possible this is a general raidboss bug as well, but it is untested.
preRun: (data) => data.orbCount++,
},
{
id: 'Zot Minduruva Transmute Fire III',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '629A', source: 'Minduruva', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '629A', source: 'Rug', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '629A', source: 'Anabella', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '629A', source: 'ラグ', capture: false }),
durationSeconds: 13,
// These are info so that any Under/Behind from Fire III / Bio III above take precedence.
// But, sometimes the run from Bio III -> Transmute Fire III is tight so warn ahead of
// time which orb the player needs to run to.
infoText: (data, _matches, output) => output.text!({ num: data.orbCount }),
outputStrings: {
text: {
en: 'Under Orb ${num}',
de: 'Unter den ${num}. Orb',
fr: 'En dessous l\'orbe ${num}',
ja: '${num}番目の玉へ',
cn: '靠近第${num}个球',
ko: '${num}번 구슬 밑으로',
},
},
},
{
id: 'Zot Minduruva Transmute Bio III',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '631D', source: 'Minduruva', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '631D', source: 'Rug', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '631D', source: 'Anabella', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '631D', source: 'ラグ', capture: false }),
durationSeconds: 13,
infoText: (data, _matches, output) => output.text!({ num: data.orbCount }),
outputStrings: {
text: {
en: 'Behind Orb ${num}',
de: 'Hinter den ${num}. Orb',
fr: 'Allez derrière l\'orbe ${num}',
ja: '${num}番目の玉の後ろへ',
cn: '去第${num}个球的终点方向贴边',
ko: '${num}번 구슬 뒤로',
},
},
},
{
id: 'Zot Minduruva Dhrupad Reset',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '629C', source: 'Minduruva', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '629C', source: 'Rug', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '629C', source: 'Anabella', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '629C', source: 'ラグ', capture: false }),
// There's a Dhrupad cast after every transmute sequence.
run: (data) => data.orbCount = 0,
},
{
id: 'Zot Sanduruva Isitva Siddhi',
type: 'StartsUsing',
// 62A9 is 2nd boss, 62C0 is 3rd boss.
netRegex: NetRegexes.startsUsing({ id: ['62A9', '62C0'], source: 'Sanduruva' }),
netRegexDe: NetRegexes.startsUsing({ id: ['62A9', '62C0'], source: 'Dug' }),
netRegexFr: NetRegexes.startsUsing({ id: ['62A9', '62C0'], source: 'Samanta' }),
netRegexJa: NetRegexes.startsUsing({ id: ['62A9', '62C0'], source: 'ドグ' }),
response: Responses.tankBuster(),
},
{
id: 'Zot Sanduruva Manusya Berserk',
type: 'Ability',
// 62A1 is 2nd boss, 62BC in the 3rd boss.
netRegex: NetRegexes.ability({ id: ['62A1', '62BC'], source: 'Sanduruva', capture: false }),
netRegexDe: NetRegexes.ability({ id: ['62A1', '62BC'], source: 'Dug', capture: false }),
netRegexFr: NetRegexes.ability({ id: ['62A1', '62BC'], source: 'Samanta', capture: false }),
netRegexJa: NetRegexes.ability({ id: ['62A1', '62BC'], source: 'ドグ', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Go behind empty spot',
de: 'Hinter den leeren Spot gehen',
fr: 'Allez derrière un espace vide',
ja: '玉のない箇所へ',
cn: '去没球球的角落贴边',
ko: '빈 공간 끝으로',
},
},
},
{
id: 'Zot Sanduruva Manusya Confuse',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '62A5', source: 'Sanduruva', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '62A5', source: 'Dug', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '62A5', source: 'Samanta', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '62A5', source: 'ドグ', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Go behind still clone',
de: 'Geh hinter den ruhigen Klon',
fr: 'Allez derrière le vrai clone',
ja: '動いていないドグの後ろへ',
cn: '找不动的boss',
ko: '가만히 있는 분신 뒤로',
},
},
},
{
id: 'Zot Cinduruva Samsara',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '62B9', source: 'Cinduruva', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '62B9', source: 'Mug', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '62B9', source: 'Maria', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '62B9', source: 'マグ', capture: false }),
response: Responses.aoe(),
},
{
id: 'Zot Cinduruva Isitva Siddhi',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '62A9', source: 'Cinduruva' }),
netRegexDe: NetRegexes.startsUsing({ id: '62A9', source: 'Mug' }),
netRegexFr: NetRegexes.startsUsing({ id: '62A9', source: 'Maria' }),
netRegexJa: NetRegexes.startsUsing({ id: '62A9', source: 'マグ' }),
response: Responses.tankBuster(),
},
{
id: 'Zot Cinduruva Delta Thunder III Stack',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '62B8', source: 'Cinduruva' }),
netRegexDe: NetRegexes.startsUsing({ id: '62B8', source: 'Mug' }),
netRegexFr: NetRegexes.startsUsing({ id: '62B8', source: 'Maria' }),
netRegexJa: NetRegexes.startsUsing({ id: '62B8', source: 'マグ' }),
response: Responses.stackMarkerOn(),
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Berserker Sphere': 'Tollwutssphäre',
'Cinduruva': 'Mug',
'Ingenuity\'s Ingress': 'Gelass der Finesse',
'Minduruva': 'Rug',
'Prosperity\'S Promise': 'Gelass des Reichtums',
'Sanduruva': 'Dug',
'Wisdom\'S Ward': 'Gelass der Weisheit',
},
'replaceText': {
'Cinduruva': 'Mug',
'Sanduruva': 'Dug',
'Delayed Element III': 'Verzögertes Element-ga',
'Delayed Thunder III': 'Verzögertes Blitzga',
'Delta Attack': 'Delta-Attacke',
'Delta Blizzard/Fire/Thunder III': 'DeltaEisga/Feuga/Blitzga',
'Dhrupad': 'Dhrupad',
'Explosive Force': 'Zündung',
'Isitva Siddhi': 'Isitva Siddhi',
'Manusya Berserk': 'Manusya-Tollwut',
'Manusya Bio(?! )': 'Manusya-Bio',
'Manusya Bio III': 'Manusya-Bioga',
'Manusya Blizzard(?! )': 'Manusya-Eis',
'Manusya Blizzard III': 'Manusya-Eisga',
'Manusya Confuse': 'Manusya-Konfus',
'Manusya Element III': 'Manusya Element-ga',
'Manusya Faith': 'Manusya-Ener',
'Manusya Fire(?! )': 'Manusya-Feuer',
'Manusya Fire III': 'Manusya-Feuga',
'Manusya Reflect': 'Manusya-Reflektion',
'Manusya Stop': 'Manusya-Stopp',
'Manusya Thunder(?! )': 'Manusya-Blitz',
'Manusya Thunder III': 'Manusya-Blitzga',
'Prakamya Siddhi': 'Prakamya Siddhi',
'Prapti Siddhi': 'Prapti Siddhi',
'Samsara': 'Samsara',
'Sphere Shatter': 'Sphärensplitterung',
'Transmute Thunder III': 'Manipuliertes Blitzga',
'Transmute Element III': 'Manipuliertes Element-ga',
},
},
{
'locale': 'fr',
'replaceSync': {
'Berserker Sphere': 'sphère berserk',
'Cinduruva': 'Maria',
'Ingenuity\'s Ingress': 'Chambre de l\'habileté',
'Minduruva': 'Anabella',
'Prosperity\'S Promise': 'Chambre de la fortune',
'Sanduruva': 'Samanta',
'Wisdom\'S Ward': 'Chambre de la sagesse',
},
'replaceText': {
'Cinduruva': 'Maria',
'Delayed Element III': 'Méga Élément retardé',
'Delayed Thunder III': 'Méga Foudre retardé',
'Delta Attack': 'Attaque Delta',
'Delta Blizzard/Fire/Thunder III': 'Méga Glace/Feu/Foudre delta',
'Dhrupad': 'Dhrupad',
'Explosive Force': 'Détonation',
'Isitva Siddhi': 'Isitva Siddhi',
'Manusya Berserk': 'Berserk manusya',
'Manusya Bio(?! )': 'Bactérie manusya',
'Manusya Bio III': 'Méga Bactérie manusya',
'Manusya Blizzard(?! )': 'Glace manusya',
'Manusya Blizzard III': 'Méga Glace manusya',
'Manusya Confuse': 'Confusion manusya',
'Manusya Element III': 'Méga Élément manusya',
'Manusya Faith': 'Foi manusya',
'Manusya Fire(?! )': 'Feu manusya',
'Manusya Fire III': 'Méga Feu manusya',
'Manusya Reflect': 'Reflet manusya',
'Manusya Stop': 'Stop manusya',
'Manusya Thunder(?! )': 'Foudre manusya',
'Manusya Thunder III': 'Méga Foudre manusya',
'Prakamya Siddhi': 'Prakamya Siddhi',
'Prapti Siddhi': 'Prapti Siddhi',
'Samsara': 'Samsara',
'Sanduruva': 'Samanta',
'Sphere Shatter': 'Rupture',
'Transmute Element III': 'Manipulation magique : Méga Élément',
'Transmute Thunder III': 'Manipulation magique : Méga Foudre',
},
},
{
'locale': 'ja',
'replaceSync': {
'Berserker Sphere': 'バーサクスフィア',
'Cinduruva': 'マグ',
'Ingenuity\'s Ingress': '技巧の間',
'Minduruva': 'ラグ',
'Prosperity\'S Promise': '富の間',
'Sanduruva': 'ドグ',
'Wisdom\'S Ward': '知恵の間',
},
'replaceText': {
'Delayed Element III': '玉:???ガ',
'Delta Attack': 'デルタアタック',
'Delta Blizzard/Fire/Thunder III': 'デルタ・ブリザガ/ファイガ/サンダガ',
'Dhrupad': 'ドゥルパド',
'Explosive Force': '起爆',
'Isitva Siddhi': 'イシトヴァシッディ',
'Manusya Berserk': 'マヌシャ・バーサク',
'Manusya Bio(?! )': 'マヌシャ・バイオ',
'Manusya Bio III': 'マヌシャ・バイオガ',
'Manusya Blizzard(?! )': 'マヌシャ・ブリザド',
'Manusya Blizzard III': 'マヌシャ・ブリザガ',
'Manusya Confuse': 'マヌシャ・コンフュ',
'Manusya Element III': 'マヌシャ・???ガ',
'Manusya Faith': 'マヌシャ・フェイス',
'Manusya Fire(?! )': 'マヌシャ・ファイア',
'Manusya Fire III': 'マヌシャ・ファイガ',
'Manusya Reflect': 'マヌシャ・リフレク',
'Manusya Stop': 'マヌシャ・ストップ',
'Manusya Thunder(?! )': 'マヌシャ・サンダー',
'Manusya Thunder III': 'マヌシャ・サンダガ',
'Prakamya Siddhi': 'プラカーミャシッディ',
'Prapti Siddhi': 'プラプティシッディ',
'Samsara': 'サンサーラ',
'Sphere Shatter': '破裂',
'Transmute Element III': '魔力操作:???ガ',
'Transmute Thunder III': '魔力操作:サンダガ',
},
},
],
};
export default triggerSet; | the_stack |
import { CommonOffset } from "@akashic/pdi-types";
import * as pl from "@akashic/playlog";
import { E, PointDownEvent, PointMoveEvent, PointUpEvent } from "./entities/E";
import { Event, JoinEvent, LeaveEvent, MessageEvent, OperationEvent, PlayerInfoEvent, TimestampEvent } from "./Event";
import { EventIndex } from "./EventIndex";
import { ExceptionFactory } from "./ExceptionFactory";
import { InternalOperationPluginOperation } from "./OperationPluginOperation";
import { Player } from "./Player";
import { StorageValueStore } from "./Storage";
/**
* @ignore
*/
// TODO: Game を意識しないインターフェース を検討する
interface EventConverterParameterObejctGameLike {
db: { [idx: number]: E };
_localDb: { [id: number]: E };
_decodeOperationPluginOperation: (code: number, op: (number | string)[]) => any;
}
export interface EventConverterParameterObejct {
game: EventConverterParameterObejctGameLike;
playerId?: string;
}
/**
* 本クラスのインスタンスをゲーム開発者が直接生成することはなく、ゲーム開発者が利用する必要もない。
* @ignore
*/
export class EventConverter {
_game: EventConverterParameterObejctGameLike;
_playerId: string | null;
_playerTable: { [key: string]: Player };
constructor(param: EventConverterParameterObejct) {
this._game = param.game;
this._playerId = param.playerId ?? null;
this._playerTable = {};
}
/**
* playlog.Eventからg.Eventへ変換する。
*/
toGameEvent(pev: pl.Event): Event {
let pointerId: number;
let entityId: number;
let target: E | undefined;
let point: CommonOffset;
let startDelta: CommonOffset;
let prevDelta: CommonOffset;
let local: boolean;
let timestamp: number;
const eventCode = pev[EventIndex.General.Code];
const prio = pev[EventIndex.General.EventFlags];
const playerId = pev[EventIndex.General.PlayerId];
// @ts-ignore
let player = this._playerTable[playerId] || { id: playerId };
switch (eventCode) {
case pl.EventCode.Join:
player = {
id: playerId,
name: pev[EventIndex.Join.PlayerName]
};
// @ts-ignore
if (this._playerTable[playerId] && this._playerTable[playerId].userData != null) {
// @ts-ignore
player.userData = this._playerTable[playerId].userData;
}
// @ts-ignore
this._playerTable[playerId] = player;
let store: StorageValueStore | undefined = undefined;
if (pev[EventIndex.Join.StorageData]) {
let keys: pl.StorageReadKey[] = [];
let values: pl.StorageValue[][] = [];
pev[EventIndex.Join.StorageData].map((data: pl.StorageData) => {
keys.push(data.readKey);
values.push(data.values);
});
store = new StorageValueStore(keys, values);
}
return new JoinEvent(player, store, prio);
case pl.EventCode.Leave:
delete this._playerTable[player.id];
return new LeaveEvent(player, prio);
case pl.EventCode.Timestamp:
timestamp = pev[EventIndex.Timestamp.Timestamp];
return new TimestampEvent(timestamp, player, prio);
case pl.EventCode.PlayerInfo:
let playerName = pev[EventIndex.PlayerInfo.PlayerName];
let userData: any = pev[EventIndex.PlayerInfo.UserData];
player = {
id: playerId,
name: playerName,
userData
};
// @ts-ignore
this._playerTable[playerId] = player;
return new PlayerInfoEvent(player, prio);
case pl.EventCode.Message:
local = pev[EventIndex.Message.Local];
return new MessageEvent(pev[EventIndex.Message.Message], player, local, prio);
case pl.EventCode.PointDown:
local = pev[EventIndex.PointDown.Local];
pointerId = pev[EventIndex.PointDown.PointerId];
entityId = pev[EventIndex.PointDown.EntityId];
target = entityId == null ? undefined : entityId >= 0 ? this._game.db[entityId] : this._game._localDb[entityId];
point = {
x: pev[EventIndex.PointDown.X],
y: pev[EventIndex.PointDown.Y]
};
return new PointDownEvent(pointerId, target, point, player, local, prio);
case pl.EventCode.PointMove:
local = pev[EventIndex.PointMove.Local];
pointerId = pev[EventIndex.PointMove.PointerId];
entityId = pev[EventIndex.PointMove.EntityId];
target = entityId == null ? undefined : entityId >= 0 ? this._game.db[entityId] : this._game._localDb[entityId];
point = {
x: pev[EventIndex.PointMove.X],
y: pev[EventIndex.PointMove.Y]
};
startDelta = {
x: pev[EventIndex.PointMove.StartDeltaX],
y: pev[EventIndex.PointMove.StartDeltaY]
};
prevDelta = {
x: pev[EventIndex.PointMove.PrevDeltaX],
y: pev[EventIndex.PointMove.PrevDeltaY]
};
return new PointMoveEvent(pointerId, target, point, prevDelta, startDelta, player, local, prio);
case pl.EventCode.PointUp:
local = pev[EventIndex.PointUp.Local];
pointerId = pev[EventIndex.PointUp.PointerId];
entityId = pev[EventIndex.PointUp.EntityId];
target = entityId == null ? undefined : entityId >= 0 ? this._game.db[entityId] : this._game._localDb[entityId];
point = {
x: pev[EventIndex.PointUp.X],
y: pev[EventIndex.PointUp.Y]
};
startDelta = {
x: pev[EventIndex.PointUp.StartDeltaX],
y: pev[EventIndex.PointUp.StartDeltaY]
};
prevDelta = {
x: pev[EventIndex.PointUp.PrevDeltaX],
y: pev[EventIndex.PointUp.PrevDeltaY]
};
return new PointUpEvent(pointerId, target, point, prevDelta, startDelta, player, local, prio);
case pl.EventCode.Operation:
local = pev[EventIndex.Operation.Local];
let operationCode = pev[EventIndex.Operation.OperationCode];
let operationData = pev[EventIndex.Operation.OperationData];
let decodedData = this._game._decodeOperationPluginOperation(operationCode, operationData);
return new OperationEvent(operationCode, decodedData, player, local, prio);
default:
// TODO handle error
throw ExceptionFactory.createAssertionError("EventConverter#toGameEvent");
}
}
/**
* g.Eventからplaylog.Eventに変換する。
*/
toPlaylogEvent(e: Event, preservePlayer?: boolean): pl.Event {
let targetId: number | null;
let playerId: string | null;
switch (e.type) {
case "join":
case "leave":
// akashic-engine は決して Join と Leave を生成しない
throw ExceptionFactory.createAssertionError("EventConverter#toPlaylogEvent: Invalid type: " + e.type);
case "timestamp":
let ts = e as TimestampEvent;
playerId = preservePlayer ? ts.player.id ?? null : this._playerId;
return [
pl.EventCode.Timestamp, // 0: イベントコード
ts.eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
ts.timestamp // 3: タイムスタンプ
];
case "player-info":
let playerInfo = e as PlayerInfoEvent;
playerId = preservePlayer ? playerInfo.player.id ?? null : this._playerId;
return [
pl.EventCode.PlayerInfo, // 0: イベントコード
playerInfo.eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
playerInfo.player.name, // 3: プレイヤー名
playerInfo.player.userData // 4: ユーザデータ
];
case "point-down":
let pointDown = e as PointDownEvent;
targetId = pointDown.target ? pointDown.target.id : null;
playerId = preservePlayer && pointDown.player ? pointDown.player.id ?? null : this._playerId;
return [
pl.EventCode.PointDown, // 0: イベントコード
pointDown.eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
pointDown.pointerId, // 3: ポインターID
pointDown.point.x, // 4: X座標
pointDown.point.y, // 5: Y座標
targetId, // 6?: エンティティID
!!pointDown.local // 7?: 直前のポイントムーブイベントからのY座標の差
];
case "point-move":
let pointMove = e as PointMoveEvent;
targetId = pointMove.target ? pointMove.target.id : null;
playerId = preservePlayer && pointMove.player ? pointMove.player.id ?? null : this._playerId;
return [
pl.EventCode.PointMove, // 0: イベントコード
pointMove.eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
pointMove.pointerId, // 3: ポインターID
pointMove.point.x, // 4: X座標
pointMove.point.y, // 5: Y座標
pointMove.startDelta.x, // 6: ポイントダウンイベントからのX座標の差
pointMove.startDelta.y, // 7: ポイントダウンイベントからのY座標の差
pointMove.prevDelta.x, // 8: 直前のポイントムーブイベントからのX座標の差
pointMove.prevDelta.y, // 9: 直前のポイントムーブイベントからのY座標の差
targetId, // 10?: エンティティID
!!pointMove.local // 11?: 直前のポイントムーブイベントからのY座標の差
];
case "point-up":
let pointUp = e as PointUpEvent;
targetId = pointUp.target ? pointUp.target.id : null;
playerId = preservePlayer && pointUp.player ? pointUp.player.id ?? null : this._playerId;
return [
pl.EventCode.PointUp, // 0: イベントコード
pointUp.eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
pointUp.pointerId, // 3: ポインターID
pointUp.point.x, // 4: X座標
pointUp.point.y, // 5: Y座標
pointUp.startDelta.x, // 6: ポイントダウンイベントからのX座標の差
pointUp.startDelta.y, // 7: ポイントダウンイベントからのY座標の差
pointUp.prevDelta.x, // 8: 直前のポイントムーブイベントからのX座標の差
pointUp.prevDelta.y, // 9: 直前のポイントムーブイベントからのY座標の差
targetId, // 10?: エンティティID
!!pointUp.local // 11?: 直前のポイントムーブイベントからのY座標の差
];
case "message":
let message = e as MessageEvent;
playerId = preservePlayer && message.player ? message.player.id ?? null : this._playerId;
return [
pl.EventCode.Message, // 0: イベントコード
message.eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
message.data, // 3: 汎用的なデータ
!!message.local // 4?: ローカル
];
case "operation":
let op = e as OperationEvent;
playerId = preservePlayer && op.player ? op.player.id ?? null : this._playerId;
return [
pl.EventCode.Operation, // 0: イベントコード
op.eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
op.code, // 3: 操作プラグインコード
op.data, // 4: 操作プラグインデータ
!!op.local // 5?: ローカル
];
default:
throw ExceptionFactory.createAssertionError("Unknown type: " + e.type);
}
}
makePlaylogOperationEvent(op: InternalOperationPluginOperation): pl.Event {
let playerId = this._playerId;
let eventFlags = op.priority != null ? op.priority & pl.EventFlagsMask.Priority : 0;
return [
pl.EventCode.Operation, // 0: イベントコード
eventFlags, // 1: イベントフラグ値
playerId, // 2: プレイヤーID
op._code, // 3: 操作プラグインコード
op.data, // 4: 操作プラグインデータ
!!op.local // 5: ローカル
];
}
} | the_stack |
import { DataSource } from '@angular/cdk/table';
import { compareValues, isNumber } from '@dynatrace/barista-components/core';
import { DtPagination } from '@dynatrace/barista-components/pagination';
import {
BehaviorSubject,
combineLatest,
merge,
Observable,
of,
Subject,
Subscription,
} from 'rxjs';
import { distinctUntilChanged, map, takeUntil } from 'rxjs/operators';
import { DtTableSearch } from './search';
import {
DtSimpleColumnComparatorFunction,
DtSimpleColumnDisplayAccessorFunction,
DtSimpleColumnSortAccessorFunction,
} from './simple-columns';
import { DtSort, DtSortEvent } from './sort/sort';
import { DtTableSelection } from './selection/selection';
import { DtTable } from './table';
export type DtSortAccessorFunction<T> = (data: T) => any; // tslint:disable-line:no-any
/**
* Signature type for the comparision function, which can be passed to the DtTableDataSource.
* The return value has to be < 0 if the left is logical smaller than right, 0 if they
* are equivalent, otherwise > 0.
*/
export type DtColumnComparatorFunction<T> = (left: T, right: T) => number;
const DEFAULT_PAGE_SIZE = 10;
export class DtTableDataSource<T> extends DataSource<T> {
/**
* The filtered set of data that has been matched by the filter string, or all the data if there
* is no filter. Useful for knowing the set of data the table represents.
* For example, a 'selectAll()' function would likely want to select the set of filtered data
* shown to the user rather than all the data.
*/
filteredData: T[];
/**
* Data structure to expose exportable data to the table.
*/
exporter: {
filteredData: T[];
selection: DtTableSelection<T> | null;
} = {
filteredData: [],
selection: null,
};
/** @internal DisplayAccessorMap for SimpleColumn displayAccessor functions. */
_displayAccessorMap: Map<string, DtSimpleColumnDisplayAccessorFunction<T>> =
new Map();
/**
* @internal SortAccessorMap for SimpleColumn sortAccessor functions. This sortAccessorMap
* is automatically populated by the sortAccessor functions on the dt-simple-columns.
*/
_simpleColumnSortAccessorMap: Map<
string,
DtSimpleColumnSortAccessorFunction<T>
> = new Map();
/**
* @internal
* SortAccessorMap for SimpleColumn sortAccessor functions. This sortAccessorMap
* is exposed to the outside and can be filled by the consumer.
*/
_customSortAccessorMap: Map<string, DtSortAccessorFunction<T>> = new Map();
/** Comparator map for SimpleColumn comparator functions */
private _simpleComparatorMap: Map<
string,
DtSimpleColumnComparatorFunction<T>
> = new Map();
/** Comparator map for column comparator functions */
private readonly _customComparatorMap: Map<
string,
DtColumnComparatorFunction<T>
> = new Map();
/** Stream that emits when a new data array is set on the data source. */
private readonly _data: BehaviorSubject<T[]>;
/** Stream emitting render data to the table (depends on ordered data changes). */
private readonly _renderData = new BehaviorSubject<T[]>([]);
/** Stream that emits when a new filter string is set on the data source. */
private readonly _filter = new BehaviorSubject<string>('');
/** Used to react to internal changes of the pagination that are made by the data source itself. */
private readonly _internalPageChanges = new Subject<void>();
/** Used for unsubscribing */
private readonly _destroy$ = new Subject<void>();
/**
* Subscription to the changes that should trigger an update to the table's rendered rows, such
* as filtering, sorting, pagination, or base data changes.
*/
private _renderChangesSubscription = Subscription.EMPTY;
private _searchChangeSubscription = Subscription.EMPTY;
/** Public stream emitting render data to the table */
renderData = this._renderData.asObservable();
/** Array of data that should be rendered by the table, where each object represents one row. */
get data(): T[] {
return this._data.value;
}
set data(data: T[]) {
this._data.next(data);
this._updateChangeSubscription();
}
/**
* Instance of the DtSort directive used by the table to control its sorting.
* Sort changes emitted by the DtSort will trigger an update to the tables
* rendered data.
*/
get sort(): DtSort | null {
return this._sort;
}
set sort(sort: DtSort | null) {
this._sort = sort;
this._updateChangeSubscription();
}
private _sort: DtSort | null;
/**
* Instance of the DtTableSelection directive used by the table to provide selected data.
*/
get selection(): DtTableSelection<T> | null {
return this.exporter.selection;
}
set selection(selection: DtTableSelection<T> | null) {
this.exporter.selection = selection;
}
/**
* Instance of the DtTableSearch directive used by the table to control which
* rows are displayed. Search changes emitted by the DtTableSearch will
* trigger an update to the tables rendered data.
*/
get search(): DtTableSearch | null {
return this._search;
}
set search(search: DtTableSearch | null) {
this._search = search;
this._searchChangeSubscription.unsubscribe();
if (this._search !== null) {
this._searchChangeSubscription = this._search._filterValueChanged
.pipe(
map((event) => event.value),
distinctUntilChanged(),
)
.subscribe((value) => {
this._filter.next(value);
});
} else {
this._searchChangeSubscription = Subscription.EMPTY;
}
}
private _search: DtTableSearch | null = null;
/** Filter term that should be used to filter out objects from the data array. */
get filter(): string {
return this._filter.value;
}
set filter(value: string) {
this._filter.next(value);
}
/**
* Instance of the `DtPagination` component used by the table to control what page of the data is
* displayed. Page changes emitted by the pagination will trigger an update to the
* table's rendered data.
*
* Note that the data source uses the pagination's properties to calculate which page of data
* should be displayed.
*/
get pagination(): DtPagination | null {
return this._pagination;
}
set pagination(pagination: DtPagination | null) {
this._pagination = pagination;
this._internalPageChanges.next();
this._updateChangeSubscription();
}
private _pagination: DtPagination | null = null;
/** Number of items to display on a page. By default set to 50. */
get pageSize(): number {
return this._pageSize;
}
set pageSize(pageSize: number) {
this._pageSize = pageSize;
if (!!this._pagination) {
this._pagination.pageSize = pageSize;
this._internalPageChanges.next();
}
this._updateChangeSubscription();
}
private _pageSize: number = DEFAULT_PAGE_SIZE;
/**
* Data accessor function that is used for accessing data properties for sorting through
* the default sortData function.
* This default function assumes that the sort header IDs (which defaults to the column name)
* matches the datas properties (e.g. column Xyz represents data['Xyz']).
* May be set to a custom function for different behavior.
*/
sortingDataAccessor: (
data: T,
sortHeaderId: string,
) => string | number | null = (
data: T,
sortHeaderId: string,
): string | number | null => {
let value;
if (this._customSortAccessorMap.has(sortHeaderId)) {
value = this._customSortAccessorMap.get(sortHeaderId)!(data);
} else if (this._simpleColumnSortAccessorMap.has(sortHeaderId)) {
value = this._simpleColumnSortAccessorMap.get(sortHeaderId)!(
data,
sortHeaderId,
);
} else if (this._displayAccessorMap.has(sortHeaderId)) {
value = this._displayAccessorMap.get(sortHeaderId)!(data, sortHeaderId);
} else {
// tslint:disable-next-line: no-any
value = (data as { [key: string]: any })[sortHeaderId];
}
if (isNumber(value)) {
const numberValue = Number(value);
// Numbers beyond `MAX_SAFE_INTEGER` can't be compared reliably so we
// leave them as strings. For more info: https://goo.gl/y5vbSg
return numberValue < Number.MAX_SAFE_INTEGER ? numberValue : value;
}
if (value === undefined) {
return null;
}
return value;
};
/**
* Gets a sorted copy of the data array based on the state of the DtSort. Called
* after changes are made to the filtered data or when sort changes are emitted from DtSort.
* By default, the function retrieves the active sort and its direction and compares data
* by retrieving data using the sortingDataAccessor. May be overridden for a custom implementation
* of data ordering.
*/
sortData: (data: T[], sort: DtSort) => T[] = (
data: T[],
sort: DtSort,
): T[] => {
const active = sort.active;
const direction = sort.direction;
if (!active || direction === '') {
return data;
}
const comparator = this._getComparatorFunction(active);
return data.sort(
(a, b) => comparator(a, b) * (direction === 'asc' ? 1 : -1),
);
};
/**
* Checks if a data object matches the data source's filter string. By default, each data object
* is converted to a string of its properties and returns true if the filter has
* at least one occurrence in that string. By default, the filter string has its whitespace
* trimmed and the match is case-insensitive. May be overridden for a custom implementation of
* filter matching.
* @param data Data object used to check against the filter.
* @param filter Filter string that has been set on the data source.
* @returns Whether the filter matches against the data
*/
filterPredicate: (data: T, filter: string) => boolean = (
data: T,
filter: string,
): boolean => {
// Transform the data into a lowercase string of all property values.
const dataStr = Object.keys(data)
.reduce(
(currentTerm: string, key: string) =>
// Use an obscure Unicode character to delimit the words in the concatenated string.
// This avoids matches where the values of two columns combined will match the user's query
// (e.g. `Flute` and `Stop` will match `Test`). The character is intended to be something
// that has a very low chance of being typed in by somebody in a text field. This one in
// particular is "White up-pointing triangle with dot" from
// https://en.wikipedia.org/wiki/List_of_Unicode_characters
// tslint:disable-next-line
`${currentTerm}${(data as { [key: string]: any })[key]}◬`,
'',
)
.toLowerCase();
// Transform the filter by converting it to lowercase and removing whitespace.
const transformedFilter = filter.trim().toLowerCase();
return dataStr.indexOf(transformedFilter) !== -1;
};
constructor(initialData: T[] = []) {
super();
this._data = new BehaviorSubject<T[]>(initialData);
this._updateChangeSubscription();
}
/**
* Subscribe to changes that should trigger an update to the table's rendered rows. When the
* changes occur, process the current state of the sort with the provided base data, and send
* it to the table for rendering.
*/
private _updateChangeSubscription(): void {
const sortChange: Observable<DtSortEvent | null | boolean> = this._sort
? merge(this._sort.sortChange, this._sort._initialized)
: of(null);
const pageChange: Observable<boolean | number | null | void> = this
._pagination
? merge(
this._pagination._initialized,
this._internalPageChanges,
this._pagination.changed,
)
: of(null);
const dataStream = this._data;
// Watch for base data or filter changes to provide a filtered set of data.
const filteredData = combineLatest([dataStream, this._filter]).pipe(
map(([data]) => this._filterData(data)),
);
// Watch for filtered data or sort changes to provide a sorted set of data.
const sortedData = combineLatest([filteredData, sortChange]).pipe(
map(([data]) => this._sortData(data)),
);
// Watch for ordered data or page changes to provide a paged set of data.
const paginatedData = combineLatest([sortedData, pageChange]).pipe(
map(([data]) => this._pageData(data)),
);
this._renderChangesSubscription.unsubscribe();
this._renderChangesSubscription = paginatedData.subscribe((data) => {
this._renderData.next(data);
});
}
/**
* @internal
* Returns a sorted copy of the data if DtSort has a sort applied, otherwise just returns the
* data array as provided. Uses the default data accessor for data lookup, unless a
* sortDataAccessor function is defined.
*/
_sortData(data: T[]): T[] {
// If there is no active sort or direction, return the data without trying to sort.
if (!this.sort) {
return data;
}
return this.sortData(data.slice(), this.sort);
}
/**
* Returns a filtered data array where each filter object contains the filter string within
* the result of the filterTermAccessor function. If no filter is set, returns the data array
* as provided.
*/
private _filterData(data: T[]): T[] {
// If there is a filter string, filter out data that does not contain it.
// May be overridden for customization.
this.filteredData = !this.filter
? data
: data.filter((obj: T) => this.filterPredicate(obj, this.filter));
if (
this._pagination &&
this._pagination.length !== this.filteredData.length
) {
this._updatePagination(this.filteredData.length);
}
return this.filteredData;
}
/**
* Returns a paged splice of the provided data array according to the provided pagination's page
* index and length. If there is no pagination provided, return the data array as provided.
*/
private _pageData(data: T[]): T[] {
if (!this._pagination) {
return data;
}
// -1 in case that the currentPage starts with 1
const pageSize = this._pagination.pageSize;
const startIndex = (this._pagination.currentPage - 1) * pageSize;
return data.slice().splice(startIndex, pageSize);
}
/**
* Updates the pagination to reflect the length of the filtered data, and makes sure that the page
* index does not exceed the pagination's last page. Values are changed in a resolved promise to
* guard against making property changes within a round of change detection.
*/
private _updatePagination(filteredDataLength: number): void {
Promise.resolve().then(() => {
if (this._pagination) {
const pagination = this._pagination;
pagination.length = filteredDataLength;
// If the page index is set beyond the page, reduce it to the last page.
if (pagination.currentPage > 0) {
// Set the last page index, if this would result to 0, fall back to the default
// page 1.
const lastPageIndex =
Math.ceil(pagination.length / pagination.pageSize) || 1;
const newPageIndex = Math.min(pagination.currentPage, lastPageIndex);
if (newPageIndex !== pagination.currentPage) {
pagination.currentPage = newPageIndex;
// Since the pagination only emits after user-generated changes,
// we need our own stream so we know to should re-render the data.
this._internalPageChanges.next();
}
}
}
});
}
/**
* Used by the DtTable. Called when it connects to the data source.
*/
connect(_table: DtTable<T>): Observable<T[]> {
_table._dataAccessors
.pipe(takeUntil(this._destroy$))
.subscribe(({ comparatorMap, displayAccessorMap, sortAccessorMap }) => {
this._displayAccessorMap = displayAccessorMap;
this._simpleColumnSortAccessorMap = sortAccessorMap;
this._simpleComparatorMap = comparatorMap;
this._updateChangeSubscription();
});
_table._filteredData = this.filteredData;
_table._exporter = this.exporter;
return this._renderData;
}
/**
* Used by the DtTable. Called when it is destroyed. No-op.
*/
disconnect(): void {
this._renderChangesSubscription.unsubscribe();
this._searchChangeSubscription.unsubscribe();
this._destroy$.next();
this._destroy$.complete();
}
/**
* Lets the user define a sortAccessor function for a named column,
* that is being used for sorting when the DataSource is used in combination
* with simple and non-simple columns.
*/
addSortAccessorFunction(
columnName: string,
fn: DtSortAccessorFunction<T>,
): void {
this._customSortAccessorMap.set(columnName, fn);
this._data.next(this._data.value);
}
/**
* Lets the user remove a sortAccessor function for a named column,
* that is being used for sorting when the DataSource is used in combination
* with simple and non-simple columns.
*/
removeSortAccessorFunction(columnName: string): void {
this._customSortAccessorMap.delete(columnName);
}
/**
* Lets the user define a comparator function for a named column,
* that is being used for sorting when the DataSource is used in combination
* with simple and non-simple columns.
* A comparator defined with this function is used instead of a comparator
* defined in a simple column.
*/
addComparatorFunction(
columnName: string,
fn: DtColumnComparatorFunction<T>,
): void {
this._customComparatorMap.set(columnName, fn);
this._data.next(this._data.value);
}
/**
* Lets the user remove a comparator function for a named column.
*/
removeComparatorFunction(columnName: string): void {
this._customComparatorMap.delete(columnName);
}
/**
* Gets a comparator function which calls the responsible comparator function.
* The comparator is first searched in the custom comparators, then in the simple
* comparators, and if this does not exists, a fallback comparator is used.
*/
private _getComparatorFunction(columnName: string): (a: T, b: T) => number {
const customComparator = this._customComparatorMap.get(columnName);
if (customComparator) {
return customComparator;
}
const simpleComparator = this._simpleComparatorMap.get(columnName);
if (simpleComparator) {
return (a, b) => simpleComparator(a, b, columnName);
}
return (a, b) => this._fallbackColumnComparator(a, b, columnName);
}
/**
* Default comparator so compare two rows.
* If is used if no comparator is set in the SimpleColumns or custom defined one.
*/
private _fallbackColumnComparator(left: T, right: T, active: string): number {
const valueA = this.sortingDataAccessor(left, active);
const valueB = this.sortingDataAccessor(right, active);
return compareValues(valueA, valueB, 'asc');
}
} | the_stack |
import {
Component,
OnInit,
ViewChild,
Input,
Output,
EventEmitter,
Inject,
HostListener,
AfterViewInit,
AfterViewChecked,
ApplicationRef
} from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { HealthStatusService } from '../../../core/services';
import { SortUtils } from '../../../core/util';
import { EnvironmentsDataService } from '../management-data.service';
import { EnvironmentModel, ManagementConfigModel } from '../management.model';
import {ProgressBarService} from '../../../core/services/progress-bar.service';
import {DetailDialogComponent} from '../../../resources/exploratory/detail-dialog';
import {BehaviorSubject, Subject, timer} from 'rxjs';
import { ChangeDetectorRef } from '@angular/core';
import {CompareUtils} from '../../../core/util/compareUtils';
export interface ManageAction {
action: string;
environment: string;
resource: string;
}
@Component({
selector: 'management-grid',
templateUrl: 'management-grid.component.html',
styleUrls: [
'./management-grid.component.scss',
'../../../resources/resources-grid/resources-grid.component.scss',
'../../../resources/computational/computational-resources-list/computational-resources-list.component.scss'
]
})
export class ManagementGridComponent implements OnInit, AfterViewInit, AfterViewChecked {
allEnvironmentData: Array<any>;
allFilteredEnvironmentData: Array<any>;
loading: boolean = false;
filterConfiguration: ManagementConfigModel = new ManagementConfigModel([], '', [], [], [], [], []);
filterForm: ManagementConfigModel = new ManagementConfigModel([], '', [], [], [], [], []);
filtering: boolean = false;
collapsedFilterRow: boolean = false;
isMaxRight: Subject<boolean> = new BehaviorSubject(false);
private tableWrapperWidth: number;
tableEl = {};
@Input() environmentsHealthStatuses: Array<any>;
@Input() resources: Array<any>;
@Input() isAdmin: boolean;
@Input() currentUser: string = '';
@Output() refreshGrid: EventEmitter<{}> = new EventEmitter();
@Output() actionToggle: EventEmitter<ManageAction> = new EventEmitter();
@Output() emitSelectedList: EventEmitter<ManageAction> = new EventEmitter();
@ViewChild('tableWrapper') tableWrapper;
@ViewChild('wrapper') wrapper;
@ViewChild('pageWrapper') pageWrapper;
@ViewChild('table') table;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.checkMaxRight();
}
@HostListener('scroll', ['$event'])
scrollTable($event: Event) {
this.checkMaxRight();
}
displayedColumns: string[] = [ 'checkbox', 'user', 'type', 'project', 'endpoint', 'shape', 'status', 'resources', 'actions'];
displayedFilterColumns: string[] = ['checkbox-filter', 'user-filter', 'type-filter', 'project-filter', 'endpoint-filter', 'shape-filter', 'status-filter', 'resource-filter', 'actions-filter'];
public selected;
public allActiveNotebooks: any;
private cashedFilterForm: ManagementConfigModel = new ManagementConfigModel([], '', [], [], [], [], []);
public isFilterSelected: boolean;
public isFilterChanged: boolean;
constructor(
private healthStatusService: HealthStatusService,
private environmentsDataService: EnvironmentsDataService,
public toastr: ToastrService,
public dialog: MatDialog,
private progressBarService: ProgressBarService,
private cdRef: ChangeDetectorRef,
private applicationRef: ApplicationRef,
) { }
ngOnInit() {
this.getEnvironmentData();
}
ngAfterViewInit() {
this.progressBarService.startProgressBar();
this.tableEl = this.table._elementRef.nativeElement;
this.checkMaxRight();
}
ngAfterViewChecked() {
if (this.tableWrapperWidth !== this.wrapper.nativeElement.offsetWidth) {
this.tableWrapperWidth = this.wrapper.nativeElement.offsetWidth;
timer(100).subscribe(_ => {
this.applicationRef.tick();
});
}
this.cdRef.detectChanges();
}
getEnvironmentData() {
this.progressBarService.startProgressBar();
this.environmentsDataService._data.subscribe(data => {
if (data) {
this.allEnvironmentData = EnvironmentModel.loadEnvironments(data);
this.getDefaultFilterConfiguration(data);
this.applyFilter(this.cashedFilterForm || this.filterForm);
}
this.progressBarService.stopProgressBar();
}, () => {
this.progressBarService.stopProgressBar();
});
}
buildGrid(): void {
this.refreshGrid.emit();
this.filtering = false;
}
public onUpdate($event): void {
this.filterForm[$event.type] = $event.model;
this.checkFilters();
}
private checkFilters() {
this.isFilterChanged = CompareUtils.compareFilters(this.filterForm, this.cashedFilterForm);
this.isFilterSelected = Object.keys(this.filterForm).some(v => this.filterForm[v].length > 0);
}
public toggleFilterRow(): void {
this.collapsedFilterRow = !this.collapsedFilterRow;
}
public resetFilterConfigurations(): void {
this.filterForm.defaultConfigurations();
this.applyFilter(this.filterForm);
this.buildGrid();
}
public applyFilter(config) {
if (config) {
this.filterForm = JSON.parse(JSON.stringify(config));
Object.setPrototypeOf(this.filterForm, Object.getPrototypeOf(config));
this.cashedFilterForm = JSON.parse(JSON.stringify(config));
Object.setPrototypeOf(this.cashedFilterForm, Object.getPrototypeOf(config));
}
let filteredData = this.getEnvironmentDataCopy();
const containsStatus = (list, selectedItems) => {
if (list) {
return list.filter((item: any) => { if (selectedItems.indexOf(item.status) !== -1) return item; });
}
};
if (filteredData.length) this.filtering = true;
if (config) {
filteredData = filteredData.filter(item => {
const isUser = config.users.length > 0 ? (config.users.indexOf(item.user) !== -1) : true;
const isTypeName = item.name ? item.name.toLowerCase()
.indexOf(config.type.toLowerCase()) !== -1 : item.type.toLowerCase().indexOf(config.type.toLowerCase()) !== -1;
const isStatus = config.statuses.length > 0 ? (config.statuses.indexOf(item.status) !== -1) : (config.type !== 'active');
const isShape = config.shapes.length > 0 ? (config.shapes.indexOf(item.shape) !== -1) : true;
const isProject = config.projects.length > 0 ? (config.projects.indexOf(item.project) !== -1) : true;
const isEndpoint = config.endpoints.length > 0 ? (config.endpoints.indexOf(item.endpoint) !== -1) : true;
const modifiedResources = containsStatus(item.resources, config.resources);
let isResources = config.resources.length > 0 ? (modifiedResources && modifiedResources.length > 0) : true;
if (config.resources.length > 0 && modifiedResources && modifiedResources.length > 0) { item.resources = modifiedResources; }
if (config.resources && config.resources.length === 0 && config.type === 'active' ||
modifiedResources && modifiedResources.length >= 0 && config.resources.length > 0 && config.type === 'active') {
item.resources = modifiedResources;
isResources = true;
}
return isUser && isTypeName && isStatus && isShape && isProject && isResources && isEndpoint;
});
}
this.allFilteredEnvironmentData = filteredData;
this.allActiveNotebooks = this.allFilteredEnvironmentData
.filter(v => v.name &&
(v.status === 'running' || v.status === 'stopped') &&
!this.clustersInProgress(v.resources || []));
this.checkFilters();
}
getEnvironmentDataCopy() {
return this.allEnvironmentData;
}
toggleResourceAction(environment: any, action: string, resource?): void {
this.actionToggle.emit({ environment, action, resource });
}
isResourcesInProgress(notebook) {
if (notebook) {
if (notebook.name === 'edge node') {
return this.allEnvironmentData
.filter(env => env.user === notebook.user)
.some(el => this.inProgress([el]) || this.inProgress(el.resources));
} else if (notebook.resources && notebook.resources.length) {
return this.inProgress(notebook.resources);
}
}
return false;
}
public inProgress(resources) {
return resources.some(resource => (
resource.status !== 'failed'
&& resource.status !== 'terminated'
&& resource.status !== 'running'
&& resource.status !== 'stopped'));
}
private getDefaultFilterConfiguration(data): void {
const users = [], projects = [], shapes = [], statuses = [], resources = [], endpoints = [];
data && data.forEach((item: any) => {
if (item.user && users.indexOf(item.user) === -1) users.push(item.user);
if (item.endpoint && endpoints.indexOf(item.endpoint) === -1) endpoints.push(item.endpoint);
if (item.status && statuses.indexOf(item.status.toLowerCase()) === -1) statuses.push(item.status.toLowerCase());
if (item.project && projects.indexOf(item.project) === -1) projects.push(item.project);
if (item.shape && shapes.indexOf(item.shape) === -1) shapes.push(item.shape);
if (item.computational_resources) {
item.computational_resources.map((resource: any) => {
if (resources.indexOf(resource.status) === -1) resources.push(resource.status);
resources.sort(SortUtils.statusSort);
});
}
});
this.filterConfiguration = new ManagementConfigModel(users, '', projects, shapes, statuses, resources, endpoints);
}
public openNotebookDetails(data) {
if (!data.exploratory_urls || !data.exploratory_urls.length) {
return;
}
this.dialog.open(DetailDialogComponent, { data:
{notebook: data, buckets: [], type: 'environment'},
panelClass: 'modal-lg'
})
.afterClosed().subscribe(() => {});
}
public toggleActionForAll(element) {
element.isSelected = !element.isSelected;
this.selected = this.allFilteredEnvironmentData.filter(item => !!item.isSelected);
this.emitSelectedList.emit(this.selected);
}
public toggleSelectionAll() {
if (this.selected && this.selected.length === this.allActiveNotebooks.length) {
this.allActiveNotebooks.forEach(notebook => notebook.isSelected = false);
} else {
this.allActiveNotebooks.forEach(notebook => notebook.isSelected = true);
}
this.selected = this.allFilteredEnvironmentData.filter(item => !!item.isSelected);
this.emitSelectedList.emit(this.selected);
}
public clustersInProgress(resources: any) {
const statuses = ['terminating', 'stopping', 'starting', 'creating', 'configuring', 'reconfiguring'];
return resources.filter(resource => statuses.includes(resource.status)).length;
}
public onFilterNameUpdate(targetElement: any) {
this.filterForm.type = targetElement;
this.checkFilters();
}
public sctollTo(direction: string) {
if (direction === 'left') {
this.wrapper.nativeElement.scrollLeft = 0;
} else {
this.wrapper.nativeElement.scrollLeft = this.wrapper.nativeElement.offsetWidth;
}
}
public checkMaxRight() {
let arg;
if (this.wrapper && this.table) {
arg = this.wrapper.nativeElement.offsetWidth +
this.wrapper.nativeElement.scrollLeft + 2 <= this.table._elementRef.nativeElement.offsetWidth;
}
return this.isMaxRight.next(arg);
}
}
@Component({
selector: 'confirm-dialog',
template: `
<div class="dialog-header">
<h4 class="modal-title"><span class="capitalize">{{ data.action }}</span> resource</h4>
<button type="button" class="close" (click)="dialogRef.close()">×</button>
</div>
<div mat-dialog-content class="content">
<div *ngIf="data.type === 'cluster'">
<p>Resource <span class="strong"> {{ data.resource_name }}</span> of user <span class="strong"> {{ data.user }} </span> will be
<span *ngIf="data.action === 'terminate'"> decommissioned.</span>
<span *ngIf="data.action === 'stop'">stopped.</span>
</p>
</div>
<div class="resource-list" *ngIf="data.type === 'notebook'">
<div class="resource-list-header">
<div class="resource-name">Notebook</div>
<div class="clusters-list">
<div class="clusters-list-item">
<div class="cluster"><span *ngIf="isClusterLength">Compute</span></div>
<div class="status">Further status</div>
</div>
</div>
</div>
<div class="scrolling-content resource-heigth">
<div class="resource-list-row sans node" *ngFor="let notebook of notebooks">
<div class="resource-name ellipsis">
{{notebook.name}}
</div>
<div class="clusters-list">
<div class="clusters-list-item">
<div class="cluster"></div>
<div class="status"
[ngClass]="{
'stopped': data.action==='stop', 'terminated': data.action === 'terminate'
}"
>
{{data.action === 'stop' ? 'Stopped' : 'Terminated'}}
</div>
</div>
<div class="clusters-list-item" *ngFor="let cluster of notebook?.resources">
<div class="cluster">{{cluster.computational_name}}</div>
<div class="status" [ngClass]="{
'stopped': (data.action==='stop' && cluster.image==='docker.datalab-dataengine'), 'terminated': data.action === 'terminate' || (data.action==='stop' && cluster.image!=='docker.datalab-dataengine')
}">{{data.action === 'stop' && cluster.image === "docker.datalab-dataengine" ? 'Stopped' : 'Terminated'}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="text-center ">
<p class="strong">Do you want to proceed?</p>
</div>
<div class="text-center m-top-20">
<button type="button" class="butt" mat-raised-button (click)="dialogRef.close()">No</button>
<button type="button" class="butt butt-success" mat-raised-button (click)="dialogRef.close(true)">Yes</button>
</div>
`,
styles: [
`
.content { color: #718ba6; padding: 20px 50px; font-size: 14px; font-weight: 400; margin: 0; }
.info { color: #35afd5; }
.info .confirm-dialog { color: #607D8B; }
header { display: flex; justify-content: space-between; color: #607D8B; }
header h4 i { vertical-align: bottom; }
header a i { font-size: 20px; }
header a:hover i { color: #35afd5; cursor: pointer; }
.plur { font-style: normal; }
.scrolling-content{overflow-y: auto; max-height: 200px; }
.cluster { width: 50%; text-align: left;}
.status { width: 50%;text-align: left;}
.label { font-size: 15px; font-weight: 500; font-family: "Open Sans",sans-serif;}
.node { font-weight: 300;}
.resource-name { width: 40%;text-align: left; padding: 10px 0;line-height: 26px;}
.clusters-list { width: 60%;text-align: left; padding: 10px 0;line-height: 26px;}
.clusters-list-item { width: 100%;text-align: left;display: flex}
.resource-list{max-width: 100%; margin: 0 auto;margin-top: 20px; }
.resource-list-header{display: flex; font-weight: 600; font-size: 16px;height: 48px; border-top: 1px solid #edf1f5; border-bottom: 1px solid #edf1f5; padding: 0 20px;}
.resource-list-row{display: flex; border-bottom: 1px solid #edf1f5;padding: 0 20px;}
.confirm-resource-terminating{text-align: left; padding: 10px 20px;}
.confirm-message{color: #ef5c4b;font-size: 13px;min-height: 18px; text-align: center; padding-top: 20px}
.checkbox{margin-right: 5px;vertical-align: middle; margin-bottom: 3px;}
label{cursor: pointer}
.bottom-message{padding-top: 15px;}
.table-header{padding-bottom: 10px;}`
]
})
export class ReconfirmationDialogComponent {
public notebooks;
public isClusterLength;
constructor(
public dialogRef: MatDialogRef<ReconfirmationDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
if (data.notebooks && data.notebooks.length) {
this.notebooks = JSON.parse(JSON.stringify(data.notebooks));
this.notebooks = this.notebooks.map(notebook => {
notebook.resources = notebook.resources.filter(res => res.status !== 'failed' &&
res.status !== 'terminated' && res.status.slice(0, 4) !== data.action);
if (notebook.resources.length) {
this.isClusterLength = true;
}
return notebook;
});
}
}
} | the_stack |
import assert from "assert";
import FilecoinProvider from "../../../src/provider";
import getProvider from "../../helpers/getProvider";
import getIpfsClient from "../../helpers/getIpfsClient";
import { CID } from "../../../src/things/cid";
import { StartDealParams } from "../../../src/things/start-deal-params";
import { RootCID } from "../../../src/things/root-cid";
import { StorageMarketDataRef } from "../../../src/things/storage-market-data-ref";
import { DealInfo, SerializedDealInfo } from "../../../src/things/deal-info";
import { SerializedRetrievalOrder } from "../../../src/things/retrieval-order";
import BN from "bn.js";
import { SerializedQueryOffer } from "../../../src/things/query-offer";
import { SerializedFileRef } from "../../../src/things/file-ref";
import tmp from "tmp-promise";
import path from "path";
import fs from "fs";
import { Address } from "../../../src/things/address";
import { StorageDealStatus } from "../../../src/types/storage-deal-status";
const LotusRPC = require("@filecoin-shipyard/lotus-client-rpc").LotusRPC;
type LotusClient = any;
describe("api", () => {
describe("filecoin", () => {
let provider: FilecoinProvider;
let client: LotusClient;
const data = "some data";
const expectedSize = 17;
before(async () => {
tmp.setGracefulCleanup();
provider = await getProvider();
client = new LotusRPC(provider, { schema: FilecoinProvider.Schema });
});
after(async () => {
if (provider) {
await provider.stop();
}
});
describe("Filecoin.ClientGetDealStatus", () => {
it("retrieves a string for a status code", async () => {
let status = await client.clientGetDealStatus(5);
assert.strictEqual(status, "StorageDealSealing");
try {
status = await client.clientGetDealStatus(500);
assert.fail(
"Successfully retrieved status string for invalid status code"
);
} catch (e) {
if (e.code === "ERR_ASSERTION") {
throw e;
}
assert.strictEqual(e.message, "no such deal state 500");
}
});
});
describe("Filecoin.ClientStartDeal, Filecoin.ClientListDeals, Ganache.GetDealById, Filecoin.ClientGetDealInfo, and Filecoin.ClientGetDealUpdates", () => {
let ipfs: any;
let currentDeal: DealInfo = new DealInfo({
dealId: -1
});
const dealStatuses: StorageDealStatus[] = [];
const dealDuration = 5;
before(async () => {
ipfs = getIpfsClient();
});
it("should start listening for deal updates", async () => {
await client.clientGetDealUpdates(update => {
const deal = update.data[1];
currentDeal = new DealInfo(deal);
dealStatuses.push(currentDeal.state);
});
});
it("should accept a new deal", async () => {
const miners = await client.stateListMiners();
const accounts = await provider.blockchain.accountManager.getControllableAccounts();
const address = accounts[0].address;
const beginningBalance = await client.walletBalance(address.value);
const result = await ipfs.add({
content: data
});
const cid = result.path;
const proposal = new StartDealParams({
data: new StorageMarketDataRef({
transferType: "graphsync",
root: new RootCID({
"/": cid
}),
pieceSize: 0
}),
wallet: address,
miner: miners[0],
epochPrice: 2500n,
minBlocksDuration: dealDuration
});
const proposalCid = await client.clientStartDeal(proposal.serialize());
assert.ok(proposalCid["/"]);
assert(CID.isValid(proposalCid["/"]));
// Test subscription
assert.strictEqual(currentDeal.dealId, 1);
assert.strictEqual(currentDeal.state, StorageDealStatus.Active);
assert.deepStrictEqual(dealStatuses, [
StorageDealStatus.Validating,
StorageDealStatus.Staged,
StorageDealStatus.ReserveProviderFunds,
StorageDealStatus.ReserveClientFunds,
StorageDealStatus.FundsReserved,
StorageDealStatus.ProviderFunding,
StorageDealStatus.ClientFunding,
StorageDealStatus.Publish,
StorageDealStatus.Publishing,
StorageDealStatus.Transferring,
StorageDealStatus.Sealing,
StorageDealStatus.Active
]);
const deals = await client.clientListDeals();
assert.strictEqual(deals.length, 1);
const deal: SerializedDealInfo = deals[0];
assert.strictEqual(deal.ProposalCid["/"], proposalCid["/"]);
assert.strictEqual(deal.Size, expectedSize);
const endingBalance = await client.walletBalance(address.value);
assert(new BN(endingBalance).lt(new BN(beginningBalance)));
});
it("retrieves deal using ID", async () => {
const deals = await client.clientListDeals();
assert.strictEqual(deals.length, 1);
const deal = await provider.send({
jsonrpc: "2.0",
id: "0",
method: "Ganache.GetDealById",
params: [deals[0].DealID]
});
assert.deepStrictEqual(deal, deals[0]);
});
it("fails to retrieve invalid deal using ID", async () => {
try {
await provider.send({
jsonrpc: "2.0",
id: "0",
method: "Ganache.GetDealById",
params: [1337]
});
assert.fail("Successfully retrieved a deal for an invalid ID");
} catch (e) {
if (e.code === "ERR_ASSERTION") {
throw e;
}
assert(
e.message.includes("Could not find a deal for the provided ID")
);
}
});
it("retrieves deal using CID", async () => {
const deals = await client.clientListDeals();
assert.strictEqual(deals.length, 1);
const deal = await client.clientGetDealInfo(deals[0].ProposalCid);
assert.deepStrictEqual(deal, deals[0]);
});
it("fails to retrieve invalid deal using CID", async () => {
try {
const invalidCid =
"bafyreifi6tnqdabvaid7o4qezjpcavkwtibctpfzuarr4erfxjqds52bba";
await client.clientGetDealInfo({ "/": invalidCid });
assert.fail("Successfully retrieved a deal for an invalid CID");
} catch (e) {
if (e.code === "ERR_ASSERTION") {
throw e;
}
assert(
e.message.includes("Could not find a deal for the provided CID")
);
}
});
it("expires a deal at the given duration", async () => {
let deals = await client.clientListDeals();
assert.strictEqual(deals.length, 1);
let deal: SerializedDealInfo = deals[0];
assert.strictEqual(deal.State, StorageDealStatus.Active);
const priorHead = await client.chainHead();
let currentHead = await client.chainHead();
while (
deal.State === StorageDealStatus.Active &&
currentHead.Height - priorHead.Height <= dealDuration
) {
await provider.send({
jsonrpc: "2.0",
id: "0",
method: "Ganache.MineTipset"
});
deal = (await client.clientListDeals())[0];
currentHead = await client.chainHead();
}
assert.strictEqual(deal.State, StorageDealStatus.Expired);
assert.strictEqual(
currentHead.Height,
priorHead.Height + dealDuration + 1
); // the duration is inclusive, thus the +1
});
});
describe("Filecoin.ClientFindData, Filecoin.ClientRetrieve, and Filecoin.ClientHasLocal", () => {
let ipfs: any;
let offer: SerializedQueryOffer;
let address: string;
let beginningBalance: string;
before(async () => {
ipfs = getIpfsClient();
address = await client.walletDefaultAddress();
beginningBalance = await client.walletBalance(address);
});
it("should provide a remote offer", async () => {
const expectedMinPrice = `${expectedSize * 2}`;
const result = await ipfs.add({
content: data
});
const offers = await client.clientFindData({ "/": result.path });
assert.strictEqual(offers.length, 1);
offer = offers[0];
assert.ok(offer);
assert.strictEqual(offer.Root["/"], result.path);
assert.strictEqual(offer.Size, expectedSize);
assert.strictEqual(offer.MinPrice, expectedMinPrice);
const hasLocal = await client.clientHasLocal({ "/": result.path });
assert(hasLocal);
});
it("should retrieve without error, and subtract balance", async () => {
const order: SerializedRetrievalOrder = {
Root: offer.Root,
Piece: offer.Piece,
Size: offer.Size,
Total: offer.MinPrice,
UnsealPrice: offer.UnsealPrice,
PaymentInterval: offer.PaymentInterval,
PaymentIntervalIncrease: offer.PaymentIntervalIncrease,
Client: address,
Miner: offer.Miner,
MinerPeer: offer.MinerPeer
};
const tmpObj = await tmp.dir();
const file = path.join(tmpObj.path, "content");
const fileRef: SerializedFileRef = {
Path: file,
IsCAR: false
};
await client.clientRetrieve(order, fileRef);
const content = await fs.promises.readFile(file, { encoding: "utf-8" });
assert.strictEqual(content, data);
// No error? Great, let's make sure it subtracted the retrieval cost.
const endingBalance = await client.walletBalance(address);
assert(new BN(endingBalance).lt(new BN(beginningBalance)));
});
it("errors if we try to retrieve a file our IPFS server doesn't know about", async () => {
const cidIMadeUp = "QmY7Yh4UquoXdL9Fo2XbhXkhBvFoLwmQUfa92pxnxjQuPU";
const madeUpOrder: SerializedRetrievalOrder = {
Root: {
"/": cidIMadeUp
},
Piece: {
"/": cidIMadeUp
},
Size: 1234,
Total: "2468",
UnsealPrice: "2468",
PaymentInterval: 1048576,
PaymentIntervalIncrease: 1048576,
Client: address,
Miner: Address.fromId(0, false, true).value,
MinerPeer: {
Address: Address.fromId(0, false, true).value,
ID: "0",
PieceCID: {
"/": "6vuxqgevbl6irx7tymbj7o4t8bz1s5vy88zmum7flxywy1qugjfd"
}
}
};
const tmpObj = await tmp.dir();
const file = path.join(tmpObj.path, "content");
const fileRef: SerializedFileRef = {
Path: file,
IsCAR: false
};
let error: Error | undefined;
try {
await client.clientRetrieve(madeUpOrder, fileRef);
} catch (e) {
error = e;
}
assert.notStrictEqual(
typeof error,
"undefined",
"Expected ClientRetrieve to throw an error!"
);
assert(error!.message.indexOf("Object not found") >= 0);
const hasLocal = await client.clientHasLocal({ "/": cidIMadeUp });
assert(!hasLocal);
});
});
});
}); | the_stack |
import { TokenReader, Token, characterIsNumber, ITokenizationSettings, createCombineMap } from "../helpers";
import { ArgumentList } from "./components/constructs/function";
import { ForIteratorExpression, ForStatementExpression } from "./components/statements/for";
import { StatementTypes } from "./components/statements/statement";
import { TypeSignature } from "./components/types/type-signature";
import { ValueTypes } from "./components/value/value";
export type astTypes = StatementTypes
| ValueTypes
| ArgumentList
| ForIteratorExpression
| ForStatementExpression
| TypeSignature;
export enum JSToken {
Identifier, StringLiteral, NumberLiteral, RegexLiteral, TemplateLiteralString,
TemplateLiteralStart, TemplateLiteralEnd, SingleQuote, DoubleQuote, HashBang,
Backslash,
Comma, SemiColon, Colon, Dot, At,
Const, Var, Let,
New, Spread, Assign, ArrowFunction,
OpenBracket, CloseBracket, OpenCurly, CloseCurly, OpenSquare, CloseSquare, OpenAngle, CloseAngle,
If, Else, For, While, Do, Switch,
Case, Yield, DelegatedYield, Return, Continue, Break,
Class, Function,
Enum, Interface, Type,
Import, Export, Default, From,
In, Of,
TypeOf, InstanceOf, Void, Delete,
This, Super,
Try, Catch, Finally, Throw,
Async, Await,
Static, Abstract,
Get, Set,
Extends, Implements,
MultilineComment, Comment,
True, False,
Plus, Minus, Multiply, Divide,
QuestionMark, Percent, Exponent, Remainder,
PlusAssign, SubtractAssign, MultiplyAssign, DivideAssign, ExponentAssign, RemainderAssign,
Increment, Decrement,
BitwiseShiftLeft, BitwiseShiftRight, UnaryBitwiseShiftRight,
BitwiseNot, BitwiseOr, BitwiseXor, BitwiseAnd,
LogicalOr, LogicalAnd, LogicalNot,
BitwiseOrAssign, BitwiseAndAssign, BitwiseXorAssign,
LeftShift, RightShift,
LeftShiftAssign, RightShiftAssign,
Equal, NotEqual, StrictEqual, StrictNotEqual,
GreaterThanEqual, LessThanEqual,
Private, Public, Protected,
Null, Undefined,
OptionalChain, NullishCoalescing, OptionalMember,
HashTag,
As,
EOF,
}
export const commentTokens = [JSToken.Comment, JSToken.MultilineComment];
// All symbols in Javascript. If encountered during tokenization it will cut accumulation
const symbols: Array<[string, JSToken]> = [
["{", JSToken.OpenCurly],
["}", JSToken.CloseCurly],
["[", JSToken.OpenSquare],
["]", JSToken.CloseSquare],
["<", JSToken.OpenAngle],
[">", JSToken.CloseAngle],
["(", JSToken.OpenBracket],
[")", JSToken.CloseBracket],
[":", JSToken.Colon],
[",", JSToken.Comma],
[".", JSToken.Dot],
["@", JSToken.At],
[";", JSToken.SemiColon],
["+", JSToken.Plus],
["-", JSToken.Minus],
["*", JSToken.Multiply],
["&", JSToken.BitwiseAnd],
["^", JSToken.BitwiseXor],
["=", JSToken.Assign],
["'", JSToken.SingleQuote],
["\"", JSToken.DoubleQuote],
["|", JSToken.BitwiseOr],
["?", JSToken.QuestionMark],
["#", JSToken.HashTag],
["%", JSToken.Percent],
["!", JSToken.LogicalNot],
["~", JSToken.BitwiseNot],
["`", JSToken.TemplateLiteralStart],
["/", JSToken.Divide],
["\\", JSToken.Backslash],
];
// Maps symbols to a JSToken
const symbolsMap: Map<string, JSToken> = new Map(symbols);
const keywords: Array<[string, JSToken]> = [
["const", JSToken.Const],
["var", JSToken.Var],
["let", JSToken.Let],
["new", JSToken.New],
["if", JSToken.If],
["else", JSToken.Else],
["for", JSToken.For],
["while", JSToken.While],
["do", JSToken.Do],
["switch", JSToken.Switch],
["case", JSToken.Case],
["yield", JSToken.Yield],
["return", JSToken.Return],
["continue", JSToken.Continue],
["break", JSToken.Break],
["class", JSToken.Class],
["enum", JSToken.Enum],
["interface", JSToken.Interface],
["function", JSToken.Function],
["import", JSToken.Import],
["export", JSToken.Export],
["default", JSToken.Default],
["from", JSToken.From],
["in", JSToken.In],
["of", JSToken.Of],
["typeof", JSToken.TypeOf],
["instanceof", JSToken.InstanceOf],
["void", JSToken.Void],
["delete", JSToken.Delete],
["this", JSToken.This],
["super", JSToken.Super],
["try", JSToken.Try],
["catch", JSToken.Catch],
["finally", JSToken.Finally],
["throw", JSToken.Throw],
["async", JSToken.Async],
["await", JSToken.Await],
["static", JSToken.Static],
["abstract", JSToken.Abstract],
["get", JSToken.Get],
["set", JSToken.Set],
["extends", JSToken.Extends],
["implements", JSToken.Implements],
["true", JSToken.True],
["false", JSToken.False],
["public", JSToken.Public],
["private", JSToken.Private],
["protected", JSToken.Protected],
["null", JSToken.Null],
["undefined", JSToken.Undefined],
["as", JSToken.As],
["type", JSToken.Type],
];
// Maps keywords to tokens
const keywordMap: Map<string, JSToken> = new Map(keywords);
// A series of sequences which when match the head of token reader matches will be collapsed into to the token on rhs
// TODO more assignments
const combine: Array<[Array<JSToken>, JSToken]> = [
[[JSToken.Plus, JSToken.Assign], JSToken.PlusAssign], // +=
[[JSToken.Dot, JSToken.Dot, JSToken.Dot], JSToken.Spread], // ...
[[JSToken.Minus, JSToken.Assign], JSToken.SubtractAssign], // -=
[[JSToken.Multiply, JSToken.Assign], JSToken.MultiplyAssign], // *=
[[JSToken.Divide, JSToken.Assign], JSToken.DivideAssign], // /=
[[JSToken.Plus, JSToken.Plus], JSToken.Increment], // ++
[[JSToken.Minus, JSToken.Minus], JSToken.Decrement], // --
[[JSToken.Assign, JSToken.CloseAngle], JSToken.ArrowFunction], // =>
[[JSToken.OpenAngle, JSToken.Assign], JSToken.LessThanEqual], // <=
[[JSToken.CloseAngle, JSToken.Assign], JSToken.GreaterThanEqual], // >=
[[JSToken.Multiply, JSToken.Multiply], JSToken.Exponent], // **
[[JSToken.Remainder, JSToken.Assign], JSToken.RemainderAssign], // %=
[[JSToken.Divide, JSToken.Divide], JSToken.Comment], // //
[[JSToken.Divide, JSToken.Multiply], JSToken.MultilineComment], // /* */
[[JSToken.Assign, JSToken.Assign], JSToken.Equal], // ==
[[JSToken.Equal, JSToken.Assign], JSToken.StrictEqual], // ===
[[JSToken.LogicalNot, JSToken.Assign], JSToken.NotEqual], // !=
[[JSToken.NotEqual, JSToken.Assign], JSToken.StrictNotEqual], // !==
[[JSToken.OpenAngle, JSToken.OpenAngle], JSToken.BitwiseShiftLeft], // <<
[[JSToken.CloseAngle, JSToken.CloseAngle], JSToken.BitwiseShiftRight], // >>
[[JSToken.BitwiseShiftRight, JSToken.CloseAngle], JSToken.UnaryBitwiseShiftRight], // >>>
[[JSToken.BitwiseOr, JSToken.BitwiseOr], JSToken.LogicalOr], // ||
[[JSToken.BitwiseAnd, JSToken.BitwiseAnd], JSToken.LogicalAnd], // &&
[[JSToken.QuestionMark, JSToken.Dot], JSToken.OptionalChain], // ?.
[[JSToken.QuestionMark, JSToken.QuestionMark], JSToken.NullishCoalescing], // ??
[[JSToken.Yield, JSToken.Multiply], JSToken.DelegatedYield], // yield*
[[JSToken.QuestionMark, JSToken.Colon], JSToken.OptionalMember], // ?:
];
// A map that reverses tokens to there original form
const tokenToKeyword = keywords.concat(symbols).map(([string, token]) => [token, string]);
export const tokenToKeywordMap: Map<JSToken, string> = new Map(tokenToKeyword as any);
// Reverse tokens formed from collapsation into the token-to-keyword map
combine.forEach(([group, token]) => {
tokenToKeywordMap.set(token, group.map(t => tokenToKeywordMap.get(t)).join(""))
});
// Setup reverses for tokens with no identifer
tokenToKeywordMap.set(JSToken.Identifier, "Identifier");
tokenToKeywordMap.set(JSToken.NumberLiteral, "Number");
tokenToKeywordMap.set(JSToken.StringLiteral, "String");
tokenToKeywordMap.set(JSToken.RegexLiteral, "RegularExpression");
tokenToKeywordMap.set(JSToken.TemplateLiteralString, "Template literal");
tokenToKeywordMap.set(JSToken.TemplateLiteralStart, "Template literal start");
tokenToKeywordMap.set(JSToken.TemplateLiteralEnd, "Template literal end");
tokenToKeywordMap.set(JSToken.EOF, "End of script");
tokenToKeywordMap.set(JSToken.Comment, "Comment");
tokenToKeywordMap.set(JSToken.MultilineComment, "Multiline comment");
function addIdent(string: string, column: number, line: number): Token<JSToken> {
if (keywordMap.has(string)) {
return { type: keywordMap.get(string)!, column: column - string.length, line };
} else {
return { type: JSToken.Identifier, value: string, column: column - string.length, line };
}
}
enum Literals {
Regex, Number, SingleQuoteString, DoubleQuoteString, Template, Comment, MultilineComment, Ident, HashBang
}
const combineMap = createCombineMap(combine);
const lengthMap = new Map();
for (const [str, token] of symbols.concat(keywords)) {
lengthMap.set(token, str.length);
}
export function stringToTokens(javascript: string, settings: ITokenizationSettings = {}): TokenReader<JSToken> {
if (!javascript) {
throw Error("Cannot tokenize empty string");
}
const reader = new TokenReader<JSToken>({
combinations: combineMap,
reverse: tokenToKeywordMap,
file: settings.file || null,
tokenLengths: lengthMap
});
let index = 0;
let acc = "";
let escaped = false; // Used in string literals to escape quotation marks etc, e.g: "\""
let line = settings.lineOffset || 1;
let column = settings.columnOffset || 0;
let currentLiteral: Literals | null = null;
let templateLiteralDepth = 0;
let curlyCount: Array<number> = []; // little workaround for templateLiterals
while (index < javascript.length) {
// Updates line and character token position:
if (javascript[index] === "\n") {
line++;
column = 0;
} else {
column++;
}
// If currently tokenizing literal
if (currentLiteral !== null) {
switch (currentLiteral) {
case Literals.Number:
if (characterIsNumber(javascript[index])) {
reader.top.value += javascript[index];
} else if (javascript[index] === "." && !reader.top.value?.includes(".")) {
reader.top.value += javascript[index];
}
// Numerical separators
else if (!reader.top.value?.endsWith("_") && javascript[index] === "_") {
reader.top.value += javascript[index];
}
// Hex, binary and octal literals
else if (reader.top.value === "0" && "xbo".includes(javascript[index])) {
reader.top.value += javascript[index];
}
// Big int
else if (javascript[index] === "n") {
reader.top.value += javascript[index];
currentLiteral = null;
}
// Exponential syntax
else if (javascript[index] === "e" && !reader.top.value?.includes("e")) {
reader.top.value += javascript[index];
}
// Hex syntax
else if (reader.top.value?.[1] === "x" && "abcdef".includes(javascript[index].toLowerCase())) {
reader.top.value += javascript[index];
} else {
currentLiteral = null;
column--; index--;
}
break;
case Literals.Comment:
if (javascript[index] === "\n") {
reader.top.value = reader.top.value!.trim();
currentLiteral = null;
} else {
reader.top.value += javascript[index];
}
break;
case Literals.HashBang:
if (javascript[index] === "\n") {
reader.top.value = reader.top.value!.trim();
currentLiteral = null;
} else {
reader.top.value += javascript[index];
}
break;
case Literals.MultilineComment:
if (javascript.startsWith("*/", index)) {
reader.top.value = reader.top.value!.trim();
index++; column++;
currentLiteral = null;
} else {
reader.top.value += javascript[index];
}
break;
case Literals.SingleQuoteString:
if (javascript[index] === "'" && !escaped) {
currentLiteral = null;
} else {
escaped = javascript[index] === "\\";
reader.top.value += javascript[index];
}
break;
case Literals.DoubleQuoteString:
if (javascript[index] === "\"" && !escaped) {
currentLiteral = null;
} else {
escaped = javascript[index] === "\\";
reader.top.value += javascript[index];
}
break;
case Literals.Regex:
if (javascript[index] === "/" && !escaped) {
currentLiteral = null;
} else {
escaped = javascript[index] === "\\";
reader.top.value += javascript[index];
}
break;
case Literals.Template:
if (javascript[index] === "`" && !escaped) {
currentLiteral = null;
templateLiteralDepth--;
reader.add({ type: JSToken.TemplateLiteralEnd, line, column });
} else if (javascript.startsWith("${", index) && !escaped) {
index++; column++;
curlyCount.push(1);
currentLiteral = null;
} else {
if (javascript[index] === "\\") escaped = true;
else escaped = false;
reader.top.value += javascript[index];
}
break;
// Deals with unicode variables names eg: \u{00ab} \\u\{([0-9a-fA-F]{1,})\}
case Literals.Ident:
if (reader.top.value === "\\") {
if (javascript[index] !== "u") reader.throwExpect(`"u" in unicode variable identifier`);
reader.top.value += "u";
} else if (reader.top.value?.length === 2 && javascript[index] === "{") {
reader.top.value += "{";
} else if (javascript[index] === "}") {
reader.top.value += "}";
currentLiteral = null;
} else if (reader.top.value!.length > 2) {
const charCode = javascript.charCodeAt(index);
if (
47 < charCode && charCode < 58 ||
64 < charCode && charCode < 71 ||
96 < charCode && charCode < 103
) {
reader.top.value += javascript[index];
} else {
currentLiteral = null;
column--; index--;
}
} else {
currentLiteral = null;
column--; index--;
}
break;
}
}
// If meets a symbol
else if (symbolsMap.has(javascript[index])) {
if (acc.length > 0) {
reader.add(addIdent(acc, column, line));
acc = "";
}
const tokenType = symbolsMap.get(javascript[index])!;
if (templateLiteralDepth > 0) {
if (tokenType === JSToken.OpenCurly) {
curlyCount[templateLiteralDepth - 1]++;
} else if (tokenType === JSToken.CloseCurly) {
curlyCount[templateLiteralDepth - 1]--;
if (curlyCount[templateLiteralDepth - 1] === 0) {
curlyCount.pop();
reader.add({ type: JSToken.TemplateLiteralString, value: "", line, column });
currentLiteral = Literals.Template;
}
}
}
if (currentLiteral === Literals.Template) { }
else if (javascript.startsWith("//", index)) {
index++; column++;
reader.add({ type: JSToken.Comment, value: "", column, line });
currentLiteral = Literals.Comment;
} else if (javascript.startsWith("/*", index)) {
index++; column++;
reader.add({ type: JSToken.MultilineComment, value: "", column, line });
currentLiteral = Literals.MultilineComment;
} else if (tokenType === JSToken.SingleQuote || tokenType === JSToken.DoubleQuote) {
reader.add({ type: JSToken.StringLiteral, value: "", line, column })
currentLiteral = javascript[index] === "\"" ? Literals.DoubleQuoteString : Literals.SingleQuoteString;
}
// Divide can also match regex literal
else if (tokenType === JSToken.Divide) {
// These tokens cannot be used before regex literal as they imply division
const tokensBeforeDivision = [JSToken.Identifier, JSToken.NumberLiteral, JSToken.CloseBracket];
if (
(
reader.length === 0 ||
(tokensBeforeDivision.includes(reader.top.type) === false)
) &&
"*/".includes(javascript[index + 1]) === false
) {
reader.add({ type: JSToken.RegexLiteral, value: "", column, line });
currentLiteral = Literals.Regex;
} else {
reader.add({ type: tokenType, column, line });
}
}
// For template literals
else if (tokenType === JSToken.TemplateLiteralStart) {
currentLiteral = Literals.Template;
templateLiteralDepth++;
reader.add({ type: JSToken.TemplateLiteralStart, column, line });
reader.add({ type: JSToken.TemplateLiteralString, value: "", column, line });
}
// For decimals without number in front e.g .5
else if (tokenType === JSToken.Dot && characterIsNumber(javascript[index + 1])) {
reader.add({ type: JSToken.NumberLiteral, value: ".", column, line });
currentLiteral = Literals.Number;
}
// For unicode variable names
else if (tokenType === JSToken.Backslash && javascript[index + 1] === "u") {
reader.add({ type: JSToken.Identifier, value: "\\", column, line });
currentLiteral = Literals.Ident;
}
// HashBang for nodejs scripts
else if (tokenType === JSToken.HashTag && reader.length === 0) {
reader.add({ type: JSToken.HashBang, value: "", column, line });
currentLiteral = Literals.HashBang;
} else {
reader.add({ type: tokenType, column, line });
}
}
// If start of number (#!/usr/bin/env node)
else if (characterIsNumber(javascript[index]) && acc.length === 0) {
if (acc.length > 0) {
reader.add(addIdent(acc, column - 1, line));
acc = "";
}
reader.add({ type: JSToken.NumberLiteral, value: javascript[index], column, line });
currentLiteral = Literals.Number;
}
// If break add the acc as a identifer
else if (
javascript[index] === " " ||
javascript[index] === "\n" ||
javascript[index] === "\r" ||
javascript[index] === "\t"
) {
if (acc.length > 0) {
reader.add(addIdent(acc, column - 1, line));
acc = "";
}
}
// Else append the accumulator
// if (javascript[index] !== "\n" && javascript[index] !== "\r")
else {
acc += javascript[index];
}
index++;
}
if (curlyCount.length > 1) {
reader.throwError("Could not find end to template literal");
}
if (currentLiteral === Literals.Comment) {
reader.top.value = reader.top.value!.trim();
acc = "";
} else if (currentLiteral !== null && currentLiteral !== Literals.Number && currentLiteral !== Literals.Ident) {
reader.throwError(`Could not find end to ${Literals[currentLiteral]}`);
}
if (acc.length > 0) {
reader.add(addIdent(acc, column, line));
}
reader.add({ type: JSToken.EOF, column: column + 1, line });
return reader;
} | the_stack |
import { getDPRValue, hideAutoFillElement, hideAutoFillOptions, positionAutoFillElement, Spreadsheet } from '../index';
import { closest, detach, EventHandler } from '@syncfusion/ej2-base';
import { Tooltip } from '@syncfusion/ej2-popups';
import { colWidthChanged, rowHeightChanged, contentLoaded, getFilterRange } from '../common/index';
import { findMaxValue, setResize, autoFit, HideShowEventArgs, completeAction, setAutoFit } from '../common/index';
import { setRowHeight, isHiddenRow, SheetModel, getRowHeight, getColumnWidth, setColumn, isHiddenCol } from '../../workbook/base/index';
import { getColumn, setRow, getCell, CellModel } from '../../workbook/base/index';
import { getRangeIndexes, getSwapRange, CellStyleModel, getCellIndexes, setMerge, MergeArgs } from '../../workbook/common/index';
import { rowFillHandler, hideShow } from '../../workbook/common/event';
/**
* The `Resize` module is used to handle the resizing functionalities in Spreadsheet.
*/
export class Resize {
private parent: Spreadsheet;
private trgtEle: HTMLElement;
private event: MouseEvent;
private isMouseMoved: boolean;
/**
* Constructor for resize module in Spreadsheet.
*
* @param {Spreadsheet} parent - Constructor for resize module in Spreadsheet.
* @private
*/
constructor(parent: Spreadsheet) {
this.parent = parent;
this.addEventListener();
}
private addEventListener(): void {
this.parent.on(contentLoaded, this.wireEvents, this);
this.parent.on(autoFit, this.autoFit, this);
this.parent.on(setAutoFit, this.setAutoFitHandler, this);
}
private autoFit(args: { isRow: boolean, startIndex: number, endIndex: number }): void {
const element: Element = args.isRow ? this.parent.getRowHeaderTable() : this.parent.getColHeaderTable().rows[0];
for (let i: number = args.startIndex; i <= args.endIndex; i++) {
this.trgtEle = args.isRow ? this.parent.getRow(i, <HTMLTableElement>element) :
this.parent.getCell(null, i, <HTMLTableRowElement>element);
this.setAutofit(i, !args.isRow);
}
}
private wireEvents(): void {
const rowHeader: Element = this.parent.getRowHeaderContent();
const colHeader: Element = this.parent.element.getElementsByClassName('e-header-panel')[0];
if (!colHeader) {
return;
}
EventHandler.add(colHeader, 'dblclick', this.dblClickHandler, this);
EventHandler.add(rowHeader, 'dblclick', this.dblClickHandler, this);
EventHandler.add(colHeader, 'mousedown', this.mouseDownHandler, this);
EventHandler.add(rowHeader, 'mousedown', this.mouseDownHandler, this);
this.wireResizeCursorEvent(rowHeader, colHeader);
}
private wireResizeCursorEvent(rowHeader: Element, colHeader: Element): void {
EventHandler.add(rowHeader, 'mousemove', this.setTarget, this);
EventHandler.add(colHeader, 'mousemove', this.setTarget, this);
}
private unWireResizeCursorEvent(): void {
EventHandler.remove(this.parent.getRowHeaderContent(), 'mousemove', this.setTarget);
const headerPanel: Element = this.parent.element.getElementsByClassName('e-header-panel')[0];
if (headerPanel) {
EventHandler.remove(headerPanel, 'mousemove', this.setTarget);
}
}
private unwireEvents(): void {
EventHandler.remove(this.parent.getColumnHeaderContent(), 'dblclick', this.dblClickHandler);
EventHandler.remove(this.parent.getRowHeaderContent(), 'dblclick', this.dblClickHandler);
EventHandler.remove(this.parent.getColumnHeaderContent(), 'mousedown', this.mouseDownHandler);
EventHandler.remove(this.parent.getRowHeaderContent(), 'mousedown', this.mouseDownHandler);
this.unWireResizeCursorEvent();
}
private removeEventListener(): void {
if (!this.parent.isDestroyed) {
this.parent.off(contentLoaded, this.wireEvents);
this.parent.off(autoFit, this.autoFit);
this.parent.off(setAutoFit, this.setAutoFitHandler);
}
}
private mouseMoveHandler(e: MouseEvent): void {
const colResizeHandler: HTMLElement = this.parent.element.getElementsByClassName('e-colresize-handler')[0] as HTMLElement;
const rowResizeHandler: HTMLElement = this.parent.element.getElementsByClassName('e-rowresize-handler')[0] as HTMLElement;
this.resizeTooltip(null, true, e);
if (colResizeHandler || rowResizeHandler) {
this.isMouseMoved = true;
if (colResizeHandler) {
if (e.x > (this.trgtEle.parentElement.firstChild as HTMLElement).getBoundingClientRect().left) {
colResizeHandler.style.left = e.clientX -
document.getElementById(this.parent.element.id + '_sheet').getBoundingClientRect().left + 'px';
}
} else if (rowResizeHandler) {
if (e.y >= (this.trgtEle.parentElement.parentElement.firstChild as HTMLElement).getBoundingClientRect().top) {
rowResizeHandler.style.top = e.clientY -
document.getElementById(this.parent.element.id + '_sheet').getBoundingClientRect().top + 'px';
}
}
}
}
private mouseDownHandler(e: MouseEvent & TouchEvent): void {
if (!closest(e.target as Element, '.e-header-cell')) { return; }
this.event = e;
this.trgtEle = <HTMLElement>e.target;
if (this.trgtEle.parentElement.classList.contains('e-hide-end') || this.trgtEle.classList.contains('e-hide-end')) {
const offsetSize: number = this.trgtEle.offsetHeight;
const offset: number = e.offsetY;
if ((offsetSize >= 10 && offset < 5) || (offsetSize - 2 < 8 && offset < Math.ceil((offset - 2) / 2))) {
this.trgtEle.classList.add('e-skip-resize');
}
}
this.updateTarget(e, this.trgtEle);
const trgt: HTMLElement = this.trgtEle;
const className: string = trgt.classList.contains('e-colresize') ? 'e-colresize-handler' :
trgt.classList.contains('e-rowresize') ? 'e-rowresize-handler' : '';
this.createResizeHandler(trgt, className);
this.unWireResizeCursorEvent();
EventHandler.add(this.parent.element, 'mousemove', this.mouseMoveHandler, this);
EventHandler.add(document, 'mouseup', this.mouseUpHandler, this);
}
private mouseUpHandler(e: MouseEvent & TouchEvent): void {
const resizeHandler: HTMLElement = this.parent.element.getElementsByClassName('e-resize-handle')[0] as HTMLElement;
this.resizeOn(e);
this.isMouseMoved = null;
const HeaderTooltip: HTMLElement = document.querySelector('.e-header-tooltip');
if (resizeHandler) {
detach(resizeHandler);
this.updateCursor();
}
if (HeaderTooltip) {
HeaderTooltip.remove();
}
EventHandler.remove(document, 'mouseup', this.mouseUpHandler);
EventHandler.remove(this.parent.element, 'mousemove', this.mouseMoveHandler);
const colHeader: Element = this.parent.element.getElementsByClassName('e-header-panel')[0];
if (colHeader) {
this.wireResizeCursorEvent(this.parent.getRowHeaderContent(), colHeader);
}
this.parent.notify(positionAutoFillElement, null );
this.parent.notify(hideAutoFillOptions, null );
}
private dblClickHandler(e?: MouseEvent & TouchEvent): void {
if (!closest(e.target as Element, '.e-header-cell')) { return; }
this.trgtEle = <HTMLElement>e.target;
this.updateTarget(e, this.trgtEle);
if (this.trgtEle.classList.contains('e-colresize')) {
const colIndx: number = parseInt(this.trgtEle.getAttribute('aria-colindex'), 10) - 1;
const prevWidth: string = `${getColumnWidth(this.parent.getActiveSheet(), colIndx)}px`;
if (this.trgtEle.classList.contains('e-unhide-column')) {
this.showHiddenColumns(colIndx - 1);
} else {
this.setAutofit(colIndx, true, prevWidth);
}
} else if (this.trgtEle.classList.contains('e-rowresize')) {
const rowIndx: number = parseInt(this.trgtEle.parentElement.getAttribute('aria-rowindex'), 10) - 1;
const prevHeight: string = `${getRowHeight(this.parent.getActiveSheet(), rowIndx)}px`;
this.setAutofit(rowIndx, false, prevHeight);
}
this.parent.notify(positionAutoFillElement, null );
}
private setTarget(e: MouseEvent): void {
if (!closest(e.target as Element, '.e-header-cell')) { return; }
const trgt: HTMLElement = <HTMLElement>e.target;
const sheet: SheetModel = this.parent.getActiveSheet();
if (sheet.isProtected && (!sheet.protectSettings.formatColumns || !sheet.protectSettings.formatRows)) {
if (!sheet.protectSettings.formatRows && !sheet.protectSettings.formatColumns) {
return;
}
if (sheet.protectSettings.formatRows) {
if (closest(trgt, '.e-colhdr-table')) {
return;
}
}
if (sheet.protectSettings.formatColumns ) {
if (closest(trgt, '.e-rowhdr-table')) {
return;
}
}
}
let newTrgt: HTMLElement; let tOffsetV: number; let eOffsetV: number; let tClass: string;
if (closest(trgt, '.e-header-row')) {
eOffsetV = e.offsetX; tOffsetV = trgt.offsetWidth; tClass = 'e-colresize';
const prevSibling: Element = this.getColPrevSibling(trgt);
if (prevSibling && !prevSibling.classList.contains('e-select-all-cell')) {
newTrgt = <HTMLElement>prevSibling;
} else {
if (Number(trgt.getAttribute('aria-colindex')) > 1) { newTrgt = trgt; }
}
} else if (closest(trgt, '.e-row')) {
eOffsetV = e.offsetY; tOffsetV = trgt.offsetHeight; tClass = 'e-rowresize';
const prevSibling: Element = this.getRowPrevSibling(trgt);
if (prevSibling) {
newTrgt = <HTMLElement>prevSibling.firstElementChild;
} else {
if (Number(trgt.parentElement.getAttribute('aria-rowindex')) > 1) { newTrgt = trgt; }
}
}
if (tOffsetV - 2 < 8 && eOffsetV !== Math.ceil((tOffsetV - 2) / 2)) {
if (eOffsetV < Math.ceil((tOffsetV - 2) / 2)) {
trgt.classList.add(tClass);
newTrgt.classList.add(tClass);
} else if (eOffsetV > Math.ceil((tOffsetV - 2) / 2)) {
trgt.classList.add(tClass);
}
} else if (tOffsetV - 5 < eOffsetV && eOffsetV <= tOffsetV && tOffsetV >= 10) {
trgt.classList.add(tClass);
} else if (eOffsetV < 5 && newTrgt && tOffsetV >= 10) {
trgt.classList.add(tClass);
newTrgt.classList.add(tClass);
} else {
const resEle: HTMLCollectionOf<Element> = this.parent.element.getElementsByClassName(tClass) as HTMLCollectionOf<Element>;
for (let index: number = 0; index < resEle.length; index++) {
resEle[index].classList.remove(tClass);
}
}
}
private getColPrevSibling(trgt: HTMLElement): Element {
const frozenCol: number = this.parent.frozenColCount(this.parent.getActiveSheet());
return trgt.previousElementSibling || (frozenCol && closest(trgt, '.e-column-header') ?
this.parent.getSelectAllContent().querySelector('.e-header-row').lastElementChild : null);
}
private getRowPrevSibling(trgt: HTMLElement): Element {
const frozenRow: number = this.parent.frozenRowCount(this.parent.getActiveSheet());
return trgt.parentElement.previousElementSibling || (frozenRow && closest(trgt, '.e-row-header') ?
this.parent.getSelectAllContent().querySelector('tbody').lastElementChild : null);
}
private updateTarget(e: MouseEvent, trgt: HTMLElement): void {
if (closest(trgt, '.e-header-row')) {
if ((trgt.offsetWidth < 10 && e.offsetX < Math.ceil((trgt.offsetWidth - 2) / 2)) || (e.offsetX < 5 &&
trgt.offsetWidth >= 10) && trgt.classList.contains('e-colresize')) {
const sheet: SheetModel = this.parent.getActiveSheet();
const prevIdx: number = Number(this.trgtEle.getAttribute('aria-colindex')) - 2;
const prevSibling: Element = this.getColPrevSibling(trgt);
if (prevSibling && !isHiddenCol(sheet, prevIdx)) {
this.trgtEle = prevSibling as HTMLElement;
} else {
if (prevIdx > -1) { this.trgtEle.classList.add('e-unhide-column'); }
}
}
} else {
if ((trgt.offsetHeight < 10 && e.offsetY < Math.ceil((trgt.offsetHeight - 2) / 2)) || (e.offsetY < 5 &&
trgt.offsetHeight >= 10) && trgt.classList.contains('e-rowresize')) {
const sheet: SheetModel = this.parent.getActiveSheet();
const prevIdx: number = Number(trgt.parentElement.getAttribute('aria-rowindex')) - 2;
const prevSibling: Element = this.getRowPrevSibling(trgt);
if (prevSibling || isHiddenRow(sheet, prevIdx)) {
if (e.type === 'dblclick' && isHiddenRow(sheet, prevIdx)) {
const selectRange: number[] = getSwapRange(getRangeIndexes(sheet.selectedRange));
let eventArgs: HideShowEventArgs;
if (prevIdx <= selectRange[2] && prevIdx > selectRange[0]) {
eventArgs = { startIndex: selectRange[0], endIndex: selectRange[2], hide: false, autoFit: true };
} else {
eventArgs = { startIndex: prevIdx, endIndex: prevIdx, hide: false, autoFit: true };
}
this.parent.notify(hideShow, eventArgs);
} else {
if (!isHiddenRow(sheet, prevIdx)) {
this.trgtEle = prevSibling.getElementsByClassName('e-header-cell')[0] as HTMLElement;
}
}
}
}
}
}
private setAutoFitHandler(args: { idx: number, isCol: boolean }): void {
this.setAutofit(args.idx, args.isCol);
}
private setAutofit(idx: number, isCol?: boolean, prevData?: string): void {
let index: number = 0;
const sheet: SheetModel = this.parent.getActiveSheet();
const mainContent: Element = this.parent.getMainContent();
const oldValue: string = isCol ? `${getColumnWidth(this.parent.getActiveSheet(), idx)}px` :
`${getRowHeight(this.parent.getActiveSheet(), idx)}px`;
const contentClone: HTMLElement[] = [];
let oldHeight: number = 0;
const contentTable: HTMLElement = mainContent.getElementsByClassName('e-content-table')[0] as HTMLElement;
let isWrap: boolean = false; let wrapCount: number = 0;
if (isCol) {
const rowLength: number = sheet.rows.length;
for (let rowIdx: number = 0; rowIdx < rowLength; rowIdx++) {
if (sheet.rows[rowIdx] && sheet.rows[rowIdx].cells && sheet.rows[rowIdx].cells[idx]) {
if (getCell(rowIdx, idx, sheet).wrap) {
isWrap = true;
wrapCount++;
}
const td: HTMLElement = this.parent.createElement('td', { className: 'e-cell' });
td.textContent = this.parent.getDisplayText(sheet.rows[rowIdx].cells[idx]);
if (sheet.rows[rowIdx].cells[idx].style) {
const style: CellStyleModel = sheet.rows[rowIdx].cells[idx].style;
if (style.fontFamily) {
td.style.fontFamily = style.fontFamily;
}
if (style.fontSize) {
td.style.fontSize = style.fontSize;
}
}
contentClone[index] = td;
index++;
}
}
} else {
const colLength: number = sheet.rows[idx] && sheet.rows[idx].cells ? sheet.rows[idx].cells.length : 0;
for (let colIdx: number = 0; colIdx < colLength; colIdx++) {
if (sheet.rows[idx] && sheet.rows[idx].cells[colIdx]) {
if (getCell(idx, colIdx, sheet).wrap) {
isWrap = true;
wrapCount++;
}
const td: HTMLElement = this.parent.createElement('td');
td.textContent = this.parent.getDisplayText(sheet.rows[idx].cells[colIdx]);
if (sheet.rows[idx].cells[colIdx].style) {
const style: CellStyleModel = sheet.rows[idx].cells[colIdx].style;
if (style.fontFamily) {
td.style.fontFamily = style.fontFamily;
}
if (style.fontSize) {
td.style.fontSize = style.fontSize;
}
}
contentClone[index] = td;
index++;
}
}
}
if (wrapCount === 0) {
let contentFit: number = findMaxValue(contentTable, contentClone, isCol, this.parent, prevData, isWrap);
if (isCol) {
contentFit = this.getFloatingElementWidth(contentFit, idx);
}
let autofitValue: number = contentFit === 0 ? parseInt(oldValue, 10) : contentFit;
let threshold: number = parseInt(oldValue, 10) > autofitValue ?
-(parseInt(oldValue, 10) - autofitValue) : autofitValue - parseInt(oldValue, 10);
if (isCol) {
if (idx >= this.parent.viewport.leftIndex && idx <= this.parent.viewport.rightIndex) {
getColumn(sheet, idx).width = autofitValue > 0 ? autofitValue : 0;
this.resizeStart(idx, this.parent.getViewportIndex(idx, true), autofitValue + 'px', isCol, true, prevData);
this.parent.notify(colWidthChanged, { threshold: threshold, colIdx: idx });
} else {
const oldWidth: number = getColumnWidth(sheet, idx);
let threshold: number;
if (autofitValue > 0) {
threshold = -(oldWidth - autofitValue);
} else {
threshold = -oldWidth;
}
this.parent.notify(colWidthChanged, { threshold, colIdx: idx });
getColumn(sheet, idx).width = autofitValue > 0 ? autofitValue : 0;
}
} else if (!isCol) {
if (idx >= this.parent.viewport.topIndex && idx <= this.parent.viewport.bottomIndex) {
autofitValue = autofitValue > 20 ? autofitValue : 20;
oldHeight = getRowHeight(sheet, idx);
if (autofitValue > 0) {
threshold = -(oldHeight - autofitValue);
} else {
threshold = -oldHeight;
}
setRowHeight(sheet, idx, autofitValue > 0 ? autofitValue : 0);
setRow(sheet, idx, { customHeight: false });
this.resizeStart(idx, this.parent.getViewportIndex(idx), autofitValue + 'px', isCol, true, prevData);
this.parent.notify(rowHeightChanged, { threshold: threshold, rowIdx: idx });
} else {
oldHeight = getRowHeight(sheet, idx);
let threshold: number;
if (autofitValue > 0) {
threshold = -(oldHeight - autofitValue);
} else {
threshold = -oldHeight;
}
this.parent.notify(rowHeightChanged, { threshold, rowIdx: idx });
setRowHeight(sheet, idx, autofitValue > 0 ? autofitValue : 0);
}
}
}
this.parent.selectRange(this.parent.getActiveSheet().selectedRange);
}
private createResizeHandler(trgt: HTMLElement, className: string): void {
const editor: HTMLElement = this.parent.createElement('div', { className: className });
editor.classList.add('e-resize-handle');
const sheet: HTMLElement = document.getElementById(this.parent.element.id + '_sheet');
if (trgt.classList.contains('e-colresize')) {
editor.style.height = this.parent.getMainContent().parentElement.clientHeight + this.parent.getColumnHeaderContent().offsetHeight + 'px';
editor.style.left = this.event.clientX - sheet.getBoundingClientRect().left + 'px';
editor.style.top = '0px';
} else if (trgt.classList.contains('e-rowresize')) {
editor.style.width = this.parent.getMainContent().parentElement.clientWidth + 'px';
editor.style.left = '0px';
editor.style.top = this.event.clientY - sheet.getBoundingClientRect().top + 'px';
}
sheet.appendChild(editor);
this.resizeTooltip(trgt, false);
this.updateCursor();
}
private resizeTooltip(trgt: HTMLElement, isResize?: boolean, e?: MouseEvent): void {
if (isResize) {
const HeaderTolltip: HTMLElement = document.querySelector('.e-header-tooltip');
const colResizeHandler: HTMLElement = this.parent.element.getElementsByClassName('e-colresize-handler')[0] as HTMLElement;
const rowResizeHandler: HTMLElement = this.parent.element.getElementsByClassName('e-rowresize-handler')[0] as HTMLElement;
if (colResizeHandler) {
const trgtWidth: number = (e.clientX) - Math.round(this.trgtEle.getBoundingClientRect().left);
if (HeaderTolltip) {
HeaderTolltip.firstChild.textContent = trgtWidth > 0 ? ('Width:(' + trgtWidth.toString() + ' pixels)') : ('Width: 0.00');
}
} else if (rowResizeHandler) {
const trgtHeight: number = (e.clientY) - Math.round(this.trgtEle.getBoundingClientRect().top);
if (HeaderTolltip) {
HeaderTolltip.firstChild.textContent = trgtHeight > 0 ? ('Height:(' + trgtHeight.toString() + ' pixels)') : ('Height: 0.00');
}
}
} else {
const isColResize: boolean = trgt.classList.contains('e-colresize');
const isRowResize: boolean = trgt.classList.contains('e-rowresize');
if (isColResize || isRowResize) {
const className: string = isColResize ? 'e-colresize-handler' : 'e-rowresize-handler';
const tooltip: Tooltip = new Tooltip({
cssClass: 'e-header-tooltip',
showTipPointer: false
});
if (isColResize) {
tooltip.content = 'Width:(' + Math.round(trgt.getBoundingClientRect().width).toString() + ' pixels)';
} else if (isRowResize) {
tooltip.content = 'Height:(' + Math.round(trgt.getBoundingClientRect().height).toString() + ' pixels)';
tooltip.offsetX = -((this.parent.getMainContent().parentElement.clientWidth / 2) -
Math.round(trgt.getBoundingClientRect().width));
}
tooltip.appendTo('.' + className);
tooltip.open();
tooltip.refresh();
}
}
}
private setColWidth(index: number, viewportIdx: number, width: number, curWidth: number): void {
const sheet: SheetModel = this.parent.getActiveSheet();
let threshold: number = getDPRValue(width) - curWidth;
if (threshold < 0 && curWidth < -(threshold)) {
threshold = -curWidth;
}
if (width > 0) {
if (this.isMouseMoved && this.trgtEle.classList.contains('e-unhide-column')) {
this.showHiddenColumns(index, width);
this.parent.notify(completeAction, {
eventArgs: {
index: index, width: `${0}px`, isCol: true, sheetIndex: this.parent.activeSheetIndex, oldWidth: `${curWidth}px`,
hide: false
}, action: 'resize'
});
return;
}
this.resizeStart(index, viewportIdx, `${width}px`, true, false, `${curWidth}px`);
setColumn(sheet, index, { width: width, customWidth: true });
this.parent.notify(colWidthChanged, { threshold, colIdx: index, checkWrapCell: true });
} else {
if (this.isMouseMoved) {
this.parent.hideColumn(index);
this.showHideCopyIndicator();
this.parent.notify(completeAction, {
eventArgs: {
index: index, width: `${0}px`, isCol: true, sheetIndex: this.parent.activeSheetIndex, oldWidth: `${curWidth}px`,
hide: true
}, action: 'resize'
});
}
}
}
private showHideCopyIndicator(): void{
const copyIndicator: HTMLElement = this.parent.element.getElementsByClassName('e-copy-indicator')[0] as HTMLElement;
let isIndicator: boolean = false;
if (copyIndicator) {
detach(copyIndicator);
this.parent.notify(hideAutoFillElement, null);
isIndicator = true;
}
if (isIndicator) {
this.parent.notify(contentLoaded, {});
}
}
private showHiddenColumns(index: number, width?: number): void {
const sheet: SheetModel = this.parent.getActiveSheet();
const selectedRange: number[] = getRangeIndexes(sheet.selectedRange);
let startIdx: number; let endIdx: number; let colgroup: Element;
if (index >= selectedRange[1] && index <= selectedRange[3] && selectedRange[2] === sheet.rowCount - 1 &&
getCellIndexes(sheet.activeCell)[0] === getCellIndexes(sheet.topLeftCell)[0]) {
startIdx = selectedRange[1]; endIdx = selectedRange[3];
colgroup = this.parent.getMainContent().querySelector('colgroup');
} else {
startIdx = endIdx = index;
}
if (width !== undefined) {
for (let i: number = startIdx; i <= endIdx; i++) {
setColumn(sheet, i, { width: width, customWidth: true });
if (i >= this.parent.viewport.leftIndex && i <= this.parent.viewport.rightIndex && !isHiddenCol(sheet, i)) {
(colgroup.children[this.parent.getViewportIndex(i, true)] as HTMLElement).style.width = `${width}px`;
}
}
}
this.trgtEle.classList.remove('e-unhide-column');
const hideEvtArgs: HideShowEventArgs = { startIndex: startIdx, endIndex: endIdx, hide: false, isCol: true, autoFit: true };
this.parent.notify(hideShow, hideEvtArgs);
this.showHideCopyIndicator();
if (width === undefined) {
if (hideEvtArgs.autoFit) {
this.autoFit({ isRow: false, startIndex: startIdx, endIndex: endIdx })
} else {
const performAutoFit: Function = (): void => {
this.parent.off(contentLoaded, performAutoFit);
this.autoFit({ isRow: false, startIndex: startIdx, endIndex: endIdx });
};
this.parent.on(contentLoaded, performAutoFit, this);
}
}
}
private setRowHeight(rowIdx: number, viewportIdx: number, height: string, prevData?: string): void {
const sheet: SheetModel = this.parent.getActiveSheet(); const frozenCol: number = this.parent.frozenColCount(sheet);
const eleHeight: number = parseInt(this.parent.getRow(rowIdx, null, frozenCol).style.height, 10);
const rowHeight: string = height;
let threshold: number = getDPRValue(parseInt(rowHeight, 10)) - eleHeight;
if (threshold < 0 && eleHeight < -(threshold)) {
threshold = -eleHeight;
}
this.resizeStart(rowIdx, viewportIdx, rowHeight, false, false, prevData);
setRow(sheet, rowIdx, { height: parseInt(rowHeight, 10) > 0 ? parseInt(rowHeight, 10) : 0, customHeight: true });
this.parent.notify(rowHeightChanged, { threshold, rowIdx: rowIdx, isCustomHgt: true });
}
private resizeOn(e: MouseEvent): void {
let idx: number; let actualIdx: number; const sheet: SheetModel = this.parent.getActiveSheet();
const activeCell: number[] = getRangeIndexes(sheet.activeCell);
const CellElem: CellModel = getCell(activeCell[0], activeCell[1], sheet);
if (this.trgtEle.classList.contains('e-rowresize')) {
const prevIdx: number = Number(this.trgtEle.parentElement.getAttribute('aria-rowindex')) - 2;
if (this.isMouseMoved && isHiddenRow(sheet, prevIdx) && this.trgtEle.classList.contains('e-skip-resize') &&
e.clientY > this.trgtEle.getBoundingClientRect().top) {
this.trgtEle.classList.remove('e-skip-resize');
const eventArgs: HideShowEventArgs = { startIndex: prevIdx, endIndex: prevIdx, hide: false, skipAppend: true };
this.parent.notify(hideShow, eventArgs);
const rTbody: HTMLElement = this.parent.getRowHeaderTable().tBodies[0];
const tbody: HTMLElement = this.parent.getContentTable().tBodies[0];
eventArgs.hdrRow.style.display = 'none'; eventArgs.row.style.display = 'none';
rTbody.insertBefore(eventArgs.hdrRow, rTbody.children[eventArgs.insertIdx]);
tbody.insertBefore(eventArgs.row, tbody.children[eventArgs.insertIdx]);
this.trgtEle = <HTMLElement>eventArgs.hdrRow.firstElementChild;
eventArgs.hdrRow.nextElementSibling.classList.remove('e-hide-end');
eventArgs.mergeCollection.forEach((mergeArgs: MergeArgs): void => { this.parent.notify(setMerge, mergeArgs); });
} else {
if (this.trgtEle.classList.contains('e-skip-resize')) {
this.trgtEle.classList.remove('e-skip-resize');
if ((!this.isMouseMoved && isHiddenRow(sheet, prevIdx)) || !this.trgtEle.parentElement.previousElementSibling) {
return;
}
this.trgtEle = this.trgtEle.parentElement.previousElementSibling.getElementsByClassName(
'e-header-cell')[0] as HTMLElement;
}
}
actualIdx = idx = parseInt(this.trgtEle.parentElement.getAttribute('aria-rowindex'), 10) - 1;
idx = this.parent.getViewportIndex(actualIdx);
const frozenCol: number = this.parent.frozenColCount(sheet);
let prevData: string = this.parent.getRow(actualIdx, null, frozenCol).style.height;
let rowHeight: number = e.clientY - this.event.clientY + parseInt(prevData, 10);
if (rowHeight <= 0) {
this.parent.hideRow(actualIdx);
this.showHideCopyIndicator();
setRow(sheet, actualIdx, { height: 0, customHeight: true });
this.parent.notify(completeAction, {
eventArgs:
{ index: actualIdx, height: '0px', isCol: false, sheetIndex: this.parent.activeSheetIndex, oldHeight: prevData },
action: 'resize'
});
return;
}
this.setRowHeight(actualIdx, idx, `${rowHeight}px`, prevData);
if (CellElem && CellElem.rowSpan) {
const td: HTMLElement = this.parent.getCell(activeCell[0], activeCell[1]);
(this.parent.element.querySelector('.e-active-cell') as HTMLElement).style.height = td.offsetHeight + 'px';
}
if (this.trgtEle.parentElement.style.display === 'none') {
const sheet: SheetModel = this.parent.getActiveSheet();
const selectedRange: number[] = getSwapRange(getRangeIndexes(sheet.selectedRange));
if (actualIdx <= selectedRange[2] && actualIdx > selectedRange[0]) {
rowHeight = getRowHeight(sheet, actualIdx); let count: number;
for (let i: number = selectedRange[0]; i <= selectedRange[2]; i++) {
if (i === actualIdx) { continue; }
prevData = `${getRowHeight(sheet, i)}px`;
setRow(sheet, i, { customHeight: true, height: rowHeight });
if (isHiddenRow(sheet, i)) {
if (!count) { count = i; }
} else {
this.parent.getRow(i).style.height = `${rowHeight}px`;
if (sheet.showHeaders) {
this.parent.getRow(i, this.parent.getRowHeaderTable()).style.height = `${rowHeight}px`;
}
}
this.parent.notify(completeAction, {
eventArgs:
{
index: i, height: `${rowHeight}px`, isCol: false,
sheetIndex: this.parent.activeSheetIndex, oldHeight: prevData
},
action: 'resize'
});
}
this.parent.hideRow(selectedRange[0], actualIdx - 1, false);
this.showHideCopyIndicator();
idx += Math.abs(actualIdx - count);
} else {
if (idx !== 0 && !isHiddenRow(sheet, actualIdx - 1)) {
this.trgtEle.parentElement.previousElementSibling.classList.remove('e-hide-start');
} else {
if (idx !== 0) { this.trgtEle.parentElement.classList.add('e-hide-end'); }
}
this.parent.selectRange(sheet.selectedRange);
}
this.trgtEle.parentElement.style.display = ''; this.parent.getContentTable().rows[idx].style.display = '';
}
} else if (this.trgtEle.classList.contains('e-colresize')) {
if (this.isMouseMoved && this.trgtEle.classList.contains('e-unhide-column') &&
e.clientX < this.trgtEle.getBoundingClientRect().left) {
this.trgtEle.classList.remove('e-unhide-column');
if (this.trgtEle.previousElementSibling) { this.trgtEle = <HTMLElement>this.trgtEle.previousElementSibling; }
}
idx = parseInt(this.trgtEle.getAttribute('aria-colindex'), 10) - 1;
let curWidth: number;
if (this.trgtEle.classList.contains('e-unhide-column')) {
idx -= 1; curWidth = 0;
} else {
curWidth = getColumnWidth(this.parent.getActiveSheet(), idx);
}
this.setColWidth(idx, this.parent.getViewportIndex(idx, true), (e.clientX - this.event.clientX) + curWidth, curWidth);
if (CellElem && CellElem.colSpan) {
const td: HTMLElement = this.parent.getCell(activeCell[0], activeCell[1]);
(this.parent.element.querySelector('.e-active-cell') as HTMLElement).style.width = td.offsetWidth + 'px';
}
}
if (CellElem && CellElem.format && CellElem.format.indexOf('*') > -1) {
this.parent.notify(rowFillHandler, { cell: CellElem, value: CellElem.format[CellElem.format.indexOf('*') + 1].toString(),
rowIdx: activeCell[0], colIdx: activeCell[1] });
}
}
private resizeStart(idx: number, viewportIdx: number, value: string, isCol?: boolean, isFit?: boolean, prevData?: string): void {
setResize(idx, viewportIdx, value, isCol, this.parent);
const action: string = isFit ? 'resizeToFit' : 'resize';
let eventArgs: object;
let isAction: boolean;
if (isCol) {
eventArgs = { index: idx, width: value, isCol: isCol, sheetIndex: this.parent.activeSheetIndex, oldWidth: prevData };
isAction = prevData !== value;
} else {
eventArgs = { index: idx, height: value, isCol: isCol, sheetIndex: this.parent.activeSheetIndex, oldHeight: prevData };
isAction = prevData !== value;
}
if (isAction) {
this.parent.notify(completeAction, { eventArgs: eventArgs, action: action });
}
}
private updateCursor(): void {
if (this.parent.element.getElementsByClassName('e-colresize-handler')[0]) {
this.parent.element.classList.add('e-col-resizing');
} else if (this.parent.element.classList.contains('e-col-resizing')) {
this.parent.element.classList.remove('e-col-resizing');
}
if (this.parent.element.getElementsByClassName('e-rowresize-handler')[0]) {
this.parent.element.classList.add('e-row-resizing');
} else if (this.parent.element.classList.contains('e-row-resizing')) {
this.parent.element.classList.remove('e-row-resizing');
}
}
// To get the floating element width like filter
private getFloatingElementWidth(oldWidth: number, colIdx: number): number {
let floatingWidth: number = oldWidth;
const eventArgs: { [key: string]: number[] | boolean } = { filterRange: [], hasFilter: false };
this.parent.notify(getFilterRange, eventArgs);
if (eventArgs.hasFilter && eventArgs.filterRange) {
if (eventArgs.filterRange[1] <= colIdx && eventArgs.filterRange[3] >= colIdx) {
floatingWidth = oldWidth + 22; // default width and padding for button
}
}
return floatingWidth;
}
/**
* To destroy the resize module.
*
* @returns {void} - To destroy the resize module.
*/
public destroy(): void {
this.unwireEvents();
this.removeEventListener();
this.parent = null;
}
/**
* Get the module name.
*
* @returns {string} - Get the module name.
*/
protected getModuleName(): string {
return 'resize';
}
} | the_stack |
import { AuthInfo, Connection } from '@salesforce/core';
import { MockTestOrgData, testSetup } from '@salesforce/core/lib/testSetup';
import {
CancelResponse,
ContinueResponse
} from '@salesforce/salesforcedx-utils-vscode/out/src/types/index';
import {
ComponentSet,
registry,
SourceComponent
} from '@salesforce/source-deploy-retrieve';
import { expect } from 'chai';
import * as path from 'path';
import { createSandbox, SinonSandbox, SinonStub } from 'sinon';
import * as vscode from 'vscode';
import { channelService } from '../../../src/channels';
import {
LibraryRetrieveSourcePathExecutor,
SourcePathChecker
} from '../../../src/commands';
import * as forceSourceRetrieveSourcePath from '../../../src/commands/forceSourceRetrieveSourcePath';
import { workspaceContext } from '../../../src/context';
import { nls } from '../../../src/messages';
import { notificationService } from '../../../src/notifications';
import { SfdxPackageDirectories, SfdxProjectConfig } from '../../../src/sfdxProject';
import { getRootWorkspacePath } from '../../../src/util';
const sb = createSandbox();
const $$ = testSetup();
describe('Force Source Retrieve with Sourcepath Option', () => {
describe('Library Executor', () => {
let mockConnection: Connection;
let retrieveStub: SinonStub;
let pollStatusStub: SinonStub;
const defaultPackage = 'test-app';
beforeEach(async () => {
const testData = new MockTestOrgData();
$$.setConfigStubContents('AuthInfoConfig', {
contents: await testData.getConfig()
});
const authInfo = await AuthInfo.create({
username: testData.username
});
mockConnection = await Connection.create({
authInfo
});
sb.stub(workspaceContext, 'getConnection').resolves(mockConnection);
sb.stub(workspaceContext, 'username').get(() => testData.username);
sb.stub(SfdxPackageDirectories, 'getDefaultPackageDir').resolves(
defaultPackage
);
sb.stub(SfdxProjectConfig, 'getValue').resolves('11.0');
pollStatusStub = sb.stub();
});
afterEach(() => {
sb.restore();
});
it('should retrieve with a file path', async () => {
const executor = new LibraryRetrieveSourcePathExecutor();
const fsPath = path.join('layouts', 'MyLayout.layout-meta.xml');
const toRetrieve = new ComponentSet([
new SourceComponent({
name: 'MyLayout',
type: registry.types.layout,
xml: fsPath
})
]);
sb.stub(ComponentSet, 'fromSource')
.withArgs([fsPath])
.returns(toRetrieve);
retrieveStub = sb
.stub(toRetrieve, 'retrieve')
.returns({ pollStatus: pollStatusStub });
await executor.run({
type: 'CONTINUE',
data: [fsPath]
});
expect(retrieveStub.calledOnce).to.equal(true);
expect(retrieveStub.firstCall.args[0]).to.deep.equal({
usernameOrConnection: mockConnection,
output: path.join(getRootWorkspacePath(), defaultPackage),
merge: true
});
expect(pollStatusStub.calledOnce).to.equal(true);
});
it('componentSet has sourceApiVersion set', async () => {
const executor = new LibraryRetrieveSourcePathExecutor();
const data = path.join(getRootWorkspacePath(), 'force-app/main/default/classes/');
const continueResponse = {
type: 'CONTINUE',
data: [data]
} as ContinueResponse<string[]>;
const componentSet = executor.getComponents(continueResponse);
expect((await componentSet).sourceApiVersion).to.equal('11.0');
});
it('should retrieve multiple files', async () => {
const filePath1 = path.join('classes', 'MyClass1.cls');
const filePath2 = path.join('classes', 'MyClass2.cls');
const filePath3 = path.join('lwc', 'myBundle', 'myBundle');
const uris = [
vscode.Uri.file(filePath1),
vscode.Uri.file(filePath2),
vscode.Uri.file(filePath3)
];
const filePaths = uris.map(uri => {
return uri.fsPath;
});
const sourcePathCheckerCheckStub = sb.stub(
SourcePathChecker.prototype, 'check').returns({
type: 'CONTINUE',
data: filePaths
});
await forceSourceRetrieveSourcePath.forceSourceRetrieveSourcePaths(
uris[0],
uris
);
expect(sourcePathCheckerCheckStub.called).to.equal(true);
const continueResponse = sourcePathCheckerCheckStub.args[0][0] as ContinueResponse<string[]>;
expect(JSON.stringify(continueResponse.data)).to.equal(JSON.stringify(filePaths));
});
it('should retrieve a single file', async () => {
const filePath1 = path.join('classes', 'MyClass1.cls');
const uris = [
vscode.Uri.file(filePath1)
];
const filePaths = uris.map(uri => {
return uri.fsPath;
});
const sourcePathCheckerCheckStub = sb.stub(
SourcePathChecker.prototype, 'check').returns({
type: 'CONTINUE',
data: filePaths
});
await forceSourceRetrieveSourcePath.forceSourceRetrieveSourcePaths(
uris[0],
uris
);
expect(sourcePathCheckerCheckStub.called).to.equal(true);
const continueResponse = sourcePathCheckerCheckStub.args[0][0] as ContinueResponse<string[]>;
expect(JSON.stringify(continueResponse.data)).to.equal(JSON.stringify(filePaths));
});
it('should retrieve when editing a single file and "Retrieve This Source from Org" is executed', async () => {
const filePath1 = path.join('classes', 'MyClass1.cls');
const uris = [
vscode.Uri.file(filePath1)
];
const filePaths = uris.map(uri => {
return uri.fsPath;
});
const sourcePathCheckerCheckStub = sb.stub(
SourcePathChecker.prototype, 'check').returns({
type: 'CONTINUE',
data: filePaths
});
await forceSourceRetrieveSourcePath.forceSourceRetrieveSourcePaths(
uris[0],
undefined
);
expect(sourcePathCheckerCheckStub.called).to.equal(true);
const continueResponse = sourcePathCheckerCheckStub.args[0][0] as ContinueResponse<string[]>;
expect(JSON.stringify(continueResponse.data)).to.equal(JSON.stringify(filePaths));
});
it('should retrieve when using the command palette', async () => {
const filePath1 = path.join('classes', 'MyClass1.cls');
// When retrieving via the command palette,
// sourceUri is undefined, and uris is undefined as well,
// and the path is obtained from the active editor
// (and calling getUriFromActiveEditor())
const sourceUri = undefined;
const uris = undefined;
const filePaths = [ filePath1 ];
const sourcePathCheckerCheckStub = sb.stub(
SourcePathChecker.prototype, 'check').returns({
type: 'CONTINUE',
data: filePaths
});
const getUriFromActiveEditorStub = sb.stub(forceSourceRetrieveSourcePath, 'getUriFromActiveEditor').returns(filePath1);
await forceSourceRetrieveSourcePath.forceSourceRetrieveSourcePaths(
sourceUri,
uris
);
expect(getUriFromActiveEditorStub.called).to.equal(true);
});
});
});
describe('SourcePathChecker', () => {
let workspacePath: string;
let sandboxStub: SinonSandbox;
let appendLineSpy: SinonStub;
let showErrorMessageSpy: SinonStub;
beforeEach(() => {
sandboxStub = createSandbox();
workspacePath = getRootWorkspacePath();
appendLineSpy = sandboxStub.stub(channelService, 'appendLine');
showErrorMessageSpy = sandboxStub.stub(
notificationService,
'showErrorMessage'
);
});
afterEach(() => {
sandboxStub.restore();
});
it('Should continue when source path is in a package directory', async () => {
const isInPackageDirectoryStub = sandboxStub
.stub(SfdxPackageDirectories, 'isInPackageDirectory')
.returns(true);
const pathChecker = new SourcePathChecker();
const sourcePath = path.join(workspacePath, 'package');
const continueResponse = (await pathChecker.check({
type: 'CONTINUE',
data: [ sourcePath ]
})) as ContinueResponse<string[]>;
expect(isInPackageDirectoryStub.getCall(0).args[0]).to.equal(sourcePath);
expect(continueResponse.type).to.equal('CONTINUE');
expect(continueResponse.data[0]).to.equal(sourcePath);
isInPackageDirectoryStub.restore();
});
it('Should notify user and cancel when source path is not inside of a package directory', async () => {
const isInPackageDirectoryStub = sandboxStub
.stub(SfdxPackageDirectories, 'isInPackageDirectory')
.returns(false);
const pathChecker = new SourcePathChecker();
const cancelResponse = (await pathChecker.check({
type: 'CONTINUE',
data: [ path.join('not', 'in', 'package', 'directory') ]
})) as CancelResponse;
const errorMessage = nls.localize(
'error_source_path_not_in_package_directory_text'
);
expect(appendLineSpy.getCall(0).args[0]).to.equal(errorMessage);
expect(showErrorMessageSpy.getCall(0).args[0]).to.equal(errorMessage);
expect(cancelResponse.type).to.equal('CANCEL');
isInPackageDirectoryStub.restore();
});
it('Should cancel and notify user if an error occurs when fetching the package directories', async () => {
const isInPackageDirectoryStub = sandboxStub
.stub(SfdxPackageDirectories, 'isInPackageDirectory')
.throws(new Error());
const pathChecker = new SourcePathChecker();
const cancelResponse = (await pathChecker.check({
type: 'CONTINUE',
data: [ 'test/path' ]
})) as CancelResponse;
const errorMessage = nls.localize(
'error_source_path_not_in_package_directory_text'
);
expect(appendLineSpy.getCall(0).args[0]).to.equal(errorMessage);
expect(showErrorMessageSpy.getCall(0).args[0]).to.equal(errorMessage);
expect(cancelResponse.type).to.equal('CANCEL');
isInPackageDirectoryStub.restore();
});
}); | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import * as deploy_contracts from '../contracts';
import * as deploy_helpers from '../helpers';
import * as deploy_objects from '../objects';
import * as deploy_workspace from '../workspace';
import * as i18 from '../i18';
import * as Path from 'path';
import * as vscode from 'vscode';
/**
* Common "deploy" arguments.
*/
export interface DeployArguments extends deploy_contracts.ScriptArguments {
/**
* Indicates if operation has been canceled or not.
*/
canceled?: boolean;
/**
* The underlying deploy context.
*/
context: deploy_contracts.DeployContext;
/**
* The downloaded data.
*/
data?: Buffer;
/**
* Deploy options.
*/
deployOptions: deploy_contracts.DeployFileOptions;
/**
* The direction.
*/
direction: deploy_contracts.DeployDirection;
/**
* A state value for the ALL scripts that exists while the
* current session.
*/
globalState?: Object;
/**
* Opens a HTML document in a new tab.
*
* @param {string} html The HTML document (source code).
* @param {string} [title] The custom title for the tab.
* @param {any} [id] The custom ID for the document in the storage.
*
* @returns {Promise<any>} The promise.
*/
openHtml: (html: string, title?: string, id?: any) => Promise<any>;
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
replaceWithValues: (val: any) => string;
/**
* The underlying "parent" object.
*/
sender: any;
/**
* A state value for the current script that exists while the
* current session.
*/
state?: any;
/**
* The target.
*/
target: DeployTargetScript;
/**
* Options from the target configuration.
*/
targetOptions: any;
}
/**
* Arguments for deploying a file.
*/
export interface DeployFileArguments extends DeployArguments {
/**
* The file to deploy.
*/
file: string;
/**
* The property where to write the file info to.
*/
info: deploy_contracts.FileInfo;
/**
* Tells the extension that the underlying file
* IS BEING to be deployed.
* @param {string} [destination] An optional string, like a path or URL, where the file will be deployed.
*
* @return {boolean} Event has been raised or not.
*/
readonly onBeforeDeploy: (destination?: string) => boolean;
}
/**
* 'script' target settings.
*/
export interface DeployTargetScript extends deploy_contracts.DeployTarget {
/**
* The optional data to use in execution of script functions.
*/
options?: any;
/**
* The script to execute.
*/
script: string;
}
/**
* Arguments for deploying the workspace.
*/
export interface DeployWorkspaceArguments extends DeployArguments {
/**
* The list of files to deploy.
*/
files: string[];
/**
* Tells the extension that one of the files
* IS BEING to be deployed.
*
* @param {string} file The file name or its index inside 'files' property.
* @param {string} [destination] An optional string, like a path or URL, where the file will be deployed.
*
* @return {boolean} Event has been raised or not.
*/
readonly onBeforeDeployFile: (file: string | number, destination?: string) => boolean;
/**
* Tells the extension that one of the files
* HAS BEEN deployed or failed.
*
* @param {string} file The file name or its index inside 'files' property.
* @param {any} [err] The error (if occurred).
*
* @return {boolean} Event has been raised or not.
*/
readonly onFileCompleted: (file: string | number, err?: any) => boolean;
}
/**
* A script module.
*/
export interface ScriptModule {
/**
* Deploys a file.
*
* @param {DeployFileArguments} args Arguments for the execution.
*
* @return {void|Promise<DeployFileArguments>} The result.
*/
deployFile?: (args: DeployFileArguments) => void | Promise<DeployFileArguments>;
/**
* Deploys the workspace.
*
* @param {DeployWorkspaceArguments} args Arguments for the execution.
*
* @return {void|Promise<DeployWorkspaceArguments>} The result.
*/
deployWorkspace?: (args: DeployWorkspaceArguments) => void | Promise<DeployWorkspaceArguments>;
/**
* Pulls a file to the workspace.
*
* @param {DeployFileArguments} args Arguments for the execution.
*
* @return {void|Promise<DeployFileArguments>} The result.
*/
pullFile?: (args: DeployFileArguments) => void | Promise<DeployFileArguments>;
/**
* Pulls files to the workspace.
*
* @param {DeployWorkspaceArguments} args Arguments for the execution.
*
* @return {void|Promise<DeployWorkspaceArguments>} The result.
*/
pullWorkspace?: (args: DeployWorkspaceArguments) => void | Promise<DeployWorkspaceArguments>;
}
class ScriptPlugin extends deploy_objects.DeployPluginBase {
protected _globalState: Object = {};
protected _scriptStates: Object = {};
public get canGetFileInfo(): boolean {
return true;
}
public get canPull(): boolean {
return true;
}
public deployFile(file: string, target: DeployTargetScript, opts?: deploy_contracts.DeployFileOptions): void {
this.deployOrPullFile(deploy_contracts.DeployDirection.Deploy,
file, target, opts);
}
protected deployOrPullFile(direction: deploy_contracts.DeployDirection,
file: string, target: DeployTargetScript, opts?: deploy_contracts.DeployFileOptions): Promise<DeployFileArguments> {
if (!opts) {
opts = {};
}
let me = this;
return new Promise<DeployFileArguments>((resolve, reject) => {
let hasCancelled = false;
let completed = (err: any, args?: DeployFileArguments) => {
if (opts.onCompleted) {
opts.onCompleted(me, {
canceled: hasCancelled,
error: err,
file: file,
target: target,
});
}
if (err) {
reject(err);
}
else {
resolve(args);
}
};
me.onCancelling(() => hasCancelled = true, opts);
if (hasCancelled) {
completed(null); // cancellation requested
}
else {
try {
let scriptFile = getScriptFile(target, me);
let relativeScriptPath = deploy_helpers.toRelativePath(scriptFile, opts.baseDirectory);
if (false === relativeScriptPath) {
relativeScriptPath = scriptFile;
}
let scriptModule = loadScriptModule(scriptFile);
let scriptFunction: Function;
switch (direction) {
case deploy_contracts.DeployDirection.Pull:
scriptFunction = scriptModule['pullFile'] || scriptModule['deployFile'];
break;
default:
// deploy
scriptFunction = scriptModule['deployFile'] || scriptModule['pullFile'];
break;
}
if (!scriptFunction) {
throw new Error(i18.t('plugins.script.noDeployFileFunction', relativeScriptPath));
}
let allStates = me._scriptStates;
let info: deploy_contracts.FileInfo;
if (deploy_contracts.DeployDirection.Pull === direction) {
info = {
exists: false,
isRemote: true,
};
}
let args: DeployFileArguments = {
canceled: me.context.isCancelling(),
context: me.context,
deployOptions: opts,
direction: direction,
emitGlobal: function() {
return me.context
.emitGlobal
.apply(me.context, arguments);
},
file: file,
globals: me.context.globals(),
info: info,
onBeforeDeploy: (destination?) => {
if (opts.onBeforeDeploy) {
opts.onBeforeDeploy(me, {
destination: destination,
file: file,
target: target,
});
return true;
}
return false;
},
openHtml: function() {
return me.context.openHtml
.apply(me.context, arguments);
},
replaceWithValues: (v) => me.context.replaceWithValues(v),
require: function(id) {
return me.context.require(id);
},
sender: me,
target: target,
targetOptions: target.options,
};
// args.globalState
Object.defineProperty(args, 'globalState', {
enumerable: true,
get: () => {
return me._globalState;
},
});
// args.state
Object.defineProperty(args, 'state', {
enumerable: true,
get: () => {
return allStates[scriptFile];
},
set: (v) => {
allStates[scriptFile] = v;
},
});
args.context.once('deploy.cancel', function() {
if (false === args.canceled) {
args.canceled = true;
}
});
Promise.resolve(scriptFunction(args)).then((a: DeployFileArguments) => {
hasCancelled = (a || args).canceled;
completed(null, a || args);
}).catch((err) => {
if (!err) {
// define generic error message
err = new Error(i18.t('plugins.script.deployFileFailed', file, relativeScriptPath));
}
completed(err);
});
}
catch (e) {
completed(e);
}
}
});
}
public deployWorkspace(files: string[], target: DeployTargetScript, opts?: deploy_contracts.DeployWorkspaceOptions) {
this.deployOrPullWorkspace(deploy_contracts.DeployDirection.Deploy,
files, target, opts);
}
protected deployOrPullWorkspace(direction: deploy_contracts.DeployDirection,
files: string[], target: DeployTargetScript, opts?: deploy_contracts.DeployWorkspaceOptions): Promise<DeployWorkspaceArguments> {
let me = this;
if (!opts) {
opts = {};
}
return new Promise<DeployWorkspaceArguments>((resolve, reject) => {
let hasCancelled = false;
let completed = (err: any, args?: DeployWorkspaceArguments) => {
if (opts.onCompleted) {
opts.onCompleted(me, {
canceled: hasCancelled,
error: err,
target: target,
});
}
if (err) {
reject(err);
}
else {
resolve(args);
}
};
me.onCancelling(() => hasCancelled = true, opts);
if (hasCancelled) {
completed(null); // cancellation requested
}
else {
try {
let scriptFile = getScriptFile(target, me);
let relativeScriptPath = deploy_helpers.toRelativePath(scriptFile, opts.baseDirectory);
if (false === relativeScriptPath) {
relativeScriptPath = scriptFile;
}
let scriptModule = loadScriptModule(scriptFile);
let scriptFunction: Function;
switch (direction) {
case deploy_contracts.DeployDirection.Pull:
scriptFunction = scriptModule['pullWorkspace'] || scriptModule['deployWorkspace'];
break;
default:
// deploy
scriptFunction = scriptModule['deployWorkspace'] || scriptModule['pullWorkspace'];
break;
}
if (scriptFunction) {
// custom function
let allStates = me._scriptStates;
let args: DeployWorkspaceArguments = {
canceled: me.context.isCancelling(),
context: me.context,
deployOptions: opts,
direction: direction,
emitGlobal: function() {
return me.context
.emitGlobal
.apply(me.context, arguments);
},
files: files,
globals: me.context.globals(),
onBeforeDeployFile: function(fileOrIndex, destination?) {
if (opts.onBeforeDeployFile) {
if (deploy_helpers.isNullOrUndefined(fileOrIndex)) {
fileOrIndex = 0;
}
if ('string' !== typeof fileOrIndex) {
fileOrIndex = parseInt(deploy_helpers.toStringSafe(fileOrIndex).trim());
fileOrIndex = args.files[fileOrIndex];
}
opts.onBeforeDeployFile(me, {
destination: destination,
file: fileOrIndex,
target: target,
});
return true;
}
return false;
},
onFileCompleted: function(fileOrIndex, err?) {
if (opts.onFileCompleted) {
if (deploy_helpers.isNullOrUndefined(fileOrIndex)) {
fileOrIndex = 0;
}
if ('string' !== typeof fileOrIndex) {
fileOrIndex = parseInt(deploy_helpers.toStringSafe(fileOrIndex).trim());
fileOrIndex = args.files[fileOrIndex];
}
opts.onFileCompleted(me, {
canceled: args.canceled,
error: err,
file: fileOrIndex,
target: target,
});
return true;
}
return false;
},
openHtml: function() {
return me.context.openHtml
.apply(me.context, arguments);
},
replaceWithValues: (v) => me.context.replaceWithValues(v),
require: function(id) {
return me.context.require(id);
},
sender: me,
target: target,
targetOptions: target.options,
};
// args.globalState
Object.defineProperty(args, 'globalState', {
enumerable: true,
get: () => {
return me._globalState;
},
});
// args.state
Object.defineProperty(args, 'state', {
enumerable: true,
get: () => {
return allStates[scriptFile];
},
set: (v) => {
allStates[scriptFile] = v;
},
});
args.context.once('deploy.cancel', function() {
if (false === args.canceled) {
args.canceled = true;
}
});
Promise.resolve(scriptFunction(args)).then((a: DeployWorkspaceArguments) => {
hasCancelled = (a || args).canceled;
completed(null, a || args);
}).catch((err) => {
if (!err) {
// define generic error message
err = new Error(i18.t('plugins.script.deployWorkspaceFailed', relativeScriptPath));
}
completed(err);
});
}
else {
// use default
super.deployWorkspace(files, target, opts);
}
}
catch (e) {
completed(e);
}
}
});
}
public downloadFile(file: string, target: DeployTargetScript, opts?: deploy_contracts.DeployFileOptions): Promise<Buffer> {
let me = this;
return new Promise<Buffer>((resolve, reject) => {
me.deployOrPullFile(deploy_contracts.DeployDirection.Pull, file, target, opts).then((args) => {
resolve(args.data);
}).catch((err) => {
reject(err);
});
});
}
public getFileInfo(file: string, target: DeployTargetScript, opts?: deploy_contracts.DeployFileOptions): Promise<deploy_contracts.FileInfo> {
let me = this;
return new Promise<deploy_contracts.FileInfo>((resolve, reject) => {
me.deployOrPullFile(deploy_contracts.DeployDirection.FileInfo, file, target, opts).then((args) => {
resolve(args.info || {
exists: false,
isRemote: true,
});
}).catch((err) => {
reject(err);
});
});
}
public info(): deploy_contracts.DeployPluginInfo {
return {
description: i18.t('plugins.script.description'),
};
}
protected onConfigReloaded(cfg: deploy_contracts.DeployConfiguration) {
this._globalState = {};
this._scriptStates = {};
}
}
/**
* Creates a new Plugin.
*
* @param {deploy_contracts.DeployContext} ctx The deploy context.
*
* @returns {deploy_contracts.DeployPlugin} The new instance.
*/
export function createPlugin(ctx: deploy_contracts.DeployContext): deploy_contracts.DeployPlugin {
return new ScriptPlugin(ctx);
}
function getScriptFile(target: DeployTargetScript, plugin: ScriptPlugin): string {
let scriptFile = deploy_helpers.toStringSafe(target.script);
scriptFile = plugin.context.replaceWithValues(scriptFile);
if ('' === scriptFile.trim()) {
scriptFile = './deploy.js';
}
if (!Path.isAbsolute(scriptFile)) {
scriptFile = Path.join(deploy_workspace.getRootPath(), scriptFile);
}
return scriptFile;
}
function loadScriptModule(scriptFile: string): ScriptModule {
scriptFile = Path.resolve(scriptFile);
delete require.cache[scriptFile];
return require(scriptFile);
} | the_stack |
import Ambrosia = require("ambrosia-node");
import IC = Ambrosia.IC;
import Messages = Ambrosia.Messages;
import StringEncoding = Ambrosia.StringEncoding;
import Utils = Ambrosia.Utils;
import * as PublishedAPI from "./ConsumerInterface.g"; // This is a generated file
import * as Framework from "./PublisherFramework.g"; // This is a generated file [only needed to support code upgrade]
const PAYLOAD_FILL_BYTE: number = 170; // 170 = 10101010
const ONE_MB: number = 1024 * 1024
const ONE_GB: number = ONE_MB * 1024;
const ONE_HUNDRED_MB: number = ONE_MB * 100;
const CLIENT_START_TIMESTAMP_LENGTH: number = 7; // One byte for each digit pair in the client original start timestamp ([YY][YY][MM][DD][HH][MM][SS])
let _healthTimer: NodeJS.Timer;
/** The roles that the local instance can act as in the test. */
export enum InstanceRoles
{
/** The local instance is acting as a client in the test (there can be more than one client, but only when there is an instance running the 'Server' role). */
Client,
/** The local instance is acting as the server in the test (there can only be one server). */
Server,
/**
* The local instance is acting as **both** the client and the server in the test. This is the simplest way
* to run the test. In this role, additional clients should not target this instance as their server.
*/
Combined
}
/** Namespace for application state. */
export namespace State
{
export class AppState extends Ambrosia.AmbrosiaAppState
{
// Server-side state:
/** The total number of bytes [from the doWork() message payload] received since the server started running. */
bytesReceived: number = 0;
/** The total number of doWork() calls received since the server started running. */
numCalls: number = 0;
/** The call number from the previously received doWork() call (for a given client). */
lastCallNum: { [clientName: string]: number } = {};
/** The total number of times the checkHealth() method has been called. */
checkHealthCallNumber: number = 0;
/** When true, disables the periodic server health check (requested via an impulse message). */
noHealthCheck: boolean = false;
/** When true, enables echoing the 'doWork' method call back to the client(s). */
bidirectional: boolean = false;
/** The total number of bytes expected to be received from all clients. The server will report a "success" message when this number of bytes have been received. */
expectedFinalBytesTotal: number = 0
// Client-side state:
/** The name of the instance that's acting in the 'Server' role for the test. */
serverInstanceName: string = "";
/** The total number of [variable sized] message payload bytes that will be sent in a single round. */
bytesPerRound: number = 0;
/** Once the total number of [variable sized] message payload bytes queued reaches (or exceeds) this limit, then the batch will be sent. */
batchSizeCutoff: number = 0;
/** The maximum size (in bytes) of the message payload; should be a power of 2 (eg. 65536), and be at least 64. */
maxMessageSize: number = 0;
/** The requested number of rounds (of size bytesPerRound). */
numRounds: number = 0;
/** The number of rounds (of size bytesPerRound) still left to process. */
numRoundsLeft: number = 0;
/** How far through the current round the client is (as a percentage). */
lastRoundCompletionPercentage: number = 0;
/** When true, disables descending (halving) message size; instead, a random [power of 2] size between 64 and maxMessageSize will be used. */
useDescendingSize: boolean = false;
/** When true, all messages (in all rounds) will be of size maxMessageSize and useDescendingSize will be ignored. */
useFixedMessageSize: boolean = false;
/** The call number of the last 'doWork' call sent. */
callNum: number = 0;
/** The total number of bytes [from the doWorkEcho() message payload] received since the client started running. */
echoedBytesReceived: number = 0
/** The call number from the previously received doWorkEcho() call. */
echoedLastCallNum: number = 0;
/** The total number of bytes [from the doWorkEcho() message payload] expected to be received from the server. The client will report a "success" message when this number of bytes have been received. */
expectedEchoedBytesTotal: number = 0;
/** The date/time when the client was originally started. This will never change (once set). */
originalStartDate: number = 0;
/** Whether to include a post method call in the test. */
includePostMethod: boolean = false;
/** The number of times the post method result handler (for 'incrementValue') has been called. */
postMethodResultCount: number = 0;
/** The result received by the previously called post method result handler (for 'incrementValue'). */
lastPostMethodResultValue: number = 1;
// Common state:
/** The role of this instance in the test. */
instanceRole: InstanceRoles = InstanceRoles.Combined;
/** Optional 'Padding' used to simulate large checkpoints. Each member of the array will be no larger than 100MB. */
checkpointPadding?: Array<Uint8Array>;
/** The prefix to use when writing to the output log [this is only used to test upgrade]. */
loggingPrefix: string = "";
/** Whether to check the doWork() / doWorkEcho() payload fill bytes. */
verifyPayload: boolean = false;
/** Whether the local instance is acting in the 'Server' role for the test. */
get isServer(): boolean
{
return ((this.instanceRole === InstanceRoles.Server) || (this.instanceRole === InstanceRoles.Combined));
}
/** Whether the local instance is acting in the 'Client' role for the test. */
get isClient(): boolean
{
return ((this.instanceRole === InstanceRoles.Client) || (this.instanceRole === InstanceRoles.Combined));
}
/**
* @param restoredAppState Supplied only when loading (restoring) a checkpoint, or (for a "VNext" AppState) when upgrading from the prior AppState.\
* **WARNING:** When loading a checkpoint, restoredAppState will be an object literal, so you must use this to reinstantiate any members that are (or contain) class references.
*/
constructor(restoredAppState?: AppState)
{
super(restoredAppState);
if (restoredAppState)
{
// WARNING: You MUST reinstantiate all members that are (or contain) class references because restoredAppState is data-only
// Server-side state:
this.bytesReceived = restoredAppState.bytesReceived;
this.numCalls = restoredAppState.numCalls;
this.lastCallNum = restoredAppState.lastCallNum;
this.checkHealthCallNumber = restoredAppState.checkHealthCallNumber;
this.noHealthCheck = restoredAppState.noHealthCheck;
this.bidirectional = restoredAppState.bidirectional;
this.expectedFinalBytesTotal = restoredAppState.expectedFinalBytesTotal;
// Client-side state:
this.serverInstanceName = restoredAppState.serverInstanceName;
this.bytesPerRound = restoredAppState.bytesPerRound;
this.batchSizeCutoff = restoredAppState.batchSizeCutoff;
this.maxMessageSize = restoredAppState.maxMessageSize;
this.numRounds = restoredAppState.numRounds;
this.numRoundsLeft = restoredAppState.numRoundsLeft;
this.lastRoundCompletionPercentage = restoredAppState.lastRoundCompletionPercentage;
this.useDescendingSize = restoredAppState.useDescendingSize;
this.useFixedMessageSize = restoredAppState.useFixedMessageSize;
this.callNum = restoredAppState.callNum;
this.echoedBytesReceived = restoredAppState.echoedBytesReceived;
this.echoedLastCallNum = restoredAppState.echoedLastCallNum;
this.expectedEchoedBytesTotal = restoredAppState.expectedEchoedBytesTotal;
this.originalStartDate = restoredAppState.originalStartDate;
if (restoredAppState["includePostMethod"] !== undefined) // So that we can still load older PTI checkpoints
{
this.includePostMethod = restoredAppState.includePostMethod;
}
if (restoredAppState["postMethodResultCount"] !== undefined) // So that we can still load older PTI checkpoints
{
this.postMethodResultCount = restoredAppState.postMethodResultCount;
}
if (restoredAppState["lastPostMethodResultValue"] !== undefined) // So that we can still load older PTI checkpoints
{
this.lastPostMethodResultValue = restoredAppState.lastPostMethodResultValue;
}
// Common state:
this.instanceRole = restoredAppState.instanceRole;
this.checkpointPadding = restoredAppState.checkpointPadding;
this.loggingPrefix = restoredAppState.loggingPrefix;
if (restoredAppState["verifyPayload"] !== undefined) // So that we can still load older PTI checkpoints
{
this.verifyPayload = restoredAppState.verifyPayload;
}
}
else
{
// Initialize application state
this.originalStartDate = Date.now();
}
}
convert(): AppStateV2
{
return (AppStateV2.fromPriorAppState(this));
}
}
/** Class representing upgraded application state. */
export class AppStateV2 extends AppState
{
/**
* @param restoredAppState Supplied only when loading (restoring) a checkpoint, or (for a "VNext" AppState) when upgrading from the prior AppState.\
* **WARNING:** When loading a checkpoint, restoredAppState will be an object literal, so you must use this to reinstantiate any members that are (or contain) class references.
*/
constructor(restoredAppState?: AppStateV2)
{
super(restoredAppState);
}
/** Factory method that creates a new AppStateV2 instance from an existing AppState instance. Called [once] during upgrade. */
static fromPriorAppState(priorAppState: AppState): AppStateV2
{
// It's sufficient to simply pass priorAppState as the 'restoredAppState' because AppStateV2 has exactly the same shape as AppState
const appStateV2: AppStateV2 = new AppStateV2(priorAppState);
// Upgrading, so transform (as needed) the supplied old state, and - if needed - [re]initialize the new state
appStateV2.loggingPrefix = "VNext";
return (appStateV2);
}
}
/**
* Only assign this using the return value of IC.start(), the return value of the upgrade() method of your AmbrosiaAppState
* instance, and [if not using the generated checkpointConsumer()] in the 'onFinished' callback of an IncomingCheckpoint object.
*/
export let _appState: AppState | AppStateV2;
}
/** Logs the specified message (regardless of the configured 'outputLoggingLevel'). */
export function log(message: string)
{
Utils.log(message, State._appState?.loggingPrefix, Utils.LoggingLevel.Minimal);
}
/** Namespace for the "server-side" published methods. */
export namespace ServerAPI
{
/**
* A method whose purpose is to update _appState with each call.
* @param rawParams A custom serialized byte array of all method parameters.
* @ambrosia publish=true, methodID=1
*/
export function doWork(rawParams: Uint8Array): void
{
const buffer: Buffer = Buffer.from(rawParams.buffer);
const currCallNum: number = buffer.readUInt32LE(0); // This changes with every message
const clientNameLength: number = buffer[4];
const clientName: string = StringEncoding.fromUTF8Bytes(buffer, 5, clientNameLength);
if (!State._appState.lastCallNum[clientName])
{
State._appState.lastCallNum[clientName] = 0;
}
const expectedCallNum: number = State._appState.lastCallNum[clientName] + 1;
if (currCallNum !== expectedCallNum)
{
log(`Error: Out of order message from '${clientName}' (expected ${expectedCallNum}, got ${currCallNum})`);
}
if (State._appState.verifyPayload)
{
verifyPayloadBytes(buffer, 4 + 1 + clientNameLength + CLIENT_START_TIMESTAMP_LENGTH);
}
State._appState.lastCallNum[clientName] = currCallNum;
State._appState.bytesReceived += rawParams.length;
State._appState.numCalls++;
// const previous100MBReceived: number = Math.floor((State._appState.bytesReceived - rawParams.length) / ONE_HUNDRED_MB);
// const current100MBReceived: number = Math.floor(State._appState.bytesReceived / ONE_HUNDRED_MB);
// if (current100MBReceived !== previous100MBReceived)
// {
// log(`Service received ${current100MBReceived * 100} MB so far`);
// }
const previousGBReceived: number = Math.floor((State._appState.bytesReceived - rawParams.length) / ONE_GB);
const currentGBReceived: number = Math.floor(State._appState.bytesReceived / ONE_GB);
if (currentGBReceived !== previousGBReceived)
{
log(`Service received ${currentGBReceived * 1024} MB so far`);
}
if (State._appState.bidirectional)
{
// Note: Because the doWork() messages get delivered to the server in RPCBatch messages, and because processLogPage() processes all
// RPC messages in a batch at once, this means we'll get implicit batching behavior for all our outgoing doWorkEcho() calls.
// This can be verified with: log(`DEBUG: QueueLength = ${IC.queueLength()}`);
PublishedAPI.setDestinationInstance(clientName);
PublishedAPI.ClientAPI.doWorkEcho_Fork(rawParams);
}
}
/**
* A method that reports (to the console) the current application state.
* @ambrosia publish=true, methodID=2
*/
export function reportState(isFinalState: boolean): void
{
if (isFinalState)
{
log(`Bytes received: ${State._appState.bytesReceived}`); // This text is looked for by the test harness
log("DONE"); // This text is looked for by the test harness
if (State._appState.isServer && (State._appState.bytesReceived === State._appState.expectedFinalBytesTotal))
{
log(`SUCCESS: The expected number of bytes (${State._appState.expectedFinalBytesTotal}) have been received`); // This text is looked for by the test harness
}
if (State._appState.instanceRole === InstanceRoles.Combined)
{
if (!State._appState.bidirectional)
{
// Stop the Combined instance
stopCombinedInstance();
}
else
{
// Let the final doWorkEcho() [which will arrive later] stop the Combined instance
}
}
}
else
{
log(`numCalls: ${State._appState.numCalls}, bytesReceived: ${State._appState.bytesReceived}`);
}
}
/**
* A method whose purpose is [mainly] to be a rapidly occurring Impulse method to test if this causes issues for recovery.\
* Also periodically (eg. every ~5 seconds) reports that the Server is still running.
* @ambrosia publish=true, methodID=3
*/
export function checkHealth(currentTime: number): void
{
if (++State._appState.checkHealthCallNumber % 200 === 0) // Every ~5 seconds [if checkHealth() is called every 25ms]
{
log(`Service healthy after ${State._appState.checkHealthCallNumber} checks at ${Utils.getTime(currentTime)}`);
}
}
/**
* A simple post method. Returns the supplied value incremented by 1.
* @ambrosia publish=true
*/
export function incrementValue(value: number): number
{
return (value + 1);
}
}
/** Stops the Combined instance, after waiting (but only in the case of --includePostMethod) for any queued outgoing messages. */
function stopCombinedInstance(isRetry: boolean = false): void
{
if (State._appState.instanceRole === InstanceRoles.Combined)
{
if (State._appState.includePostMethod)
{
const queueLength: number = IC.queueLength();
const inFlightMethodCount: number = IC.inFlightPostMethodsCount();
if ((queueLength > 0) || (inFlightMethodCount > 0))
{
log(`Waiting for ${IC.queueLength()} outgoing messages and ${IC.inFlightPostMethodsCount()} in-flight post methods...`);
setTimeout(() => stopCombinedInstance(true), 200);
return;
}
else
{
if (isRetry)
{
log(`Outgoing message queue is empty; there are no in-flight post methods`);
}
checkFinalPostMethod();
IC.stop();
}
}
else
{
IC.stop();
}
}
}
/** For a client, checks that the final 'incrementValue' post method result received was for the final 'doWork' message. */
function checkFinalPostMethod(): void
{
if (State._appState.isClient && State._appState.includePostMethod)
{
const inFlightMethodsCount: number = IC.inFlightPostMethodsCount();
if (inFlightMethodsCount > 0)
{
log(`Waiting for ${IC.inFlightPostMethodsCount()} in-flight post methods...`);
setTimeout(checkFinalPostMethod, 200);
return;
}
else
{
const finalCallNum: number = State._appState.callNum;
if (State._appState.postMethodResultCount !== State._appState.callNum)
{
throw new Error(`The result handler for the 'incrementValue' post method was not called the expected number of times (expected ${State._appState.callNum}, but it was called ${State._appState.postMethodResultCount} times)`);
}
log(`SUCCESS: The result handler for the 'incrementValue' post method was called the expected number of times (${State._appState.callNum})`);
}
}
}
/** Throws if the byte values in buffer (starting from startPos) are not all PAYLOAD_FILL_BYTE and stops the process. */
function verifyPayloadBytes(buffer: Buffer, startPos: number): void
{
try
{
for (let pos = startPos; pos < buffer.length; pos++)
{
if (buffer[pos] !== PAYLOAD_FILL_BYTE)
{
const displayBytes: string = Utils.makeDisplayBytes(buffer, pos, 64);
throw new Error(`PTI message payload is corrupt: Byte at position ${pos} (of ${buffer.length}) is ${buffer[pos]}, not ${PAYLOAD_FILL_BYTE} as expected [corrupted fragment: ${displayBytes}]`);
}
}
}
catch (error: unknown)
{
Utils.log(Utils.makeError(error));
process.exit(-1); // Hard-stop [otherwise the Immortal will keep running, but reporting many "Out of order message" errors until the round completes]
}
}
/** Returns the supplied date as an array of bytes, with one byte for each digit pair in [YY][YY][MM][DD][HH][MM][SS]. */
function makeTimestampBytes(date: number): Uint8Array
{
// Note: If you change the number of bytes in the timestamp, you MUST also change CLIENT_RUN_TIMESTAMP_LENGTH.
const runDate: Date = new Date(date);
const millennia: number = Math.floor(runDate.getFullYear() / 1000);
const century: number = Math.floor((runDate.getFullYear() - (1000 * millennia)) / 100);
const decade: number = Math.floor((runDate.getFullYear() - (1000 * millennia) - (100 * century)) / 10);
const year: number = runDate.getFullYear() - (1000 * millennia) - (100 * century) - (10 * decade);
const timestampBytes: Uint8Array = new Uint8Array([(millennia * 10) + century, (decade * 10) + year, runDate.getMonth() + 1, runDate.getDate(), runDate.getHours(), runDate.getMinutes(), runDate.getSeconds()]);
return (timestampBytes);
}
/** Namespace for the "client-side" published methods. */
export namespace ClientAPI
{
/** UTF-8 bytes representing the name of the client instance. These bytes will be added to the 'doWork' message payload (along with the call number). */
export let clientNameBytes: Uint8Array; // We "cache" this for speed
/** A byte array representing the timestamp of the original start time of the client, with one byte for each digit pair in [YY][YY][MM][DD][HH][MM][SS]. */
export let originalStartTimestampBytes: Uint8Array; // We "cache" this for speed
/**
* Builds a batch of messages (each of size 'numRPCBytes') until the batch contains at least State._appState.batchSizeCutoff bytes. The batch is then sent.\
* This continues until a total of State._appState.bytesPerRound have been sent.\
* With the round complete, numRPCBytes is adjusted, then the whole cycle repeats until State._appState.numRoundsLeft reaches 0.
* @ambrosia publish=true, methodID=4
*/
export function continueSendingMessages(numRPCBytes: number, iterationWithinRound: number, startTimeOfRound: number): void
{
let bytesSentInCurrentBatch: number = 0;
let isTailOfPriorRoundACompleteBatch: boolean = false; // Note: A batch can span 2 rounds (ie. the final partial batch of round n can be flushed as part of first batch of round n+1)
for (; State._appState.numRoundsLeft > 0; State._appState.numRoundsLeft--)
{
const iterations = State._appState.bytesPerRound / numRPCBytes; // Our parameter validation ensures this will always be an integer
const buffer: Buffer = Buffer.alloc(numRPCBytes);
buffer.fill(PAYLOAD_FILL_BYTE); // Completely fill the buffer with non-zero values (170 = 10101010)
if (!isTailOfPriorRoundACompleteBatch)
{
if (iterationWithinRound === 0)
{
// A new round is starting
log(`Starting new round (with ${State._appState.numRoundsLeft} round${State._appState.numRoundsLeft === 1 ? "" : "s"} left) of ${iterations} messages of ${numRPCBytes} bytes each (${(State._appState.bytesPerRound / ONE_MB).toFixed((State._appState.bytesPerRound < 16384) ? 6 : 2)} MB/round)`);
startTimeOfRound = Date.now();
}
else
{
// log(`Continuing round (${iterationWithinRound} messages sent, ${iterations - iterationWithinRound} messages remain)...`);
}
}
else
{
// The "tail" of the prior round was a complete batch (ie. contained batchSizeCutoff bytes [or contained a single message larger than batchSizeCutoff]).
// In this case, the bytesSentInCurrentBatch (which were actually sent as the final batch of the prior round) will equal [or exceed] batchSizeCutoff,
// so the "iterationWithinRound" loop below will immediately "recurse" to start the "real" next round.
}
// Send message batch
for (; iterationWithinRound < iterations; iterationWithinRound++)
{
if (bytesSentInCurrentBatch >= State._appState.batchSizeCutoff)
{
PublishedAPI.setDestinationInstance(IC.instanceName());
PublishedAPI.ClientAPI.continueSendingMessages_EnqueueFork(numRPCBytes, iterationWithinRound, startTimeOfRound); // "Recurse" to continue (or complete) the round
// PublishedAPI.setDestinationInstance(State._appState.serverInstanceName);
// PublishedAPI.ServerAPI.reportState_EnqueueFork(false);
IC.flushQueue();
// Report client's progress through round [but only as we cross each 10% completion boundary]
const percentInterval: number = 10; // Report at every 10%
const currentRound: number = (State._appState.numRounds - State._appState.numRoundsLeft) + 1;
const roundCompletionPercentage: number = (iterationWithinRound / iterations) * 100;
const isTenPercentBoundaryCrossed: boolean = Math.floor(roundCompletionPercentage / percentInterval) > Math.floor(State._appState.lastRoundCompletionPercentage / percentInterval);
if (isTenPercentBoundaryCrossed)
{
log(`Client is ${Math.floor(roundCompletionPercentage)}% through round #${currentRound}`);
}
State._appState.lastRoundCompletionPercentage = roundCompletionPercentage;
return;
}
buffer.writeUInt32LE(++State._appState.callNum, 0); // Set (overwrite) the first 4 bytes to the callNum
buffer[4] = clientNameBytes.length;
buffer.set(clientNameBytes, 5);
buffer.set(originalStartTimestampBytes, 5 + clientNameBytes.length);
PublishedAPI.setDestinationInstance(State._appState.serverInstanceName);
PublishedAPI.ServerAPI.doWork_EnqueueFork(buffer);
bytesSentInCurrentBatch += numRPCBytes;
if (State._appState.includePostMethod)
{
PublishedAPI.ServerAPI.incrementValue_Post(State._appState.callNum + 1, State._appState.callNum);
}
}
// The round has ended...
if (State._appState.numRoundsLeft === 1)
{
// We're at the end of the final round, so we need to flush the partial final batch.
// Note: In the case of "(bytesPerRound % batchSizeCutoff) == 0", then the "partial final batch" will actually be a complete batch.
IC.flushQueue();
}
else
{
// We let the first batch of the next round flush the "tail" (ie. the partial [or complete] final batch) of the current round.
// Note: In the case of "(bytesPerRound % batchSizeCutoff) == 0", then the "partial final batch" will actually be a complete batch.
// Further, if batchSizeCutoff is less than the message size (numRPCBytes) then the "partial final batch" is also a complete batch (since each batch consists of a single message).
// Note: Because a batch can span rounds, it can contain messages of 2 different sizes.
isTailOfPriorRoundACompleteBatch = (bytesSentInCurrentBatch === State._appState.batchSizeCutoff) || (State._appState.batchSizeCutoff < numRPCBytes);
}
// Report throughput
const endTimeOfRound: number = Date.now();
const roundDurationInMs: number = Math.max(1, endTimeOfRound - startTimeOfRound); // Don't allow a duration of 0ms since this results in all xxxPerSecond values being "Infinity"
const numberOfBytesSent: number = iterations * numRPCBytes;
const numberOfGigabytesSent: number = numberOfBytesSent / ONE_GB;
const gigabytesPerSecond: number = numberOfGigabytesSent / (roundDurationInMs / 1000);
const messagesPerSecond: number = (iterations / roundDurationInMs) * 1000; // Note: This excludes the 'continueSendingMessages' message [which is an "overhead" message]
log(`Round complete (${messagesPerSecond.toFixed(2)} messages/sec, ${(gigabytesPerSecond * 1024).toFixed(2)} MB/sec, ${gigabytesPerSecond.toFixed(8)} GB/sec)`);
// Prepare for the next round
iterationWithinRound = 0;
State._appState.lastRoundCompletionPercentage = 0;
if (!State._appState.useFixedMessageSize)
{
if (State._appState.useDescendingSize)
{
// Halve the message size (but not below 64 bytes)
if (numRPCBytes > 64)
{
numRPCBytes >>= 1;
}
}
else
{
// Use a random message size between 64 and maxMessageSize
const minPower2: number = 6;
const maxPower2: number = Math.log2(State._appState.maxMessageSize);
const randomPower2: number = minPower2 + Math.floor((Math.random() * 100) % ((maxPower2 - minPower2) + 1)); // 100 is just a value that will always be greater than (maxPower2 - minPower2) + 1)
numRPCBytes = 1 << randomPower2;
}
}
if (State._appState.numRoundsLeft > 1)
{
PublishedAPI.setDestinationInstance(State._appState.serverInstanceName);
PublishedAPI.ServerAPI.reportState_Fork(false);
}
}
// All rounds have ended
log(`All rounds complete (${State._appState.callNum} messages sent)`); // This text is looked for by the test harness
if (_healthTimer)
{
clearTimeout(_healthTimer)
};
PublishedAPI.setDestinationInstance(State._appState.serverInstanceName);
PublishedAPI.ServerAPI.reportState_Fork(true);
if ((State._appState.instanceRole === InstanceRoles.Client) && State._appState.includePostMethod)
{
checkFinalPostMethod();
}
}
let _noMoreEchoCallsExpected: boolean = false;
/**
* A client method whose purpose is simply to be called [by the server] as an "echo" of the doWork() call sent to the server [by the client].
* @param rawParams A custom serialized byte array of all method parameters.
* @ambrosia publish=true, methodID=5
*/
// Note: The equivalent method in C# PTI is MAsync() in C:\src\git\AMBROSIA\InternalImmortals\PerformanceTestInterruptible\Client\Program.cs
export function doWorkEcho(rawParams: Uint8Array): void
{
const buffer: Buffer = Buffer.from(rawParams.buffer);
const currCallNum: number = buffer.readUInt32LE(0); // This changes with every message
const expectedCallNum: number = State._appState.echoedLastCallNum + 1;
if (currCallNum !== expectedCallNum)
{
log(`Error: Out of order echoed message (expected ${expectedCallNum}, got ${currCallNum})`);
}
if (State._appState.verifyPayload)
{
verifyPayloadBytes(buffer, 4 + 1 + clientNameBytes.length + CLIENT_START_TIMESTAMP_LENGTH);
}
if (_noMoreEchoCallsExpected)
{
log(`Error: doWorkEcho() called (call #${currCallNum} with ${rawParams.length} bytes) after receiving all expected echoed bytes (${State._appState.expectedEchoedBytesTotal})`);
}
State._appState.echoedLastCallNum = currCallNum;
State._appState.echoedBytesReceived += rawParams.length;
const previousGBReceived: number = Math.floor((State._appState.echoedBytesReceived - rawParams.length) / ONE_GB);
const currentGBReceived: number = Math.floor(State._appState.echoedBytesReceived / ONE_GB);
if (currentGBReceived !== previousGBReceived)
{
log(`Client received ${currentGBReceived * 1024} MB so far`);
}
if (State._appState.echoedBytesReceived === State._appState.expectedEchoedBytesTotal)
{
log(`SUCCESS: The expected number of echoed bytes (${State._appState.expectedEchoedBytesTotal}) have been received`); // This text is looked for by the test harness
_noMoreEchoCallsExpected = true;
if (State._appState.instanceRole === InstanceRoles.Combined)
{
// Stop the Combined instance
stopCombinedInstance();
}
}
}
}
/** Namespace for Ambrosia AppEvent handlers. */
export namespace EventHandlers
{
export function onICConnected(): void
{
// We don't check State._appState.isClient here because it's not reliable [yet] - it could change after a checkpoint is loaded.
// Instead, we just always set ClientAPI.clientNameBytes (it's benign to set it if we're the server).
ClientAPI.clientNameBytes = StringEncoding.toUTF8Bytes(IC.instanceName());
}
export function onFirstStart(): void
{
log(`${IC.instanceName()} in entry point`);
if (State._appState.isClient)
{
ClientAPI.originalStartTimestampBytes = makeTimestampBytes(State._appState.originalStartDate);
log(`Client original start date: ${Utils.makeDisplayBytes(ClientAPI.originalStartTimestampBytes)}`)
PublishedAPI.setDestinationInstance(IC.instanceName());
PublishedAPI.ClientAPI.continueSendingMessages_Fork(State._appState.maxMessageSize, 0, Date.now());
}
}
export function onBecomingPrimary(): void
{
log(`Becoming primary`);
if (State._appState.isServer && !State._appState.noHealthCheck)
{
_healthTimer = setInterval(() =>
{
PublishedAPI.setDestinationInstance(State._appState.serverInstanceName);
PublishedAPI.ServerAPI.checkHealth_Impulse(Date.now());
}, 25); // Nominally ~40 per second, in reality closer to ~28 per second (ie. every ~35ms)
}
}
export function onRecoveryComplete(): void
{
if (State._appState.callNum > 0)
{
log(`Recovery complete: Resuming test at call #${State._appState.callNum + 1}`);
}
}
export function onCheckpointLoaded(checkpointSizeInBytes: number): void
{
const roleStateInfo: string = State._appState.isClient ? `Last call #${State._appState.callNum}` : `${State._appState.numCalls} calls received`;
log(`Checkpoint loaded (${checkpointSizeInBytes} bytes): ${roleStateInfo}`);
if (State._appState.isClient)
{
ClientAPI.originalStartTimestampBytes = makeTimestampBytes(State._appState.originalStartDate);
log(`Client original start date: ${Utils.makeDisplayBytes(ClientAPI.originalStartTimestampBytes)}`)
}
}
export function onCheckpointSaved(): void
{
const roleStateInfo: string = State._appState.isClient ? `Last call #${State._appState.callNum}` : `${State._appState.numCalls} calls received`;
log(`Checkpoint saved: ${roleStateInfo}`);
}
export function onUpgradeState(upgradeMode: Messages.AppUpgradeMode)
{
State._appState = State._appState.upgrade<State.AppStateV2>(State.AppStateV2);
}
export function onUpgradeCode(upgradeMode: Messages.AppUpgradeMode)
{
IC.upgrade(Framework.messageDispatcher, Framework.checkpointProducer, Framework.checkpointConsumer); // A no-op code upgrade
}
export function onUpgradeComplete(): void
{
log(`Successfully upgraded!`); // This should be logged as "VNext: Successfully upgraded!"
}
} | the_stack |
import * as THREE from 'three';
import {cloneDeep} from 'lodash';
import {getObjectName} from '../ui/editor/DebugData';
import {createBoundingBox} from '../utils/rendering';
import { getParams } from '../params';
import assert from 'assert';
export const ZONE_TYPE = [
'TELEPORT',
'CAMERA',
'SCENERIC',
'FRAGMENT',
'BONUS',
'TEXT',
'LADDER',
'CONVEYOR',
'SPIKE',
'RAIL'
];
const ZONE_TYPE_MATERIAL_COLOR = [
'#84ff84', // TELEPORT
'#ff7448', // CAMERA
'#6495ed', // SCENERIC
'#ff00ff', // FRAGMENT
'#e7b5d6', // BONUS
'#ffb200', // TEXT
'#5555ff', // LADDER
'#96c09f', // CONVEYOR
'#ffc475', // SPIKE
'#008000', // RAIL
];
export enum ZoneType {
TELEPORT = 0,
CAMERA = 1,
SCENERIC = 2,
FRAGMENT = 3,
BONUS = 4,
TEXT = 5,
LADDER = 6,
CONVEYOR = 7,
SPIKE = 8,
RAIL = 9,
}
export interface ZoneProps {
sceneIndex: number;
index: number;
type: ZoneType;
pos: number[];
param: number;
info0: number; // Camera X. Bonus type. Fragment number. Ladder/rail on/off. Text color.
info1: number; // Camera Y. Bonus quantity. Conveyor on/off. Spike damage. Text camera.
info2: number; // Camera Z. Fragment on/off. Conveyor dir. Spike rearm time. Text side.
info3: number; // Camera alpha. Teleport beta.
info4: number; // Camera beta. Teleport destination scene.
info5: number; // Camera gamma.
info6: number; // Camera distance.
info7: number; // Camera on/off/force. Teleport on/off.
box: {
xMin: number;
yMin: number;
zMin: number;
xMax: number;
yMax: number;
zMax: number;
};
}
export default class Zone {
readonly type = 'zone';
readonly zoneType: string;
readonly props: ZoneProps;
readonly color: THREE.Color;
readonly physics: {
position: THREE.Vector3;
};
readonly threeObject: THREE.Object3D;
readonly boundingBox: THREE.Box3;
readonly index: number;
private labelCanvas: HTMLCanvasElement;
private labelCtx: CanvasRenderingContext2D;
private labelTexture: THREE.CanvasTexture;
private icon: HTMLImageElement;
private name: string;
protected constructor(props: ZoneProps, is3DCam: boolean) {
this.index = props.index;
this.zoneType = ZONE_TYPE[props.type];
this.props = cloneDeep(props);
this.color = new THREE.Color(ZONE_TYPE_MATERIAL_COLOR[props.type]);
this.physics = {
position: new THREE.Vector3(props.pos[0], props.pos[1], props.pos[2])
};
const {xMin, yMin, zMin, xMax, yMax, zMax} = props.box;
const bb = new THREE.Box3(
new THREE.Vector3(xMin, yMin, zMin),
new THREE.Vector3(xMax, yMax, zMax)
);
if (getParams().editor) {
const bbGeom = createBoundingBox(bb, this.color);
this.name = getObjectName('zone', props.sceneIndex, props.index);
bbGeom.name = `zone:${this.name}`;
bbGeom.visible = false;
bbGeom.position.copy(this.physics.position);
bbGeom.matrixAutoUpdate = false;
this.threeObject = bbGeom;
const width = bb.max.x - bb.min.x;
const height = bb.max.y - bb.min.y;
const depth = bb.max.z - bb.min.z;
this.boundingBox = new THREE.Box3(
new THREE.Vector3(-width * 0.5, -height * 0.5, -depth * 0.5),
new THREE.Vector3(width * 0.5, height * 0.5, depth * 0.5)
);
this.createLabel(is3DCam);
}
}
createLabel(is3DCam: boolean) {
this.labelCanvas = document.createElement('canvas');
this.labelCanvas.width = 256;
this.labelCanvas.height = 64;
this.labelCtx = this.labelCanvas.getContext('2d');
this.icon = new Image(32, 32);
this.icon.src = `editor/icons/zones/${this.zoneType}.svg`;
this.labelTexture = new THREE.CanvasTexture(this.labelCanvas);
this.labelTexture.encoding = THREE.GammaEncoding;
this.labelTexture.anisotropy = 16;
this.icon.onload = () => this.updateLabel();
const spriteMaterial = new THREE.SpriteMaterial({
map: this.labelTexture,
depthTest: false
});
// @ts-ignore
spriteMaterial.sizeAttenuation = false;
const sprite = new THREE.Sprite(spriteMaterial);
if (is3DCam) {
sprite.scale.set(0.3, 0.075, 1);
} else {
sprite.scale.set(2, 0.5, 1);
}
sprite.renderOrder = 2;
sprite.name = `label:${this.name}`;
if (this.threeObject) {
this.threeObject.add(sprite);
}
}
updateLabel(selected = false) {
this.labelCtx.clearRect(0, 0, this.labelCanvas.width, this.labelCanvas.height);
this.labelCtx.font = '16px LBA';
this.labelCtx.textAlign = 'center';
const textWidth = Math.min(this.labelCtx.measureText(this.name).width, 256 - 64);
this.labelCtx.fillStyle = selected ? 'white' : 'black';
this.labelCtx.fillRect(128 - (textWidth * 0.5) - 18, 16, textWidth + 38, 32);
this.labelCtx.lineWidth = 2;
this.labelCtx.strokeStyle = `#${this.color.getHexString()}`;
this.labelCtx.strokeRect(128 - (textWidth * 0.5) - 18, 16, textWidth + 38, 32);
this.labelCtx.drawImage(this.icon, 128 - (textWidth * 0.5) - 16, 16, 32, 32);
this.labelCtx.fillStyle = selected ? 'black' : 'white';
this.labelCtx.fillText(this.name, 128 + 18, 38, 256 - 64);
this.labelTexture.needsUpdate = true;
}
static create(props: ZoneProps, is3DCam: boolean): Zone {
switch (props.type)
{
case ZoneType.TELEPORT:
return new TeleportZone(props, is3DCam);
case ZoneType.CAMERA:
return new CameraZone(props, is3DCam);
case ZoneType.SCENERIC:
return new ScenericZone(props, is3DCam);
case ZoneType.FRAGMENT:
return new FragmentZone(props, is3DCam);
case ZoneType.TEXT:
return new TextZone(props, is3DCam);
case ZoneType.BONUS:
return new BonusZone(props, is3DCam);
case ZoneType.LADDER:
return new LadderZone(props, is3DCam);
case ZoneType.CONVEYOR:
return new ConveyorZone(props, is3DCam);
case ZoneType.SPIKE:
return new SpikeZone(props, is3DCam);
case ZoneType.RAIL:
return new RailZone(props, is3DCam);
}
}
}
export class TeleportZone extends Zone {
targetScene: number;
x: number;
y: number;
z: number;
beta: number;
id: number;
enabled: boolean;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.TELEPORT);
super(props, is3DCam);
this.targetScene = this.props.param;
this.x = this.props.info0;
this.y = this.props.info1;
this.z = this.props.info2;
this.beta = this.props.info3;
this.id = this.props.info4;
this.enabled = (this.props.info7 & 3) !== 0;
}
}
export class CameraZone extends Zone {
id: number;
x: number;
y: number;
z: number;
alpha: number;
beta: number;
gamma: number;
distance: number;
enabled: boolean;
force: boolean;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.CAMERA);
super(props, is3DCam);
this.id = this.props.param;
this.x = this.props.info0;
this.y = this.props.info1;
this.z = this.props.info2;
this.alpha = this.props.info3;
this.beta = this.props.info4;
this.gamma = this.props.info5;
this.distance = this.props.info6;
this.enabled = (this.props.info7 & 3) !== 0;
this.force = (this.props.info7 & 8) !== 0;
}
}
export class ScenericZone extends Zone {
id: number;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.SCENERIC);
super(props, is3DCam);
this.id = this.props.param;
}
}
export class FragmentZone extends Zone {
id: number;
fragment: number;
enabled: boolean;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.FRAGMENT);
super(props, is3DCam);
this.id = this.props.param;
this.fragment = this.props.info0;
this.enabled = this.props.info2 !== 0;
}
}
export class BonusZone extends Zone {
bonusType: number;
quantity: number;
given: boolean;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.BONUS);
super(props, is3DCam);
this.bonusType = this.props.info0;
this.quantity = this.props.info1;
this.given = false;
}
}
export class TextZone extends Zone {
message: number;
textColor: number;
camera: number;
side: number;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.TEXT);
super(props, is3DCam);
this.message = this.props.param;
this.textColor = this.props.info0;
this.camera = this.props.info1;
this.side = this.props.info2;
}
}
export class LadderZone extends Zone {
id: number;
enabled: boolean;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.LADDER);
super(props, is3DCam);
this.id = this.props.param;
this.enabled = this.props.info0 !== 0;
}
}
export class ConveyorZone extends Zone {
id: number;
enabled: boolean;
direction: number;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.CONVEYOR);
super(props, is3DCam);
this.id = this.props.param;
this.enabled = this.props.info1 !== 0;
this.direction = this.props.info2;
}
}
export class SpikeZone extends Zone {
id: number;
damage: number;
rearmTime: number;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.SPIKE);
super(props, is3DCam);
this.id = this.props.param;
this.damage = this.props.info1;
this.rearmTime = this.props.info2;
}
}
export class RailZone extends Zone {
id: number;
enabled: boolean;
constructor(props: ZoneProps, is3DCam: boolean) {
assert(props.type === ZoneType.RAIL);
super(props, is3DCam);
this.id = this.props.param;
this.enabled = this.props.info0 !== 0;
}
} | the_stack |
import chai from "chai";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
const assert = chai.assert;
import * as sinon from "sinon";
import { EventEmitter } from "events";
import {
BatchingReceiver,
getRemainingWaitTimeInMsFn,
BatchingReceiverLite
} from "../../../src/core/batchingReceiver";
import { defer, createConnectionContextForTests } from "./unittestUtils";
import { createAbortSignalForTest } from "../../public/utils/abortSignalTestUtils";
import { AbortController } from "@azure/abort-controller";
import { ServiceBusMessageImpl } from "../../../src/serviceBusMessage";
import {
Receiver as RheaPromiseReceiver,
ReceiverEvents,
SessionEvents,
EventContext,
Message as RheaMessage
} from "rhea-promise";
import { ConnectionContext } from "../../../src/connectionContext";
import { ServiceBusReceiverImpl } from "../../../src/receivers/receiver";
import { OperationOptionsBase } from "../../../src/modelsToBeSharedWithEventHubs";
import { ReceiveMode } from "../../../src/models";
import { Constants, StandardAbortMessage } from "@azure/core-amqp";
describe("BatchingReceiver unit tests", () => {
let closeables: { close(): Promise<void> }[];
beforeEach(() => {
closeables = [];
});
afterEach(async () => {
for (const closeable of closeables) {
await closeable.close();
}
});
describe("AbortSignal", () => {
// establish that the abortSignal does get properly sent down. Now the rest of the tests
// will test at the BatchingReceiver level.
it("is plumbed into BatchingReceiver from ServiceBusReceiverImpl", async () => {
const origAbortSignal = createAbortSignalForTest();
const receiver = new ServiceBusReceiverImpl(
createConnectionContextForTests(),
"fakeEntityPath",
"peekLock",
1,
false
);
let wasCalled = false;
receiver["_createBatchingReceiver"] = () => {
return {
async receive(
_maxMessageCount: number,
_maxWaitTimeInMs: number,
_maxTimeAfterFirstMessageMs: number,
options?: OperationOptionsBase
): Promise<ServiceBusMessageImpl[]> {
assert.equal(options?.abortSignal, origAbortSignal);
wasCalled = true;
return [];
}
} as BatchingReceiver;
};
await receiver.receiveMessages(1000, {
maxWaitTimeInMs: 60 * 1000,
abortSignal: origAbortSignal
});
assert.isTrue(wasCalled, "Expected a call to BatchingReceiver.receive()");
});
it("abortSignal is already signalled", async () => {
const abortController = new AbortController();
abortController.abort();
const receiver = new BatchingReceiver(createConnectionContextForTests(), "fakeEntityPath", {
receiveMode: "peekLock",
lockRenewer: undefined,
skipParsingBodyAsJson: false
});
try {
await receiver.receive(1, 60 * 1000, 60 * 1000, {
abortSignal: abortController.signal
});
assert.fail("Should have thrown");
} catch (err) {
assert.equal(err.message, StandardAbortMessage);
assert.equal(err.name, "AbortError");
}
}).timeout(1000);
it("abortSignal while receive is in process", async () => {
const abortController = new AbortController();
const receiver = new BatchingReceiver(createConnectionContextForTests(), "fakeEntityPath", {
receiveMode: "peekLock",
lockRenewer: undefined,
skipParsingBodyAsJson: false
});
closeables.push(receiver);
const listeners = new Set<string>();
const callsDoneAfterAbort: string[] = [];
receiver["_init"] = async () => {
// just enough of a Receiver to validate that cleanup actions
// are being run on abort.
receiver["_link"] = ({
connection: {
id: "connection id"
},
removeListener: (eventType: ReceiverEvents) => {
listeners.add(eventType.toString());
},
once: (eventType: ReceiverEvents) => {
// we definitely shouldn't be registering any new handlers if we've aborted.
callsDoneAfterAbort.push(eventType);
listeners.add(eventType);
},
on: (eventType: ReceiverEvents) => {
// we definitely shouldn't be registering any new handlers if we've aborted.
callsDoneAfterAbort.push(eventType);
listeners.add(eventType);
},
addCredit: () => {
// we definitely shouldn't be adding credits if we know we've aborted.
callsDoneAfterAbort.push("addCredit");
},
session: {
removeListener: (eventType: SessionEvents) => {
listeners.add(eventType.toString());
},
once: (eventType: SessionEvents) => {
// we definitely shouldn't be registering any new handlers if we've aborted.
callsDoneAfterAbort.push(eventType);
listeners.add(eventType);
}
}
} as any) as RheaPromiseReceiver;
abortController.abort();
};
try {
await receiver.receive(1, 60 * 1000, 60 * 1000, { abortSignal: abortController.signal });
assert.fail("Should have thrown");
} catch (err) {
assert.equal(err.message, StandardAbortMessage);
assert.equal(err.name, "AbortError");
}
// order here isn't important, it just happens to be the order we call in `cleanupBeforeReject`
assert.isEmpty(listeners);
assert.isEmpty(callsDoneAfterAbort);
});
});
/**
* receive(max messages, max wait time, max wait time past first message) has 3 exit paths:
* 1. We received 'max messages'
* 2. We've waited 'max wait time'
* 3. We've received 1 message and _now_ have exceeded 'max wait time past first message'
*/
const receiveModes: ReceiveMode[] = ["peekLock", "receiveAndDelete"];
receiveModes.forEach((lockMode) => {
describe(`${lockMode} receive, exit paths`, () => {
const bigTimeout = 60 * 1000;
const littleTimeout = 30 * 1000;
let clock: ReturnType<typeof sinon.useFakeTimers>;
beforeEach(() => {
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it("1. We received 'max messages'", async () => {
const batchingReceiver = new BatchingReceiver(
createConnectionContextForTests(),
"dummyEntityPath",
{
receiveMode: lockMode,
lockRenewer: undefined,
skipParsingBodyAsJson: false
}
);
closeables.push(batchingReceiver);
const { receiveIsReady, rheaReceiver } = setupBatchingReceiver(batchingReceiver);
const receivePromise = batchingReceiver.receive(1, bigTimeout, bigTimeout, {});
await receiveIsReady;
// batch fulfillment is checked when we receive a message...
rheaReceiver.emit(ReceiverEvents.message, {
message: { body: "the message" } as RheaMessage
} as EventContext);
const messages = await receivePromise;
assert.deepEqual(
messages.map((m) => m.body),
["the message"]
);
assertListenersRemoved(rheaReceiver);
}).timeout(5 * 1000);
// in the new world the overall timeout firing means we've received _no_ messages
// because otherwise it'd be one of the others.
it("2. We've waited 'max wait time'", async () => {
const receiver = new BatchingReceiver(
createConnectionContextForTests(),
"dummyEntityPath",
{
receiveMode: lockMode,
lockRenewer: undefined,
skipParsingBodyAsJson: false
}
);
closeables.push(receiver);
const { receiveIsReady, rheaReceiver } = setupBatchingReceiver(receiver);
const receivePromise = receiver.receive(1, littleTimeout, bigTimeout, {});
await receiveIsReady;
// force the overall timeout to fire
clock.tick(littleTimeout + 1);
const messages = await receivePromise;
assert.isEmpty(messages);
assertListenersRemoved(rheaReceiver);
}).timeout(5 * 1000);
// TODO: there's a bug that needs some more investigation where receiveAndDelete loses messages if we're
// too aggressive about returning early. In that case we just revert to using the older behavior of waiting for
// the duration of time given (or max messages) with no idle timer.
// When we eliminate that bug we can remove this check.
(lockMode === "peekLock" ? it : it.skip)(
`3a. (with idle timeout) We've received 1 message and _now_ have exceeded 'max wait time past first message'`,
async () => {
const batchingReceiver = new BatchingReceiver(
createConnectionContextForTests(),
"dummyEntityPath",
{
receiveMode: lockMode,
lockRenewer: undefined,
skipParsingBodyAsJson: false
}
);
closeables.push(batchingReceiver);
const { receiveIsReady, rheaReceiver } = setupBatchingReceiver(batchingReceiver, clock);
const receivePromise = batchingReceiver.receive(3, bigTimeout, littleTimeout, {});
await receiveIsReady;
// batch fulfillment is checked when we receive a message...
rheaReceiver.emit(ReceiverEvents.message, {
message: { body: "the first message" } as RheaMessage
} as EventContext);
// advance the timeout to _just_ before the expiration of the first one (which must have been set
// since we just received a message). This'll make it more obvious if I scheduled it a second time.
clock.tick(littleTimeout - 1);
// now emit a second message - this second message should _not_ change any existing timers
// or start new ones.
rheaReceiver.emit(ReceiverEvents.message, {
message: { body: "the second message" } as RheaMessage
} as EventContext);
// now we'll advance the clock to 'littleTimeout' which should now fire off our timer.
clock.tick(1); // make the "no new message arrived within time limit" timer fire.
const messages = await receivePromise;
assert.deepEqual(
messages.map((m) => m.body),
["the first message", "the second message"]
);
assertListenersRemoved(rheaReceiver);
}
).timeout(5 * 1000);
// TODO: there's a bug that needs some more investigation where receiveAndDelete loses messages if we're
// too aggressive about returning early. In that case we just revert to using the older behavior of waiting for
// the duration of time given (or max messages) with no idle timer.
// When we eliminate that bug we can remove this test in favor of the idle timeout test above.
(lockMode === "receiveAndDelete" ? it : it.skip)(`3b. (without idle timeout)`, async () => {
const batchingReceiver = new BatchingReceiver(
createConnectionContextForTests(),
"dummyEntityPath",
{
receiveMode: lockMode,
lockRenewer: undefined,
skipParsingBodyAsJson: false
}
);
closeables.push(batchingReceiver);
const { receiveIsReady, rheaReceiver } = setupBatchingReceiver(batchingReceiver);
const receivePromise = batchingReceiver.receive(3, bigTimeout, littleTimeout, {});
await receiveIsReady;
// batch fulfillment is checked when we receive a message...
rheaReceiver.emit(ReceiverEvents.message, {
message: {
body: "the first message"
} as RheaMessage
} as EventContext);
// In the peekLock algorithm we would've resolved the promise here but_ we disable
// that in receiveAndDelete. So we'll advance here....
clock.tick(littleTimeout);
// ...and emit another message _after_ the idle timer would have fired. Now when we advance
// the time all the way....
rheaReceiver.emit(ReceiverEvents.message, {
message: {
body: "the second message"
} as RheaMessage
} as EventContext);
clock.tick(bigTimeout);
// ...we can see that we didn't resolve earlier - we only resolved after the `maxWaitTimeInMs`
// timer fired.
const messages = await receivePromise;
assert.deepEqual(
messages.map((m) => m.body),
["the first message", "the second message"]
);
assertListenersRemoved(rheaReceiver);
}).timeout(5 * 1000);
// TODO: there's a bug that needs some more investigation where receiveAndDelete loses messages if we're
// too aggressive about returning early. In that case we just revert to using the older behavior of waiting for
// the duration of time given (or max messages) with no idle timer.
// When we eliminate that bug we can enable this test for all modes.
(lockMode === "peekLock" ? it : it.skip)(
"4. sanity check that we're using getRemainingWaitTimeInMs",
async () => {
const batchingReceiver = new BatchingReceiver(
createConnectionContextForTests(),
"dummyEntityPath",
{
receiveMode: lockMode,
lockRenewer: undefined,
skipParsingBodyAsJson: false
}
);
closeables.push(batchingReceiver);
const { receiveIsReady, rheaReceiver: emitter } = setupBatchingReceiver(
batchingReceiver,
clock
);
let wasCalled = false;
const arbitraryAmountOfTimeInMs = 40;
batchingReceiver["_batchingReceiverLite"]["_getRemainingWaitTimeInMsFn"] = (
maxWaitTimeInMs: number,
maxTimeAfterFirstMessageMs: number
) => {
// sanity check that the timeouts are passed in correctly....
assert.equal(maxWaitTimeInMs, bigTimeout + 1);
assert.equal(maxTimeAfterFirstMessageMs, bigTimeout + 2);
return () => {
// and we'll make sure that we did ask the callback from the amount
// of time to wait...
wasCalled = true;
return arbitraryAmountOfTimeInMs;
};
};
const receivePromise = batchingReceiver.receive(3, bigTimeout + 1, bigTimeout + 2, {});
await receiveIsReady;
emitter.emit(ReceiverEvents.message, {
message: {
body: "the second message"
} as RheaMessage
} as EventContext);
// and just to be _really_ sure we'll only tick the `arbitraryAmountOfTimeInMs`.
// if we resolve() then we know that we ignored the passed in timeouts in favor
// of what our getRemainingWaitTimeInMs function calculated.
clock.tick(arbitraryAmountOfTimeInMs);
const messages = await receivePromise;
assert.equal(messages.length, 1);
assert.isTrue(wasCalled);
assertListenersRemoved(emitter);
}
);
function setupBatchingReceiver(
batchingReceiver: BatchingReceiver,
clockParam?: ReturnType<typeof sinon.useFakeTimers>
): {
receiveIsReady: Promise<void>;
rheaReceiver: RheaPromiseReceiver;
} {
const rheaReceiver = createFakeReceiver(clockParam);
batchingReceiver["_link"] = rheaReceiver;
batchingReceiver["_batchingReceiverLite"]["_createServiceBusMessage"] = (eventContext) => {
return {
body: eventContext.message?.body
} as ServiceBusMessageImpl;
};
const receiveIsReady = getReceiveIsReadyPromise(batchingReceiver["_batchingReceiverLite"]);
return {
receiveIsReady,
rheaReceiver
};
}
});
});
function createFakeReceiver(clock?: ReturnType<typeof sinon.useFakeTimers>): RheaPromiseReceiver {
const fakeRheaReceiver = new EventEmitter() as RheaPromiseReceiver;
fakeRheaReceiver.drain = false;
let credit = 0;
fakeRheaReceiver.on(ReceiverEvents.message, function creditRemoverForTests() {
--credit;
});
(fakeRheaReceiver as any).session = new EventEmitter();
fakeRheaReceiver["isOpen"] = () => true;
fakeRheaReceiver["addCredit"] = (_credit: number) => {
credit += _credit;
};
fakeRheaReceiver["drainCredit"] = () => {
fakeRheaReceiver.drain = true;
fakeRheaReceiver.emit(ReceiverEvents.receiverDrained, undefined);
clock?.runAll();
};
Object.defineProperty(fakeRheaReceiver, "credit", {
get: () => credit
});
(fakeRheaReceiver as any)["connection"] = {
id: "connection-id"
};
return fakeRheaReceiver;
}
describe("getRemainingWaitTimeInMs", () => {
let clock: ReturnType<typeof sinon.useFakeTimers>;
beforeEach(() => {
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it("tests", () => {
let fn = getRemainingWaitTimeInMsFn(10, 2);
// 1ms has elapsed so we're comparing 9ms vs 2ms
clock.tick(1);
assert.equal(2, fn());
fn = getRemainingWaitTimeInMsFn(10, 2);
// 9ms has elapsed so we're comparing 1ms vs 2ms
clock.tick(9);
assert.equal(1, fn());
fn = getRemainingWaitTimeInMsFn(10, 2);
// 8ms has elapsed so we're comparing 2ms vs 2ms
clock.tick(8);
assert.equal(2, fn());
fn = getRemainingWaitTimeInMsFn(10, 2);
// 11ms has elapsed so we're comparing -1ms vs 2ms (we'll just treat that as "don't wait, just return what you have")
clock.tick(11);
assert.equal(0, fn());
});
});
describe("BatchingReceiverLite", () => {
let clock: ReturnType<typeof sinon.useFakeTimers>;
beforeEach(() => {
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it("isReceivingMessages is properly set and unset when receiving operations run", async () => {
const fakeRheaReceiver = createFakeReceiver();
const batchingReceiver = new BatchingReceiverLite(
createConnectionContextForTests(),
"fakeEntityPath",
async () => {
return fakeRheaReceiver;
},
"peekLock",
false
);
assert.isFalse(batchingReceiver.isReceivingMessages);
const receiveIsReady = getReceiveIsReadyPromise(batchingReceiver);
const prm = batchingReceiver.receiveMessages({
maxMessageCount: 1,
maxTimeAfterFirstMessageInMs: 20,
maxWaitTimeInMs: 10
});
assert.isTrue(batchingReceiver.isReceivingMessages);
await receiveIsReady;
clock.tick(10 + 1);
await prm;
assert.isFalse(batchingReceiver.isReceivingMessages);
});
it("batchingReceiverLite.close(actual-error) - throws the error from the current receiverMessages() call", async () => {
const fakeRheaReceiver = createFakeReceiver();
const batchingReceiver = new BatchingReceiverLite(
{} as ConnectionContext,
"fakeEntityPath",
async () => {
return fakeRheaReceiver;
},
"peekLock",
false
);
assert.notExists(batchingReceiver["_closeHandler"]);
const receiveIsReady = getReceiveIsReadyPromise(batchingReceiver);
const receiveMessagesPromise = batchingReceiver.receiveMessages({
maxMessageCount: 1,
maxTimeAfterFirstMessageInMs: 1,
maxWaitTimeInMs: 1
});
await receiveIsReady;
assert.exists(batchingReceiver["_closeHandler"]);
batchingReceiver.terminate(new Error("actual error"));
try {
await receiveMessagesPromise;
assert.fail("Test should have thrown");
} catch (err) {
assert.equal(err.message, "actual error");
}
});
it("batchingReceiverLite.close() (ie, no error) just shuts down the current operation with no error", async () => {
const fakeRheaReceiver = createFakeReceiver();
const batchingReceiver = new BatchingReceiverLite(
createConnectionContextForTests(),
"fakeEntityPath",
async () => {
return fakeRheaReceiver;
},
"peekLock",
false
);
assert.notExists(batchingReceiver["_closeHandler"]);
let resolveWasCalled = false;
let rejectWasCalled = false;
batchingReceiver["_receiveMessagesImpl"](
(await batchingReceiver["_getCurrentReceiver"]())!,
{
maxMessageCount: 1,
maxTimeAfterFirstMessageInMs: 1,
maxWaitTimeInMs: 1
},
() => {
resolveWasCalled = true;
},
() => {
rejectWasCalled = true;
}
);
assert.exists(batchingReceiver["_closeHandler"]);
assert.isFalse(resolveWasCalled);
assert.isFalse(rejectWasCalled);
batchingReceiver.terminate();
// these are still false because we used setTimeout() (and we're using sinon)
// so the clock is "frozen"
assert.isFalse(resolveWasCalled);
assert.isFalse(rejectWasCalled);
// now unfreeze it (without ticking time forward, just running whatever is eligible _now_)
clock.tick(0);
assert.isTrue(resolveWasCalled);
assert.isFalse(rejectWasCalled);
});
it("finalAction prevents multiple concurrent drain calls", async () => {
// there are unintended side effects if multiple drains are requested (ie - you start to get
// mismatches between responses, resulting in this error message ("Received transfer
// when credit was 0") bring printed by rhea.
const fakeRheaReceiver = createFakeReceiver();
const batchingReceiverLite = new BatchingReceiverLite(
createConnectionContextForTests(),
"fakeEntityPath",
async () => {
return fakeRheaReceiver;
},
"peekLock",
false
);
batchingReceiverLite["_receiveMessagesImpl"](
fakeRheaReceiver,
{
maxMessageCount: 2,
maxTimeAfterFirstMessageInMs: 1,
maxWaitTimeInMs: 1
},
() => {
/* empty body */
},
() => {
/* empty body */
}
);
assert.equal(
fakeRheaReceiver.credit,
2,
"No messages received, nothing drained, should have all the credits from the start."
);
const finalAction = batchingReceiverLite["_finalAction"];
if (!finalAction) {
throw new Error("No finalAction defined!");
}
fakeRheaReceiver.removeAllListeners(ReceiverEvents.receiverDrained);
// the first call (when there are no received messages) will initiate a drain
assert.isFalse(fakeRheaReceiver.drain);
const drainCreditSpy = sinon.spy(fakeRheaReceiver, "drainCredit");
finalAction();
assert.isTrue(drainCreditSpy.calledOnceWith());
// also our fix should leave our # of credits untouched (ie, no +1 effect)
assert.equal(fakeRheaReceiver.credit, 2);
drainCreditSpy.resetHistory();
// subsequent calls will not initiate drains.
finalAction();
assert.isTrue(drainCreditSpy.notCalled);
});
});
it("drain doesn't resolve before message callbacks have completed", async () => {
const fakeRheaReceiver = createFakeReceiver();
const batchingReceiverLite = new BatchingReceiverLite(
createConnectionContextForTests(),
"fakeEntityPath",
async () => {
return fakeRheaReceiver;
},
"peekLock",
false
);
const receiveIsReady = getReceiveIsReadyPromise(batchingReceiverLite);
const receiveMessagesPromise = batchingReceiverLite
.receiveMessages({
maxMessageCount: 3,
maxTimeAfterFirstMessageInMs: 5000,
maxWaitTimeInMs: 5000
})
.then((messages) => {
return [...messages];
});
await receiveIsReady;
// We've had an issue in the past where it seemed that drain was
// causing us to potentially not return messages that should have
// existed. In our tests this is very hard to reproduce because it
// requires us to control more of how the stream of events are
// returned in Service Bus.
// Our suspicion has been that it's possible we're receiving messages _after_ a
// drain has occurred but we've never seen it in the wild or in any of our testing.
// However, in rhea-promise there is an odd mismatch of dispatching that can cause this
// sequence of events to occur:
// 1. rhea-promise: receive message A
// rhea-promise then calls: setTimeout(emit(messageA))
// 2. us: decide to drain (timeout expired)
// 3. rhea-promise: sends drain
// 4. rhea-promise: receives message B (Service Bus has not yet processed the drain request)
// rhea-promise then calls: setTimeout(emit(messageB))
//
// Now at this point we have the setTimeout(emit(messageB)) in the task queue. It'll be
// executed at the next turn of the event loop.
//
// The problem then comes in when rhea-promise receives the receiver_drained event:
// 4. rhea-promise: receives receiver_drain event
// emit(drain) // note it does _not_ use setTimeout()
//
// This causes the drain event to fire immediately. When it resolves the underlying promise
// it resolves it prior to emit(messageB) firing, resulting in lost messages.
//
// To fix this when we get receive_drained we setTimeout(resolve) instead of just immediately resolving. This allows
// us to enter into the same task queue as all the message callbacks, and makes it so everything occurs in the
// right order.
setTimeout(() => {
fakeRheaReceiver.emit(ReceiverEvents.message, {
message: {
body: "the first message",
message_annotations: {
[Constants.enqueuedTime]: 0
}
} as RheaMessage
} as EventContext);
});
fakeRheaReceiver.emit(ReceiverEvents.receiverDrained, {} as EventContext);
const results = await receiveMessagesPromise;
assert.equal(1, results.length);
});
});
function getReceiveIsReadyPromise(batchingReceiverLite: BatchingReceiverLite): Promise<void> {
// receiveMessagesImpl is the 'non-async' method that sets up the receiver and adds credits. So it's a
// perfect method to hook into to test the internals of the BatchingReceiver(Lite)
const orig = batchingReceiverLite["_receiveMessagesImpl"];
const { resolve, promise } = defer<void>();
batchingReceiverLite["_receiveMessagesImpl"] = (...args) => {
orig.call(batchingReceiverLite, ...args);
resolve();
};
return promise;
}
function assertListenersRemoved(rheaReceiver: RheaPromiseReceiver): void {
const shouldBeEmpty = [
ReceiverEvents.receiverClose,
ReceiverEvents.receiverDrained,
ReceiverEvents.receiverError,
ReceiverEvents.receiverFlow,
ReceiverEvents.receiverOpen,
ReceiverEvents.settled,
SessionEvents.sessionClose,
SessionEvents.sessionError,
SessionEvents.sessionOpen,
SessionEvents.settled
];
// we add a little credit remover for our tests. Ignore it.
assert.isEmpty(
rheaReceiver
.listeners(ReceiverEvents.message)
.filter((f) => f.name !== "creditRemoverForTests"),
`No listeners (aside from the test credit remover) should be registered for ${ReceiverEvents.message}`
);
for (const eventName of shouldBeEmpty) {
assert.isEmpty(
rheaReceiver.listeners(eventName),
`No listeners should be registered for ${eventName} on the receiver`
);
assert.isEmpty(
rheaReceiver.session.listeners(eventName),
`No listeners should be registered for ${eventName} on the receiver.session`
);
}
} | the_stack |
import EventDispatcher from "./../../starling/events/EventDispatcher";
import Starling from "./../../starling/core/Starling";
import IllegalOperationError from "openfl/errors/IllegalOperationError";
import FilterHelper from "./../../starling/filters/FilterHelper";
import FilterQuad from "./../../starling/filters/FilterQuad";
import Pool from "./../../starling/utils/Pool";
import Stage from "./../../starling/display/Stage";
import RectangleUtil from "./../../starling/utils/RectangleUtil";
import MatrixUtil from "./../../starling/utils/MatrixUtil";
import FilterEffect from "./../../starling/rendering/FilterEffect";
import VertexData from "./../../starling/rendering/VertexData";
import IndexData from "./../../starling/rendering/IndexData";
import Padding from "./../../starling/utils/Padding";
import ArgumentError from "openfl/errors/ArgumentError";
import Matrix3D from "openfl/geom/Matrix3D";
import FilterEffect from "./../rendering/FilterEffect";
import Mesh from "./../display/Mesh";
import Texture from "./../textures/Texture";
import Painter from "./../rendering/Painter";
import IFilterHelper from "./IFilterHelper";
import DisplayObject from "./../display/DisplayObject";
import Rectangle from "openfl/geom/Rectangle";
declare namespace starling.filters
{
/** Dispatched when the settings change in a way that requires a redraw. */
// @:meta(Event(name="change", type="starling.events.Event"))
/** Dispatched every frame on filters assigned to display objects connected to the stage. */
// @:meta(Event(name="enterFrame", type="starling.events.EnterFrameEvent"))
/** The FragmentFilter class is the base class for all filter effects in Starling.
* All filters must extend this class. You can attach them to any display object through the
* <code>filter</code> property.
*
* <p>A fragment filter works in the following way:</p>
* <ol>
* <li>The object to be filtered is rendered into a texture.</li>
* <li>That texture is passed to the <code>process</code> method.</li>
* <li>This method processes the texture using a <code>FilterEffect</code> subclass
* that processes the input via fragment and vertex shaders to achieve a certain
* effect.</li>
* <li>If the filter requires several passes, the process method may execute the
* effect several times, or even make use of other filters in the process.</li>
* <li>In the end, a quad with the output texture is added to the batch renderer.
* In the next frame, if the object hasn't changed, the filter is drawn directly
* from the render cache.</li>
* <li>Alternatively, the last pass may be drawn directly to the back buffer. That saves
* one draw call, but means that the object may not be drawn from the render cache in
* the next frame. Starling makes an educated guess if that makes sense, but you can
* also force it to do so via the <code>alwaysDrawToBackBuffer</code> property.</li>
* </ol>
*
* <p>All of this is set up by the basic FragmentFilter class. Concrete subclasses
* just need to override the protected method <code>createEffect</code> and (optionally)
* <code>process</code>. Multi-pass filters must also override <code>numPasses</code>.</p>
*
* <p>Typically, any properties on the filter are just forwarded to an effect instance,
* which is then used automatically by <code>process</code> to render the filter pass.
* For a simple example on how to write a single-pass filter, look at the implementation of
* the <code>ColorMatrixFilter</code>; for a composite filter (i.e. a filter that combines
* several others), look at the <code>GlowFilter</code>.
* </p>
*
* <p>Beware that a filter instance may only be used on one object at a time!</p>
*
* <p><strong>Animated filters</strong></p>
*
* <p>The <code>process</code> method of a filter is only called when it's necessary, i.e.
* when the filter properties or the target display object changes. This means that you cannot
* rely on the method to be called on a regular basis, as needed when creating an animated
* filter class. Instead, you can do so by listening for an <code>ENTER_FRAME</code>-event.
* It is dispatched on the filter once every frame, as long as the filter is assigned to
* a display object that is connected to the stage.</p>
*
* <p><strong>Caching</strong></p>
*
* <p>Per default, whenever the target display object is changed in any way (i.e. the render
* cache fails), the filter is reprocessed. However, you can manually cache the filter output
* via the method of the same name: this will let the filter redraw the current output texture,
* even if the target object changes later on. That's especially useful if you add a filter
* to an object that changes only rarely, e.g. a TextField or an Image. Keep in mind, though,
* that you have to call <code>cache()</code> again in order for any changes to show up.</p>
*
* @see starling.rendering.FilterEffect
*/
export class FragmentFilter extends EventDispatcher
{
/** Creates a new instance. The base class' implementation just draws the unmodified
* input texture. */
public constructor();
/** Disposes all resources that have been created by the filter. */
public dispose():void;
/** Renders the filtered target object. Most users will never have to call this manually;
* it's executed automatically in the rendering process of the filtered display object.
*/
public render(painter:Painter):void;
/** Does the actual filter processing. This method will be called with up to four input
* textures and must return a new texture (acquired from the <code>helper</code>) that
* contains the filtered output. To to do this, it configures the FilterEffect
* (provided via <code>createEffect</code>) and calls its <code>render</code> method.
*
* <p>In a standard filter, only <code>input0</code> will contain a texture; that's the
* object the filter was applied to, rendered into an appropriately sized texture.
* However, filters may also accept multiple textures; that's useful when you need to
* combine the output of several filters into one. For example, the DropShadowFilter
* uses a BlurFilter to create the shadow and then feeds both input and shadow texture
* into a CompositeFilter.</p>
*
* <p>Never create or dispose any textures manually within this method; instead, get
* new textures from the provided helper object, and pass them to the helper when you do
* not need them any longer. Ownership of both input textures and returned texture
* lies at the caller; only temporary textures should be put into the helper.</p>
*/
public process(painter:Painter, helper:IFilterHelper,
input0?:Texture, input1?:Texture,
input2?:Texture, input3?:Texture):Texture;
/** Caches the filter output into a texture.
*
* <p>An uncached filter is rendered every frame (except if it can be rendered from the
* global render cache, which happens if the target object does not change its appearance
* or location relative to the stage). A cached filter is only rendered once; the output
* stays unchanged until you call <code>cache</code> again or change the filter settings.
* </p>
*
* <p>Beware: you cannot cache filters on 3D objects; if the object the filter is attached
* to is a Sprite3D or has a Sprite3D as (grand-) parent, the request will be silently
* ignored. However, you <em>can</em> cache a 2D object that has 3D children!</p>
*/
public cache():void;
/** Clears the cached output of the filter. After calling this method, the filter will be
* processed once per frame again. */
public clearCache():void;
// enter frame event
/** @protected */
/*override*/ public addEventListener(type:string, listener:Function):void;
/** @protected */
/*override*/ public removeEventListener(type:string, listener:Function):void;
// properties
/** Padding can extend the size of the filter texture in all directions.
* That's useful when the filter "grows" the bounds of the object in any direction. */
public padding:Padding;
protected get_padding():Padding;
protected set_padding(value:Padding):Padding;
/** Indicates if the filter is cached (via the <code>cache</code> method). */
public readonly isCached:boolean;
protected get_isCached():boolean;
/** The resolution of the filter texture. "1" means stage resolution, "0.5" half the stage
* resolution. A lower resolution saves memory and execution time, but results in a lower
* output quality. Values greater than 1 are allowed; such values might make sense for a
* cached filter when it is scaled up. @default 1
*/
public resolution:number;
protected get_resolution():number;
protected set_resolution(value:number):number;
/** Indicates if the filter requires all passes to be processed with the exact same
* resolution.
*
* <p>Some filters must use the same resolution for input and output; e.g. the blur filter
* is very sensitive to changes of pixel / texel sizes. When the filter is used as part
* of a filter chain, or if its last pass is drawn directly to the back buffer, such a
* filter produces artifacts. In that case, the filter author must set this property
* to <code>true</code>.</p>
*
* @default false
*/
protected maintainResolutionAcrossPasses:boolean;
protected get_maintainResolutionAcrossPasses():boolean;
protected set_maintainResolutionAcrossPasses(value:boolean):boolean;
/** The anti-aliasing level. This is only used for rendering the target object
* into a texture, not for the filter passes. 0 - none, 4 - maximum. @default 0 */
public antiAliasing:number;
protected get_antiAliasing():number;
protected set_antiAliasing(value:number):number;
/** The smoothing mode of the filter texture. @default bilinear */
public textureSmoothing:string;
protected get_textureSmoothing():string;
protected set_textureSmoothing(value:string):string;
/** The format of the filter texture. @default BGRA */
public textureFormat:string;
protected get_textureFormat():string;
protected set_textureFormat(value:string):string;
/** Indicates if the last filter pass is always drawn directly to the back buffer.
*
* <p>Per default, the filter tries to automatically render in a smart way: objects that
* are currently moving are rendered to the back buffer, objects that are static are
* rendered into a texture first, which allows the filter to be drawn directly from the
* render cache in the next frame (in case the object remains static).</p>
*
* <p>However, this fails when filters are added to an object that does not support the
* render cache, or to a container with such a child (e.g. a Sprite3D object or a masked
* display object). In such a case, enable this property for maximum performance.</p>
*
* @default false
*/
public alwaysDrawToBackBuffer:boolean;
protected get_alwaysDrawToBackBuffer():boolean;
protected set_alwaysDrawToBackBuffer(value:boolean):boolean;
}
export class FilterQuad extends Mesh
{
public constructor(smoothing:string);
/*override*/ public dispose():void;
public disposeTexture():void;
public moveVertices(sourceSpace:DisplayObject, targetSpace:DisplayObject):void;
public setBounds(bounds:Rectangle):void;
}
}
export default starling.filters.FragmentFilter; | the_stack |
import { fixInsert, insertAfterNode, insertBeforeNode } from "../tree/insert";
import { Color, PageContent } from "../pageModel";
import { SENTINEL_INDEX, EMPTY_TREE_ROOT } from "../tree/tree";
import { Buffer, ContentNode } from "./contentModel";
import {
getLineStarts,
getNodeContent,
updateContentTreeMetadata,
} from "./tree";
import { InsertContentDOM } from "./actions";
import { insertStructureNode } from "../structureTree/insert";
import { generateNewId } from "../structureTree/tree";
import { TagType } from "../structureTree/structureModel";
/**
* Creates a new node, and creates a new buffer to contain the new content.
* @param action The insert action.
* @param page The page to insert the content into.
*/
function createNodeCreateBuffer(
action: InsertContentDOM,
page: PageContent,
): void {
const newBuffer: Buffer = {
content: action.content,
isReadOnly: false,
lineStarts: getLineStarts(action.content),
};
const newNode: ContentNode = {
bufferIndex: page.buffers.length,
color: Color.Red,
end: {
column:
newBuffer.content.length -
newBuffer.lineStarts[newBuffer.lineStarts.length - 1],
line: newBuffer.lineStarts.length - 1,
},
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: action.content.length,
lineFeedCount: newBuffer.lineStarts.length - 1,
parent: SENTINEL_INDEX,
right: SENTINEL_INDEX,
start: { column: 0, line: 0 },
};
page.previouslyInsertedContentNodeIndex = page.content.nodes.length;
page.previouslyInsertedContentNodeOffset = action.content.length;
page.buffers.push(newBuffer);
if (action.localOffset === 0) {
insertBeforeNode(page.content, newNode, action.start.nodeIndex);
} else {
insertAfterNode(page.content, newNode, action.end.nodeIndex);
}
}
/**
* Creates a new node, and appends the content to an existing buffer.
* @param action The insert action.
* @param page The page to insert the content into.
*/
function createNodeAppendToBuffer(
action: InsertContentDOM,
page: PageContent,
): void {
const oldBuffer = page.buffers[page.buffers.length - 1];
const newContent = oldBuffer.content + action.content;
const updatedBuffer: Buffer = {
content: newContent,
isReadOnly: oldBuffer.isReadOnly,
lineStarts: getLineStarts(newContent),
};
const newNode: ContentNode = {
bufferIndex: page.buffers.length - 1,
color: Color.Red,
end: {
column:
updatedBuffer.content.length -
updatedBuffer.lineStarts[updatedBuffer.lineStarts.length - 1],
line: updatedBuffer.lineStarts.length - 1,
},
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: action.content.length,
lineFeedCount:
updatedBuffer.lineStarts.length - oldBuffer.lineStarts.length,
parent: SENTINEL_INDEX,
right: SENTINEL_INDEX,
start: {
column:
oldBuffer.content.length -
oldBuffer.lineStarts[oldBuffer.lineStarts.length - 1],
line: oldBuffer.lineStarts.length - 1,
},
};
page.buffers[page.buffers.length - 1] = updatedBuffer;
page.previouslyInsertedContentNodeIndex = page.content.nodes.length;
page.previouslyInsertedContentNodeOffset = newNode.length;
if (action.localOffset === 0) {
insertBeforeNode(page.content, newNode, action.start.nodeIndex);
} else {
insertAfterNode(page.content, newNode, action.end.nodeIndex);
}
}
/**
* Inserts the given content into a page, by creating a node which is inserted
* either immediately before or after an existing node.
* @param action The insert action.
* @param page The page to insert the content into.
* @param maxBufferLength The maximum length of a buffer's content/string.
*/
function insertAtNodeExtremity(
action: InsertContentDOM,
page: PageContent,
maxBufferLength: number,
): void {
// check buffer size
if (
action.content.length +
page.buffers[page.buffers.length - 1].content.length <=
maxBufferLength &&
page.buffers[page.buffers.length - 1].isReadOnly === false
) {
// scenario 3 and 5: it can fit inside the previous buffer
// creates a new node
// appends to the previous buffer
createNodeAppendToBuffer(action, page);
} else {
// scenario 4 and 6: it cannot fit inside the previous buffer
// creates a new node
// creates a new buffer
createNodeCreateBuffer(action, page);
}
}
/**
* Inserts the given content into a page, inside a range which is currently
* encapsulated by an existing node.
* @param action The insert action.
* @param page The page to insert the content into.
* @param maxBufferLength The maximum length of a buffer's content/string.
*/
function insertInsideNode(
action: InsertContentDOM,
page: PageContent,
maxBufferLength: number,
): void {
const node = page.content.nodes[action.start.nodeIndex];
const nodeContent = getNodeContent(page, action.start.nodeIndex);
const firstPartContent = nodeContent.slice(0, action.localOffset);
const firstPartLineStarts = getLineStarts(firstPartContent);
const firstPartNode: ContentNode = {
...node,
end: {
column:
firstPartContent.length -
firstPartLineStarts[firstPartLineStarts.length - 1] +
node.start.column,
line: firstPartLineStarts.length - 1 + node.start.line,
},
length: firstPartContent.length,
lineFeedCount: firstPartLineStarts.length - 1,
};
page.content.nodes[action.start.nodeIndex] = firstPartNode;
const secondPartNode: ContentNode = {
bufferIndex: node.bufferIndex,
color: Color.Red,
end: node.end,
left: SENTINEL_INDEX,
leftCharCount: 0,
leftLineFeedCount: 0,
length: node.length - firstPartNode.length,
lineFeedCount: node.lineFeedCount - firstPartNode.lineFeedCount,
parent: SENTINEL_INDEX,
right: SENTINEL_INDEX,
start: firstPartNode.end,
};
// Remove the length of the second part node from the parent's leftCharCount,
// and similiarly with line feed
updateContentTreeMetadata(
page.content,
action.start.nodeIndex,
-secondPartNode.length,
-secondPartNode.lineFeedCount,
);
insertAfterNode(page.content, secondPartNode, action.end.nodeIndex);
fixInsert(page.content, page.content.nodes.length - 1);
insertAtNodeExtremity(action, page, maxBufferLength);
page.previouslyInsertedContentNodeIndex = page.content.nodes.length - 1;
page.previouslyInsertedContentNodeOffset = action.content.length;
}
/**
* Inserts the given content into a page, at the end of the previously
* inserted node.
* @param action The insert action.
* @param page The page to insert the content into.
* @param maxBufferLength The maximum length of a buffer's content/string.
*/
function insertAtEndPreviouslyInsertedNode(
action: InsertContentDOM,
page: PageContent,
maxBufferLength: number,
): void {
// check buffer size
if (
action.content.length +
page.buffers[page.buffers.length - 1].content.length <=
maxBufferLength
) {
// scenario 1: can fit inside the previous buffer
// appends to the previous node
// appends to the previous buffer
const oldBuffer = page.buffers[page.buffers.length - 1];
const newContent = oldBuffer.content + action.content;
const buffer: Buffer = {
content: newContent,
isReadOnly: oldBuffer.isReadOnly,
lineStarts: getLineStarts(newContent),
};
const node = page.content.nodes[page.content.nodes.length - 1];
node.end = {
column:
buffer.content.length - buffer.lineStarts[buffer.lineStarts.length - 1],
line: buffer.lineStarts.length - 1,
};
node.lineFeedCount = buffer.lineStarts.length - 1;
node.length += action.content.length;
page.buffers[page.buffers.length - 1] = buffer;
} else {
// scenario 2: cannot fit inside the previous buffer
// creates a new node
// creates a new buffer
createNodeCreateBuffer(action, page);
}
}
// function convertBreakToParagraph(
// tree: RedBlackTree<StructureNode>,
// contentOffset: number,
// structureNodeIndex: number,
// ): void {
// const startNode = tree.nodes[structureNodeIndex];
// startNode.style = {
// marginBottom: "0pt",
// marginTop: "0pt",
// };
// startNode.tag = "p";
// startNode.tagType = TagType.StartTag;
// tree.nodes[structureNodeIndex] = startNode;
// const endNode: StructureNode = {
// color: Color.Red,
// id: tree.nodes[structureNodeIndex].id,
// left: SENTINEL_INDEX,
// leftSubTreeLength: 0,
// length: 0,
// parent: SENTINEL_INDEX,
// right: SENTINEL_INDEX,
// tag: "p",
// tagType: TagType.EndTag,
// };
// insertNode(tree, endNode, contentOffset, structureNodeIndex);
// fixInsert(tree, tree.nodes.length - 1);
// }
/**
* Inserts the given content into a page.
* @param action The insert action.
* @param page The page to insert the content into.
* @param maxBufferLength The maximum length of a buffer's content/string.
* @param updateStructureNode If `true` when the
* `page.content.root === EMPTY_TREE_ROOT`, then inserts structure nodes.
* Otherwise, if `true`, the length of the corresponding structure is updated.
* This exists because some callers will alter the structure lengths or insert
* structure nodesthemselves.
*/
export function insertContentDOM(
page: PageContent,
action: InsertContentDOM,
maxBufferLength: number,
updateStructureNode = false,
): void {
if (page.content.root === EMPTY_TREE_ROOT) {
createNodeCreateBuffer(action, page);
page.content.root = 1;
const contentNode = page.content.nodes[1];
contentNode.color = Color.Black;
contentNode.left = SENTINEL_INDEX;
contentNode.parent = SENTINEL_INDEX;
contentNode.right = SENTINEL_INDEX;
if (updateStructureNode) {
insertStructureNode(page, {
id: generateNewId("p"),
length: action.content.length,
offset: 0,
tag: "p",
tagType: TagType.StartTag,
});
insertStructureNode(page, {
id: generateNewId("p"),
insertAfterNode: page.content.root,
length: action.content.length,
offset: 0,
tag: "p",
tagType: TagType.EndTag,
});
}
return;
}
let previouslyInsertedNode: ContentNode | undefined;
if (
page.previouslyInsertedContentNodeIndex !== null &&
page.previouslyInsertedContentNodeOffset !== null &&
page.previouslyInsertedContentNodeIndex === action.start.nodeIndex
) {
previouslyInsertedNode =
page.content.nodes[page.previouslyInsertedContentNodeIndex];
}
if (
previouslyInsertedNode !== undefined &&
action.localOffset === previouslyInsertedNode.length
) {
insertAtEndPreviouslyInsertedNode(action, page, maxBufferLength);
} else {
const node = page.content.nodes[action.start.nodeIndex];
if (action.localOffset > 0 && action.localOffset < node.length) {
insertInsideNode(action, page, maxBufferLength);
} else {
insertAtNodeExtremity(action, page, maxBufferLength);
}
}
if (updateStructureNode && action.structureNodeIndex !== SENTINEL_INDEX) {
page.structure.nodes[action.structureNodeIndex].length +=
action.content.length;
}
fixInsert(page.content, page.content.nodes.length - 1);
} | the_stack |
import { Production } from '../production';
import { WorldInterface } from './worldInterface';
import { Unit } from '../units/unit';
import { GameModel } from '../gameModel';
import { BuyAction, BuyAndUnlockAction, UpAction, UpHire, UpSpecial, Research } from '../units/action';
import { Cost } from '../cost';
import { TypeList } from '../typeList';
import { World } from '../world';
export class Beach implements WorldInterface {
crab: Unit
crabQueen: Unit
crabNest: Unit
crabFarmer: Unit
crabScientist: Unit
shrimp: Unit
lobster: Unit
shark: Unit
shark2: Unit
seaRes: Research
crabJobRes: Research
shrimpRes: Research
lobsterRes: Research
sharkRes: Research
sharkRes2: Research
beachList = new Array<Unit>()
constructor(public game: GameModel) { }
declareStuff() {
this.beachList = new Array<Unit>()
this.crab = new Unit(this.game, "crab", "Crab", "Crab yield sand.")
this.crabFarmer = new Unit(this.game, "crabF", "Farmer Crab", "Farmer Crab yield fungus.")
this.crabQueen = new Unit(this.game, "CrabQ", "Crab Queen", "Crab Queen yield crab.")
this.crabNest = new Unit(this.game, "CrabN", "Crab Nest", "Crab Nest yield crab queens.")
this.shrimp = new Unit(this.game, "shrimp", "Shrimp",
"Shrimp yield sand and crystal.")
this.lobster = new Unit(this.game, "lobster", "Lobster",
"Lobster yield sand, and crystal for food.")
this.crabScientist = new Unit(this.game, "crabScientist", "Scientist Crab",
"Scientist Crab will get science for sand.")
this.shark = new Unit(this.game, "shark", "Shark",
"Shark yield food and crystall.")
this.shark2 = new Unit(this.game, "shark2", "Great Shark",
"Great Shark yield sharks.")
this.beachList.push(this.crabNest)
this.beachList.push(this.crabQueen)
this.beachList.push(this.crab)
this.beachList.push(this.crabFarmer)
this.beachList.push(this.crabScientist)
this.beachList.push(this.shrimp)
this.beachList.push(this.lobster)
this.beachList.push(this.shark2)
this.beachList.push(this.shark)
// Shark 2
this.sharkRes2 = new Research(
"sharkRes2",
"Great Shark", "Unlock Great Sharks.",
[new Cost(this.game.baseWorld.science, new Decimal(1E9))],
[this.shark2],
this.game
)
// Shark
this.sharkRes = new Research(
"sharkRes",
"Shark", "Unlock Sharks.",
[new Cost(this.game.baseWorld.science, new Decimal(1E6))],
[this.shark, this.sharkRes2],
this.game
)
// lobster
this.lobsterRes = new Research(
"lobsterRes",
"Lobsters", "Unlock lobsters.",
[new Cost(this.game.baseWorld.science, new Decimal(1E5))],
[this.lobster, this.sharkRes],
this.game
)
// shrimp
this.shrimpRes = new Research(
"shrimpRes",
"Shrimps", "Unlock shrimps.",
[new Cost(this.game.baseWorld.science, new Decimal(2E3))],
[this.shrimp],
this.game
)
// Crab Jobs
this.crabJobRes = new Research(
"crabJobRes",
"Crab Jobs", "Unlock more jobs for your crab.",
[new Cost(this.game.baseWorld.science, new Decimal(1.5E3))],
[this.crabFarmer, this.crabScientist],
this.game
)
// Research
this.seaRes = new Research(
"seaRes",
"Sea Helpers", "Unlock Sea Helpers.",
[new Cost(this.game.baseWorld.science, new Decimal(30))],
[this.crab, this.crabQueen, this.crabJobRes, this.shrimpRes, this.lobsterRes],
this.game
)
this.seaRes.avabileBaseWorld = false
this.game.lists.push(new TypeList("Beach", this.beachList))
}
initStuff() {
// Crab
this.crab.actions.push(new BuyAction(this.game,
this.crab,
[new Cost(this.game.baseWorld.food, new Decimal(1E3), this.game.buyExp)]
))
this.crab.actions.push(new UpAction(this.game, this.crab,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, this.game.upgradeScienceExp)]))
this.crab.actions.push(new UpHire(this.game, this.crab,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, this.game.upgradeScienceHireExp)]))
this.game.baseWorld.sand.addProductor(new Production(this.crab))
// Crab Farmer
this.crabFarmer.actions.push(new BuyAction(this.game,
this.crabFarmer,
[
new Cost(this.game.baseWorld.food, new Decimal(1E3), this.game.buyExp),
new Cost(this.game.baseWorld.sand, new Decimal(100), this.game.buyExp),
new Cost(this.crab, new Decimal(1), this.game.buyExpUnit)
]
))
this.crabFarmer.actions.push(new UpAction(this.game, this.crabFarmer,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, this.game.upgradeScienceExp)]))
this.crabFarmer.actions.push(new UpHire(this.game, this.crabFarmer,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, this.game.upgradeScienceHireExp)]))
this.game.baseWorld.fungus.addProductor(new Production(this.crabFarmer))
this.game.baseWorld.sand.addProductor(new Production(this.crabFarmer, new Decimal(-1)))
const specialProduction = new Decimal(15)
const specialCost = new Decimal(-4)
const specialFood = new Decimal(1E7)
const specialRes2 = new Decimal(1E4)
// Crab Scientist
this.crabScientist.actions.push(new BuyAction(this.game,
this.crabScientist,
[
new Cost(this.game.baseWorld.food, specialFood.div(5), this.game.buyExp),
new Cost(this.game.baseWorld.sand, specialRes2.div(5), this.game.buyExp),
new Cost(this.crab, new Decimal(1), this.game.buyExpUnit)
]
))
this.crabScientist.actions.push(new UpAction(this.game, this.crabScientist,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3.times(1.5), this.game.upgradeScienceExp)]))
this.crabScientist.actions.push(new UpHire(this.game, this.crabScientist,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3.times(1.5), this.game.upgradeScienceHireExp)]))
this.game.baseWorld.science.addProductor(new Production(this.crabScientist, specialProduction.times(0.75)))
this.game.baseWorld.sand.addProductor(new Production(this.crabScientist, specialCost))
// Crab Queen ?!
// Not sure if really exists
this.crabQueen.actions.push(new BuyAndUnlockAction(this.game,
this.crabQueen,
[
new Cost(this.game.baseWorld.food, new Decimal(1E5), this.game.buyExp),
new Cost(this.crab, new Decimal(50), this.game.buyExpUnit)
], [this.crabNest]
))
this.crabQueen.actions.push(new UpAction(this.game, this.crabQueen,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3, this.game.upgradeScienceExp)]))
this.crabQueen.actions.push(new UpHire(this.game, this.crabQueen,
[new Cost(this.game.baseWorld.science, this.game.scienceCost3, this.game.upgradeScienceHireExp)]))
this.crab.addProductor(new Production(this.crabQueen))
// Crab Nest
this.crabNest.actions.push(new BuyAction(this.game,
this.crabNest,
[
new Cost(this.game.baseWorld.food, this.game.baseWorld.prestigeFood.div(1.5), this.game.buyExp),
new Cost(this.game.baseWorld.sand, this.game.baseWorld.prestigeOther1.times(2), this.game.buyExp),
new Cost(this.crabQueen, new Decimal(250), this.game.buyExpUnit)
]
))
this.crabNest.actions.push(new UpAction(this.game, this.crabNest,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4, this.game.upgradeScienceExp)]))
this.crabNest.actions.push(new UpHire(this.game, this.crabNest,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4, this.game.upgradeScienceHireExp)]))
this.crabQueen.addProductor(new Production(this.crabNest))
// Shrimp
this.shrimp.actions.push(new BuyAction(this.game,
this.shrimp,
[new Cost(this.game.baseWorld.food, new Decimal(3E3), this.game.buyExp)]
))
this.shrimp.actions.push(new UpAction(this.game, this.shrimp,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, this.game.upgradeScienceExp)]))
this.shrimp.actions.push(new UpHire(this.game, this.shrimp,
[new Cost(this.game.baseWorld.science, this.game.scienceCost2, this.game.upgradeScienceHireExp)]))
this.game.baseWorld.sand.addProductor(new Production(this.shrimp))
this.game.baseWorld.crystal.addProductor(new Production(this.shrimp, new Decimal(0.5)))
// lobster
const lobsterScience = this.game.scienceCost3.times(1.5)
this.lobster.actions.push(new BuyAction(this.game,
this.lobster,
[
new Cost(this.game.baseWorld.food, this.game.machines.price1.times(5000), this.game.buyExp),
new Cost(this.game.baseWorld.sand, this.game.machines.price1.times(1.5), this.game.buyExp)
]
))
this.lobster.actions.push(new UpAction(this.game, this.lobster,
[new Cost(this.game.baseWorld.science, lobsterScience, this.game.upgradeScienceExp)]))
this.lobster.actions.push(new UpHire(this.game, this.lobster,
[new Cost(this.game.baseWorld.science, lobsterScience, this.game.upgradeScienceHireExp)]))
this.game.baseWorld.sand.addProductor(new Production(this.lobster, this.game.machines.machineryProd.div(5)))
this.game.baseWorld.crystal.addProductor(new Production(this.lobster, this.game.machines.machineryProd.div(10)))
// Shark
this.shark.actions.push(new BuyAction(this.game,
this.shark,
[
new Cost(this.game.baseWorld.food, this.game.machines.price1.times(50000), this.game.buyExp),
new Cost(this.game.baseWorld.crystal, this.game.machines.price1.times(5), this.game.buyExp)
]
))
this.shark.actions.push(new UpAction(this.game, this.shark,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4, this.game.upgradeScienceExp)]))
this.shark.actions.push(new UpHire(this.game, this.shark,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4, this.game.upgradeScienceHireExp)]))
this.game.baseWorld.food.addProductor(new Production(this.shark, this.game.machines.machineryProd.times(100)))
this.game.baseWorld.crystal.addProductor(new Production(this.shark, this.game.machines.machineryProd.times(50)))
// Shark 2
this.shark2.actions.push(new BuyAction(this.game,
this.shark2,
[
new Cost(this.game.baseWorld.food, this.game.machines.price1.times(500000), this.game.buyExp),
new Cost(this.shark, new Decimal(100), this.game.buyExpUnit)
]
))
this.shark2.actions.push(new UpAction(this.game, this.shark2,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4.times(5), this.game.upgradeScienceExp)]))
this.shark2.actions.push(new UpHire(this.game, this.shark2,
[new Cost(this.game.baseWorld.science, this.game.scienceCost4.times(5), this.game.upgradeScienceHireExp)]))
this.shark.addProductor(new Production(this.shark2))
}
addWorld() {
World.worldTypes.push(
new World(this.game, "Beach", "A beach",
[this.game.machines.sandDigger, this.game.engineers.sandEnginer],
[],
[new Cost(this.game.beach.crabNest, new Decimal(50))],
[],
[],
[[this.game.beach.seaRes, new Decimal(0)]],
new Decimal(3)
))
World.worldPrefix.push(
new World(this.game, "Coastal", "",
[this.game.machines.sandDigger, this.game.engineers.sandEnginer],
[[this.game.baseWorld.sand, new Decimal(1.5)], [this.game.baseWorld.fungus, new Decimal(0.7)]],
[new Cost(this.game.beach.crabNest, new Decimal(50))],
[[this.game.baseWorld.fungus, new Decimal(0.7)]],
[],
[[this.game.beach.seaRes, new Decimal(0)]],
new Decimal(3)
))
World.worldSuffix.push(
new World(this.game, "of Sharks", "",
[],
[],
[new Cost(this.game.beach.shark2, new Decimal(50))],
[
[this.game.beach.shark, new Decimal(3)],
[this.game.beach.shark2, new Decimal(2)]
],
[],
[[this.game.beach.seaRes, new Decimal(0)]],
new Decimal(3)
))
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.