text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Save } from './save';
/**
* specifies current write state of XmlWriter
*/
export type XmlWriteState =
'Initial' |
'StartDocument' |
'EndDocument' |
'StartElement' |
'EndElement' |
'ElementContent';
/**
* specifies namespace kind
*/
export type NamespaceKind =
'Written' |
'NeedToWrite' |
'Implied' |
'Special';
/**
* XmlWriter class provide method to create XML data
*/
export class XmlWriter {
private bufferText: string;
private bufferBlob: Blob;
private currentState: XmlWriteState;
//namespace fields
private namespaceStack: Namespace[];
//element fields
private elementStack: XmlElement[];
private contentPos: number = 0;
//attribute fields
private attributeStack: XmlAttribute[];
/**
* Gets the content written to the {XmlWriter} as Blob.
* @returns {Blob}
*/
get buffer(): Blob {
this.flush();
return this.bufferBlob;
}
/**
* Initialize new instance of {XmlWriter}
*/
constructor() {
this.bufferText = '';
this.bufferBlob = new Blob([''], { type: 'text/plain' });
this.currentState = 'Initial';
this.namespaceStack = [];
this.namespaceStack.push(new Namespace());
this.namespaceStack[0].set('xmlns', 'http://www.w3.org/2000/xmlns/', 'Special');
this.namespaceStack.push(new Namespace());
this.namespaceStack[1].set('xml', 'http://www.w3.org/XML/1998/namespace', 'Special');
this.namespaceStack.push(new Namespace());
this.namespaceStack[2].set('', '', 'Implied');
this.elementStack = [];
this.elementStack.push(new XmlElement());
this.elementStack[0].set('', '', '', this.namespaceStack.length - 1);
this.attributeStack = [];
Save.isMicrosoftBrowser = !(!navigator.msSaveBlob);
}
/**
* Writes processing instruction with a space between the name and text
* @param {string} name - name of the processing instruction
* @param {string} text - text to write in the processing instruction
* @throws ArgumentException
* @throws InvalidArgumentException
* @throws InvalidOperationException
*/
public writeProcessingInstruction(name: string, text: string): void {
if (name === undefined || name === null || name.length === 0) {
throw new Error('ArgumentException: name should not be undefined, null or empty');
}
this.checkName(name);
if (text === undefined || text === null) {
text = '';
}
if (name.length === 3 && name === 'xml') {
if (this.currentState !== 'Initial') {
// tslint:disable-next-line:max-line-length
throw new Error('InvalidArgumentException: Cannot write XML declaration.WriteStartDocument method has already written it');
}
}
if (this.currentState !== 'Initial' || this.bufferBlob === undefined) {
throw new Error('InvalidOperationException: Wrong Token');
} else {
this.writeStartDocument();
this.writeProcessingInstructionInternal(name, text);
}
}
/**
* Writes Xml declaration with version and standalone attribute
* @param {boolean} standalone - if true it write standalone=yes else standalone=no
* @throws InvalidOperation
*/
public writeStartDocument(standalone?: boolean): void {
if (this.currentState !== 'Initial' || this.bufferBlob === undefined) {
throw new Error('InvalidOperationException: Wrong Token');
}
this.currentState = 'StartDocument';
this.rawText('<?xml version="1.0" encoding="utf-8');
if (standalone !== null && standalone !== undefined) {
this.rawText('" standalone="');
this.rawText(standalone ? 'yes' : 'no');
}
this.rawText('"?>');
}
/**
* Closes any open tag or attribute and write the state back to start
*/
public writeEndDocument(): void {
while (this.elementStack.length - 1 > 0) {
this.writeEndElement();
}
this.currentState = 'EndDocument';
this.flush();
}
/**
* Writes the specified start tag and associates it with the given namespace and prefix.
* @param {string} prefix - namespace prefix of element
* @param {string} localName -localName of element
* @param {string} namespace - namespace URI associate with element
* @throws ArgumentException
* @throws InvalidOperationException
*/
public writeStartElement(prefix: string, localName: string, namespace: string): void {
if (this.bufferBlob === undefined) {
throw new Error('InvalidOperationException: Wrong Token');
}
if (localName === undefined || localName === null || localName.length === 0) {
throw new Error('ArgumentException: localName cannot be undefined, null or empty');
}
this.checkName(localName);
if (this.currentState === 'Initial') {
this.writeStartDocument();
}
if (this.currentState === 'StartElement') {
this.startElementContent();
}
this.currentState = 'StartElement';
if (prefix === undefined || prefix === null) {
if (namespace !== undefined && namespace !== null) {
prefix = this.lookupPrefix(namespace);
}
if (prefix === undefined || prefix === null) {
prefix = '';
}
} else if (prefix.length > 0) {
if (namespace === undefined || namespace === null) {
namespace = this.lookupNamespace(prefix);
}
if (namespace === undefined || namespace === null || (namespace !== undefined && namespace.length === 0)) {
throw new Error('ArgumentException: Cannot use a prefix with an empty namespace');
}
}
if (namespace === undefined || namespace === null) {
namespace = this.lookupNamespace(prefix);
}
this.writeStartElementInternal(prefix, localName, namespace);
}
/**
* Closes one element and pop corresponding namespace scope
*/
public writeEndElement(): void {
if (this.currentState === 'StartElement') {
this.startElementContent();
this.currentState = 'ElementContent';
} else if (this.currentState === 'ElementContent') {
this.currentState = 'ElementContent';
}
this.currentState = 'EndElement';
let top: number = this.elementStack.length - 1;
this.writeEndElementInternal(this.elementStack[top].prefix, this.elementStack[top].localName);
this.namespaceStack.splice(this.elementStack[top].previousTop + 1);
this.elementStack.splice(top);
if (this.bufferText.length > 10240) {
this.flush();
}
}
/**
* Writes an element with the specified prefix, local name, namespace URI, and value.
* @param {string} prefix - namespace prefix of element
* @param {string} localName - localName of element
* @param {string} namespace - namespace URI associate with element
* @param {string} value - value of element
*/
public writeElementString(prefix: string, localName: string, namespace: string, value: string): void {
this.writeStartElement(prefix, localName, namespace);
if (value !== undefined && value !== null && value.length !== 0) {
this.writeString(value);
}
this.writeEndElement();
}
/**
* Writes out the attribute with the specified prefix, local name, namespace URI, and value
* @param {string} prefix - namespace prefix of element
* @param {string} localName - localName of element
* @param {string} namespace - namespace URI associate with element
* @param {string} value - value of element
*/
public writeAttributeString(prefix: string, localName: string, namespace: string, value: string): void {
this.writeStartAttribute(prefix, localName, namespace, value);
this.writeStringInternal(value, true);
this.writeEndAttribute();
}
/**
* Writes the given text content
* @param {string} text - text to write
* @throws InvalidOperationException
*/
public writeString(text: string): void {
this.writeInternal(text, false);
}
/**
* Write given text as raw data
* @param {string} text - text to write
* @throws InvalidOperationException
*/
public writeRaw(text: string): void {
this.writeInternal(text, true);
}
private writeInternal(text: string, isRawString: boolean): void {
if (text === undefined || text === null) {
return;
} else {
if (this.currentState !== 'StartElement' && this.currentState !== 'ElementContent') {
throw new Error('InvalidOperationException: Wrong Token');
}
if (this.currentState === 'StartElement') {
this.startElementContent();
}
this.currentState = 'ElementContent';
if (isRawString) {
this.rawText(text);
} else {
this.writeStringInternal(text, false);
}
}
}
/**
* Saves the file with specified name and sends the file to client browser
* @param {string} fileName - file name
*/
public save(fileName: string): void {
while (this.elementStack.length - 1 > 0) {
this.writeEndElement();
}
if (this.bufferText !== '') {
this.flush();
}
Save.save(fileName, this.buffer);
}
/**
* Releases the resources used by XmlWriter.
*/
public destroy(): void {
this.bufferBlob = undefined;
for (let i: number = 0; i < this.namespaceStack.length; i++) {
this.namespaceStack[i].destroy();
}
this.namespaceStack = [];
for (let i: number = 0; i < this.elementStack.length; i++) {
this.elementStack[i].destroy();
}
this.elementStack = [];
this.bufferText = '';
this.contentPos = 0;
}
private flush(): void {
if (this.bufferBlob === undefined) {
return;
}
this.bufferBlob = new Blob([this.bufferBlob, this.bufferText], { type: 'text/plain' });
this.bufferText = '';
}
private writeProcessingInstructionInternal(name: string, text: string): void {
this.bufferText += '<?';
this.rawText(name);
if (text.length > 0) {
this.bufferText += ' ';
text = text.replace(/\?\>/g, '? >');
this.bufferText += text;
}
this.bufferText += '?';
this.bufferText += '>';
}
private writeStartAttribute(prefix: string, localName: string, namespace: string, value: string): void {
if (localName === undefined || localName === null || localName.length === 0) {
if (prefix === 'xmlns') {
localName = 'xmlns';
prefix = '';
} else {
throw new Error('ArgumentException: localName cannot be undefined, null or empty');
}
}
if (this.currentState !== 'StartElement') {
throw new Error('InvalidOperationException: Wrong Token');
}
this.checkName(localName);
this.writeStartAttributePrefixAndNameSpace(prefix, localName, namespace, value);
}
private writeStartAttributePrefixAndNameSpace(prefix: string, localName: string, namespace: string, value: string): void {
if (prefix === undefined || prefix === null) {
if (namespace !== undefined && namespace !== null) {
if (!(localName === 'xmlns' && namespace === 'http://www.w3.org/2000/xmlns/')) {
prefix = this.lookupPrefix(namespace);
}
}
if (prefix === undefined || prefix === null) {
prefix = '';
}
}
if (namespace === undefined || namespace === null) {
if (prefix !== undefined && prefix !== null && prefix.length > 0) {
namespace = this.lookupNamespace(prefix);
}
if (namespace === undefined || namespace === null) {
namespace = '';
}
}
this.writeStartAttributeSpecialAttribute(prefix, localName, namespace, value);
}
private writeStartAttributeSpecialAttribute(prefix: string, localName: string, namespace: string, value: string): void {
if (prefix.length === 0) {
if (localName[0] === 'x' && localName === 'xmlns') {
this.skipPushAndWrite(prefix, localName, namespace);
this.pushNamespaceExplicit('', value);
return;
} else if (namespace.length > 0) {
prefix = this.lookupPrefix(namespace);
}
} else {
if (prefix[0] === 'x') {
if (prefix === 'xmlns') {
this.skipPushAndWrite(prefix, localName, namespace);
this.pushNamespaceExplicit(localName, value);
return;
} else if (prefix === 'xml') {
if (localName === 'space' || localName === 'lang') {
this.skipPushAndWrite(prefix, localName, namespace);
return;
}
}
}
if (namespace.length === 0) {
prefix = '';
}
}
if (prefix !== undefined && prefix !== null && prefix.length !== 0) {
this.pushNamespaceImplicit(prefix, namespace);
}
this.skipPushAndWrite(prefix, localName, namespace);
}
private writeEndAttribute(): void {
this.currentState = 'StartElement';
this.bufferText += '"';
}
private writeStartElementInternal(prefix: string, localName: string, namespace: string): void {
this.bufferText += '<';
if (prefix.length > 0) {
this.rawText(prefix);
this.bufferText += ':';
}
this.rawText(localName);
let top: number = this.elementStack.length;
this.elementStack.push(new XmlElement());
this.elementStack[top].set(prefix, localName, namespace, this.namespaceStack.length - 1);
this.pushNamespaceImplicit(prefix, namespace);
for (let i: number = 0; i < this.attributeStack.length; i++) {
this.attributeStack[i].destroy();
}
this.attributeStack = [];
}
private writeEndElementInternal(prefix: string, localName: string): void {
if (this.contentPos !== this.bufferText.length + 1) {
this.bufferText += '</';
if (prefix !== undefined && prefix !== null && prefix.length !== 0) {
this.rawText(prefix);
this.bufferText += ':';
}
this.rawText(localName);
this.bufferText += '>';
} else {
this.bufferText = this.bufferText.substring(0, this.bufferText.length - 1);
this.bufferText += ' />';
}
}
private writeStartAttributeInternal(prefix: string, localName: string, namespaceName: string): void {
this.bufferText += ' ';
if (prefix !== undefined && prefix !== null && prefix.length > 0) {
this.rawText(prefix);
this.bufferText += ':';
}
this.rawText(localName);
this.bufferText += '=';
this.bufferText += '"';
}
private writeNamespaceDeclaration(prefix: string, namespaceUri: string): void {
this.writeStartNamespaceDeclaration(prefix);
this.writeStringInternal(namespaceUri, true);
this.bufferText += '"';
}
private writeStartNamespaceDeclaration(prefix: string): void {
if (prefix === undefined || prefix === null || prefix.length === 0) {
this.rawText(' xmlns=\"');
} else {
this.rawText(' xmlns:');
this.rawText(prefix);
this.bufferText += '=';
this.bufferText += '"';
}
}
private writeStringInternal(text: string, inAttributeValue: boolean): void {
if (text === null || text === undefined) {
text = '';
}
let tempText: string = '';
text = text.replace(/\&/g, '&');
text = text.replace(/\</g, '<');
text = text.replace(/\>/g, '>');
if (inAttributeValue) {
text = text.replace(/\"/g, '"');
}
this.bufferText += text;
if (!inAttributeValue) {
this.contentPos = 0;
}
}
private startElementContent(): void {
let start: number = this.elementStack[this.elementStack.length - 1].previousTop;
for (let i: number = this.namespaceStack.length - 1; i > start; i--) {
if (this.namespaceStack[i].kind === 'NeedToWrite') {
this.writeNamespaceDeclaration(this.namespaceStack[i].prefix, this.namespaceStack[i].namespaceUri);
}
}
this.bufferText += '>';
this.contentPos = this.bufferText.length + 1;
}
private rawText(text: string): void {
this.bufferText += text;
}
private addNamespace(prefix: string, ns: string, kind: NamespaceKind): void {
let top: number = this.namespaceStack.length;
this.namespaceStack.push(new Namespace());
this.namespaceStack[top].set(prefix, ns, kind);
}
private lookupPrefix(namespace: string): string {
for (let i: number = this.namespaceStack.length - 1; i >= 0; i--) {
if (this.namespaceStack[i].namespaceUri === namespace) {
return this.namespaceStack[i].prefix;
}
}
return undefined;
}
private lookupNamespace(prefix: string): string {
for (let i: number = this.namespaceStack.length - 1; i >= 0; i--) {
if (this.namespaceStack[i].prefix === prefix) {
return this.namespaceStack[i].namespaceUri;
}
}
return undefined;
}
private lookupNamespaceIndex(prefix: string): number {
for (let i: number = this.namespaceStack.length - 1; i >= 0; i--) {
if (this.namespaceStack[i].prefix === prefix) {
return i;
}
}
return -1;
}
private pushNamespaceImplicit(prefix: string, ns: string): void {
let kind: NamespaceKind;
let existingNsIndex: number = this.lookupNamespaceIndex(prefix);
if (existingNsIndex !== -1) {
if (existingNsIndex > this.elementStack[this.elementStack.length - 1].previousTop) {
if (this.namespaceStack[existingNsIndex].namespaceUri !== ns) {
throw new Error('XmlException namespace Uri needs to be the same as the one that is already declared');
}
return;
} else {
if (this.namespaceStack[existingNsIndex].kind === 'Special') {
if (prefix === 'xml') {
if (ns !== this.namespaceStack[existingNsIndex].namespaceUri) {
throw new Error('InvalidArgumentException: Xml String');
} else {
kind = 'Implied';
}
} else {
throw new Error('InvalidArgumentException: Prefix "xmlns" is reserved for use by XML.');
}
} else {
kind = (this.namespaceStack[existingNsIndex].namespaceUri === ns) ? 'Implied' : 'NeedToWrite';
}
}
} else {
if ((ns === 'http://www.w3.org/XML/1998/namespace' && prefix !== 'xml') ||
(ns === 'http://www.w3.org/2000/xmlns/' && prefix !== 'xmlns')) {
throw new Error('InvalidArgumentException');
}
kind = 'NeedToWrite';
}
this.addNamespace(prefix, ns, kind);
}
private pushNamespaceExplicit(prefix: string, ns: string): void {
let existingNsIndex: number = this.lookupNamespaceIndex(prefix);
if (existingNsIndex !== -1) {
if (existingNsIndex > this.elementStack[this.elementStack.length - 1].previousTop) {
this.namespaceStack[existingNsIndex].kind = 'Written';
return;
}
}
this.addNamespace(prefix, ns, 'Written');
return;
}
private addAttribute(prefix: string, localName: string, namespaceName: string): void {
let top: number = this.attributeStack.length;
this.attributeStack.push(new XmlAttribute());
this.attributeStack[top].set(prefix, localName, namespaceName);
for (let i: number = 0; i < top; i++) {
if (this.attributeStack[i].isDuplicate(prefix, localName, namespaceName)) {
throw new Error('XmlException: duplicate attribute name');
}
}
}
private skipPushAndWrite(prefix: string, localName: string, namespace: string): void {
this.addAttribute(prefix, localName, namespace);
this.writeStartAttributeInternal(prefix, localName, namespace);
}
private checkName(text: string): void {
let format: RegExp = /[ !@#$%^&*()+\=\[\]{};':"\\|,<>\/?]/;
if (format.test(text)) {
throw new Error('InvalidArgumentException: invalid name character');
}
}
}
/**
* class for managing namespace collection
*/
export class Namespace {
/**
* specifies namespace's prefix
*/
public prefix: string;
/**
* specifies namespace URI
*/
public namespaceUri: string;
/**
* specifies namespace kind
*/
public kind: NamespaceKind;
/**
* set value for current namespace instance
* @param {string} prefix namespace's prefix
* @param {string} namespaceUri namespace URI
* @param {string} kind namespace kind
*/
public set(prefix: string, namespaceUri: string, kind: NamespaceKind): void {
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.kind = kind;
}
/**
* Releases the resources used by Namespace
*/
public destroy(): void {
this.prefix = undefined;
this.namespaceUri = undefined;
this.kind = undefined;
}
}
/**
* class for managing element collection
*/
export class XmlElement {
/**
* specifies previous namespace top
*/
public previousTop: number;
/**
* specifies element prefix
*/
public prefix: string;
/**
* specifies element localName
*/
public localName: string;
/**
* specified namespace URI
*/
public namespaceUri: string;
/**
* set value of current element
* @param {string} prefix - element prefix
* @param {string} localName - element local name
* @param {string} namespaceUri -namespace URI
* @param {string} previousTop - previous namespace top
*/
public set(prefix: string, localName: string, namespaceUri: string, previousTop: number): void {
this.previousTop = previousTop;
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
}
/**
* Releases the resources used by XmlElement
*/
public destroy(): void {
this.previousTop = undefined;
this.prefix = undefined;
this.localName = undefined;
this.namespaceUri = undefined;
}
}
/**
* class for managing attribute collection
*/
export class XmlAttribute {
/**
* specifies namespace's prefix
*/
public prefix: string;
/**
* specifies namespace URI
*/
public namespaceUri: string;
/**
* specifies attribute local name
*/
public localName: string;
/**
* set value of current attribute
* @param {string} prefix - namespace's prefix
* @param {string} namespaceUri - namespace URI
* @param {string} localName - attribute localName
*/
public set(prefix: string, localName: string, namespaceUri: string): void {
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
}
/**
* get whether the attribute is duplicate or not
* @param {string} prefix - namespace's prefix
* @param {string} namespaceUri - namespace URI
* @param {string} localName - attribute localName
*/
public isDuplicate(prefix: string, localName: string, namespaceUri: string): boolean {
return ((this.localName === localName) && ((this.prefix === prefix) || (this.namespaceUri === namespaceUri)));
}
/**
* Releases the resources used by XmlAttribute
*/
public destroy(): void {
this.prefix = undefined;
this.namespaceUri = undefined;
this.localName = undefined;
}
} | the_stack |
const maxIn = 255;
const parse = (d: string, len = 2): string => {
let res;
res = `${d}`;
if (res.length < len) {
res = '0'.repeat(len - res.length) + res;
} else {
res = res.slice(0, len);
}
return res;
};
const limit = (number, min, max) => Math.min(max, Math.max(min, number));
export class Color {
decode(color: string) {
let rgb;
if (/^rgb/.test(color)) {
const matcher =
color.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([\.\d]+))?\)/) ||
[];
rgb = [matcher[1], matcher[2], matcher[3]].map(item => parseInt(item, 10));
let alpha: string | number = matcher[4];
if (alpha !== undefined) {
alpha = Number(alpha) > 1 ? 1 : Number(alpha) < 0 ? 0 : alpha;
rgb.push(alpha);
}
return rgb;
}
let newColor = color.replace(/^#/, '');
const len = newColor.length;
if (len !== 6 && len !== 3) {
newColor = '000000';
}
if (len === 3) {
rgb = newColor.split('').map(item => `${item}${item}`);
} else {
rgb = newColor.match(/[0-9a-f]{2}/gi) || [];
}
return rgb.map(i => {
let idx = parseInt(i, 16);
if (idx < 0) idx = 0;
if (idx > maxIn) idx = maxIn;
return idx;
});
}
hex2hsv(hex: string) {
let [r, g, b] = this.decode(hex);
r /= maxIn;
g /= maxIn;
b /= maxIn;
const M = Math.max(r, g, b);
const m = Math.min(r, g, b);
const C = M - m;
let h;
let s;
let v;
if (C === 0) h = 0;
else if (M === r) h = ((g - b) / C) % 6;
else if (M === g) h = (b - r) / C + 2;
else h = (r - g) / C + 4;
h *= 60;
if (h < 0) h += 360;
v = M;
if (C === 0) s = 0;
else s = C / v;
s *= 100;
v *= 100;
return [h, s, v];
}
hex2hsb(hex: string) {
return this.hex2hsv(hex);
}
rgb2hex(r: number, g: number, b: number): string {
let hex: string | number = Math.round(r * 65536) + Math.round(g * 256) + Math.round(b);
hex = hex.toString(16);
const len = hex.length;
if (len < 6) for (let i = 0; i < 6 - len; i++) hex = `0${hex}`;
hex = hex.toUpperCase();
return `#${hex}`;
}
hex2hsl(hex: string): number[] {
let [r, g, b] = this.decode(hex);
r /= maxIn;
g /= maxIn;
b /= maxIn;
const M = Math.max(r, g, b);
const m = Math.min(r, g, b);
const d = M - m;
let h;
let l;
let s;
if (d === 0) h = 0;
else if (M === r) h = ((g - b) / d) % 6;
else if (M === g) h = (b - r) / d + 2;
else h = (r - g) / d + 4;
h *= 60;
if (h < 0) h += 360;
l = (M + m) / 2;
if (d === 0) s = 0;
else s = d / (1 - Math.abs(2 * l - 1));
s *= 100;
l *= 100;
return [h, s, l];
}
hex2yuv(hex: string) {
const [r, g, b] = this.decode(hex);
const y = r * 0.299 + g * 0.587 + b * 0.114;
const u = r * -0.168736 + g * -0.331264 + b * 0.5 + 128;
const v = r * 0.5 + g * -0.418688 + b * -0.081312 + 128;
return [y, u, v];
}
yuv2rgb(y: number, u: number, v: number, a?: number) {
let r;
let g;
let b;
// y = parseInt(y);
// u = parseInt(u);
// v = parseInt(v);
r = y + 1.4075 * (v - 128);
g = y - 0.3455 * (u - 128) - 0.7169 * (v - 128);
b = y + 1.779 * (u - 128);
// r = Math.floor(r);
// g = Math.floor(g);
// b = Math.floor(b);
r = r < 0 ? 0 : r;
r = r > maxIn ? maxIn : r;
g = g < 0 ? 0 : g;
g = g > maxIn ? maxIn : g;
b = b < 0 ? 0 : b;
b = b > maxIn ? maxIn : b;
const rgb = [r, g, b];
if (a !== undefined) {
rgb.push(a > 1 ? 1 : a < 0 ? 0 : a);
}
return rgb;
}
hsv2rgb(h = 0, s = 0, v = 0, a?: number): number[] {
const hsb = [h, s, v].map((bit, i) => {
let _bit = bit;
if (_bit) _bit = parseFloat(_bit.toString());
if (i === 0) {
_bit %= 360;
const res = _bit < 0 ? _bit + 360 : _bit;
return res;
}
return limit(Math.round(bit), 0, 100);
});
const br = Math.round((hsb[2] / 100) * 255);
if (hsb[1] === 0) return [br, br, br];
const hue = hsb[0];
const f = hue % 60;
const p = Math.round(((hsb[2] * (100 - hsb[1])) / 10000) * 255);
const q = Math.round(((hsb[2] * (6000 - hsb[1] * f)) / 600000) * 255);
const t = Math.round(((hsb[2] * (6000 - hsb[1] * (60 - f))) / 600000) * 255);
let rgb;
switch (Math.floor(hue / 60)) {
case 0:
rgb = [br, t, p];
break;
case 1:
rgb = [q, br, p];
break;
case 2:
rgb = [p, br, t];
break;
case 3:
rgb = [p, q, br];
break;
case 4:
rgb = [t, p, br];
break;
default:
rgb = [br, p, q];
break;
}
if (a !== undefined) {
rgb.push(limit(Number(a), 0, 1));
}
return rgb;
}
hsb2rgb(h: number, s: number, b: number, a: number) {
return this.hsv2rgb(h, s, b, a);
}
rgb2hsv(r = 0, g = 0, b = 0) {
let red = parseFloat(r.toString());
let green = parseFloat(g.toString());
let blue = parseFloat(b.toString());
if (red < 0) red = 0;
if (green < 0) green = 0;
if (blue < 0) blue = 0;
if (red > 255) red = 255;
if (green > 255) green = 255;
if (blue > 255) blue = 255;
red /= 255;
green /= 255;
blue /= 255;
const M = Math.max(red, green, blue);
const m = Math.min(red, green, blue);
const C = M - m;
let h;
let s;
let v;
if (C === 0) h = 0;
else if (M === red) h = ((green - blue) / C) % 6;
else if (M === green) h = (blue - red) / C + 2;
else h = (red - green) / C + 4;
h *= 60;
if (h < 0) h += 360;
v = M;
if (C === 0) s = 0;
else s = C / v;
s *= 100;
v *= 100;
return [h, s, v];
}
rgb2hsb(r: number, g: number, b: number) {
return this.rgb2hsv(r, g, b);
}
hsv2hex(h: number, s: number, v: number): string {
const rgb = this.hsv2rgb(h, s, v).map(item => Math.round(item));
return this.rgb2hex.apply(this, rgb);
}
hsb2hex(h: number, s: number, b: number): string {
return this.hsv2hex(h, s, b);
}
rgb2hsl(r = 0, g = 0, b = 0): number[] {
let red = parseFloat(r.toString());
let green = parseFloat(g.toString());
let blue = parseFloat(b.toString());
if (red < 0) red = 0;
if (green < 0) green = 0;
if (blue < 0) blue = 0;
if (red > 255) red = 255;
if (green > 255) green = 255;
if (blue > 255) blue = 255;
red /= 255;
green /= 255;
blue /= 255;
const M = Math.max(red, green, blue);
const m = Math.min(red, green, blue);
const d = M - m;
let h;
let s;
let l;
if (d === 0) h = 0;
else if (M === red) h = ((green - blue) / d) % 6;
else if (M === green) h = (blue - red) / d + 2;
else h = (red - green) / d + 4;
h *= 60;
if (h < 0) h += 360;
l = (M + m) / 2;
if (d === 0) s = 0;
else s = d / (1 - Math.abs(2 * l - 1));
s *= 100;
l *= 100;
h = h.toFixed(0);
s = s.toFixed(0);
l = l.toFixed(0);
return [h, s, l];
}
hsl2rgb(h = 0, s = 0, l = 0, a?: number): number[] {
let hue = parseFloat(h.toString());
let sat = parseFloat(s.toString());
let lit = parseFloat(l.toString());
if (hue < 0) hue = 0;
if (sat < 0) sat = 0;
if (lit < 0) lit = 0;
if (hue >= 360) hue = 359;
if (sat > 100) sat = 100;
if (lit > 100) lit = 100;
sat /= 100;
lit /= 100;
const C = (1 - Math.abs(2 * lit - 1)) * sat;
const hh = hue / 60;
const X = C * (1 - Math.abs((hh % 2) - 1));
let r = 0;
let g = 0;
let b = 0;
if (hh >= 0 && hh < 1) {
r = C;
g = X;
} else if (hh >= 1 && hh < 2) {
r = X;
g = C;
} else if (hh >= 2 && hh < 3) {
g = C;
b = X;
} else if (hh >= 3 && hh < 4) {
g = X;
b = C;
} else if (hh >= 4 && hh < 5) {
r = X;
b = C;
} else {
r = C;
b = X;
}
const m = lit - C / 2;
r += m;
g += m;
b += m;
r *= maxIn;
g *= maxIn;
b *= maxIn;
const rgb = [r, g, b];
if (a !== undefined) {
rgb.push(a > 1 ? 1 : a < 0 ? 0 : a);
}
return rgb;
}
hsl2hex(h: number, s: number, l: number): string {
const [r, g, b] = this.hsl2rgb(h, s, l);
return this.rgb2hex(r, g, b);
}
randomRgb(min = 0, max = 255): number[] {
const random = (mi, ma) => {
let x = max;
let y = min;
if (x < y) {
x = mi;
y = ma;
}
return Math.random() * (x - y) + y;
};
return [random(min, max), random(min, max), random(min, max)];
}
randomHsb(): number[] {
const random = (min, max) => {
let x = max;
let y = min;
if (x < y) {
x = min;
y = max;
}
return Math.random() * (x - y) + y;
};
return [random(0, 360), random(0, 100), random(0, 100)];
}
// 补色
complement(color: string): string {
const rgb = this.decode(color).map(item => Math.round(item));
const mm = Math.min(...rgb) + Math.max(...rgb);
const [r, g, b] = rgb.map(item => mm - item);
const hex = this.rgb2hex(r, g, b);
return hex;
}
// 反相
reversed(color: string): string {
const rgb = this.decode(color).map(item => Math.round(item));
const [r, g, b] = rgb.map(item => maxIn - item);
return this.rgb2hex(r, g, b);
}
hex2RgbString(hex: string, a?: number): string {
const rgb = this.decode(hex);
return toRgbString(rgb, a);
}
hsv2RgbString(h: number, s: number, v: number, a?: number): string {
const rgb = this.hsv2rgb(h, s, v, a);
return toRgbString(rgb);
}
hsb2RgbString(...args): string {
return this.hsv2RgbString.apply(this, args);
}
hsl2RgbString(h: number, s: number, l: number, a?: number): string {
const rgb = this.hsl2rgb(h, s, l, a);
return toRgbString(rgb);
}
yuv2RgbString(y: number, u: number, v: number, a?: number): string {
const rgb = this.yuv2rgb(y, u, v, a);
return toRgbString(rgb);
}
encodeColorData(rgbhsv: number[]): string {
const rgbStr = rgbhsv.slice(0, 3);
let hsv = rgbhsv.slice(3);
const rgb = rgbStr.map(item => (item < 0 ? 0 : item > 255 ? 255 : item));
if (hsv.length === 0) {
hsv = Array(4).fill(0);
} else {
let h = Number(hsv[0]);
h = h % 360 ? h % 360 : h;
h = h < 0 ? 360 + h : h;
const hh = Math.floor(h / 256);
const hl = Math.floor(h % 256);
hsv.splice(1, 0, hl);
hsv[0] = hh;
}
return rgb
.concat(hsv)
.map(item => parse(Math.round(Number(item)).toString(16), 2))
.join('');
}
decodeColorData(data = ''): number[] {
// rrggbbhhhlssvv
// hh 小于等于255色相值
// hl 大于255小于等于360的色相值
const arr1 = data.match(/[a-z\d]{2}/gi) || [];
const len = 7 - arr1.length;
const arr2 = Array(len < 0 ? 0 : len).fill('00');
const arr = arr1.concat(arr2);
const hsv = arr.slice(3);
const rgb = arr.slice(0, 3).map(item => parseInt(item, 16));
const h = parseInt(hsv[0] + hsv[1], 16);
const s = parseInt(hsv[2], 16);
const v = parseInt(hsv[3], 16);
return [...rgb, h, s, v];
}
decodeColorDataWithPosition(data = ''): number[] {
// rrggbbxxyyvv00
// xx 0 - 100 x坐标
// yy 0 - 100 y坐标
const arr1 = data.match(/[a-z\d]{2}/gi) || [];
const len = 7 - arr1.length;
const arr2 = Array(len < 0 ? 0 : len).fill('00');
const arr = arr1.concat(arr2);
const rs = arr.map(item => parseInt(item, 16));
rs[3] /= 100;
rs[4] /= 100;
return rs;
}
encodeColorDataWithPosition(rgbxyve: number[]): string {
let rgb = rgbxyve.slice(0, 3);
let xyve = rgbxyve.slice(3);
rgb = rgb.map(item => (item < 0 ? 0 : item > 255 ? 255 : item));
let len = 4 - xyve.length;
len = len < 0 ? 0 : len;
xyve = xyve.concat(Array(len).fill(0));
const [x, y] = xyve;
xyve[0] = x * 100;
xyve[1] = y * 100;
return rgb
.concat(xyve)
.map(item => parse(Math.round(item).toString(16), 2))
.join('');
}
encodeSceneData(data): string | number[] {
if (data.length === 0) {
return '';
}
const reduce = (d, init) =>
d.reduce((curr, next) => {
if (next.concat) {
return reduce(next, curr);
}
return curr + parse(Math.round(next).toString(16), 2);
}, init);
return reduce(data, '');
}
decodeSceneData(data): number[] {
if (!data) {
return [];
}
// l 亮度
// t 色温
// f 变化频率
// c 可变化的颜色数量
// [r,g,b,r,g,b,r,g,b]
const arr = data.match(/[a-z\d]{2}/gi);
const [l, t, f, c, ...d] = arr;
const ltfc = [l, t, f, c].map(item => parseInt(item, 16));
const rgbs = [];
const count = Math.min(ltfc[3], d.length / 3) || 1;
ltfc[3] = count;
for (let i = 0; i < count; i++) {
const n = i * 3 - 1;
// @ts-ignore
rgbs.push([d[n + 1], d[n + 2], d[n + 3]].map(item => parseInt(item, 16)));
}
return ltfc.concat(rgbs);
}
// data = [l,t,f,c,m,r,g,b,h,s,v,b,t,m,r,g,b,h,s,v,b,t]
decodeSceneDataWithMode(data): number[] {
if (!data) {
return [];
}
// l 亮度
// t 色温
// f 变化频率
// c 可变化的颜色数量
// [m,r,g,b,b,t,x,y,m,r,g,b,b,t,x,y,m,r,g,b,b,t,x,y]
// m 模式
// r,g,b 红绿蓝
// b 白光亮度 t白光色温
// x,y为坐标
const arr = data.match(/[a-z\d]{2}/gi);
const [l, t, f, c, ...d] = arr;
const ltfc = [l, t, f, c].map(item => parseInt(item, 16));
const mrgbhsvbt = [];
const count = Math.min(ltfc[3], d.length / 8);
ltfc[3] = count;
for (let i = 0; i < count; i++) {
const n = i * 8 - 1;
const _arr: number[] = [];
let j = 1;
while (j < 9) {
_arr.push(d[n + j]);
j++;
}
// @ts-ignore
mrgbhsvbt.push(_arr.map(item => parseInt(item, 16)));
}
return ltfc.concat(mrgbhsvbt);
}
toRgbString(rgb: number[], a?: number): string {
return toRgbString(rgb, a);
}
/**
*
* Neil Bartlett
* neilbartlett.com
* 2015-01-22
*
* Copyright [2015] [Neil Bartlett] *
*
* Color Temperature is the color due to black body radiation at a given
* temperature. The temperature is given in Kelvin. The concept is widely used
* in photography and in tools such as f.lux.
*
* The function here converts a given color temperature into a near equivalent
* in the RGB colorspace. The function is based on a curve fit on standard sparse
* set of Kelvin to RGB mappings.
*
* Two conversions are presented here. The one colorTempertature2RGBUSingTH
* is a JS version of the algorithm developed by Tanner Helland. The second is a
* slightly more accurate conversion based on a refitting of the original data
* using different curve fit functions. The performance cost of the two
* approaches is very similar and in general the second algorithm is preferred.
*
* NOTE The approximations used are suitable for photo-mainpulation and other
* non-critical uses. They are not suitable for medical or other high accuracy
* use cases.
*
* Accuracy is best between 1000K and 40000K.
*
* See http://github.com/neilbartlett/color-temperature for further details.
*
* */
/**
* A JS verion of Tanner Helland's original algorithm.
* Input: color temperature in degrees Kelvin
* Output: json object of red, green and blue components of the Kelvin temperature
*/
kelvin2rgbUsingTH(kelvin: number): number[] {
const temperature = kelvin / 100.0;
let red;
let green;
let blue;
if (temperature <= 66.0) {
red = 255;
} else {
red = temperature - 60.0;
red = 329.698727446 * Math.pow(red, -0.1332047592);
if (red < 0) red = 0;
if (red > 255) red = 255;
}
/* Calculate green */
if (temperature <= 66.0) {
green = temperature;
green = 99.4708025861 * Math.log(green) - 161.1195681661;
if (green < 0) green = 0;
if (green > 255) green = 255;
} else {
green = temperature - 60.0;
green = 288.1221695283 * Math.pow(green, -0.0755148492);
if (green < 0) green = 0;
if (green > 255) green = 255;
}
/* Calculate blue */
if (temperature >= 66.0) {
blue = 255;
} else if (temperature <= 19.0) {
blue = 0;
} else {
blue = temperature - 10;
blue = 138.5177312231 * Math.log(blue) - 305.0447927307;
if (blue < 0) blue = 0;
if (blue > 255) blue = 255;
}
return [red, green, blue];
}
/**
* A more accurate version algorithm based on a different curve fit to the
* original RGB to Kelvin data.
* Input: color temperature in degrees Kelvin
* Output: json object of red, green and blue components of the Kelvin temperature
*/
kelvin2rgb(kelvin: number): number[] {
const temperature = kelvin / 100.0;
let red;
let green;
let blue;
if (temperature < 66.0) {
red = 255;
} else {
red = temperature - 55.0;
red = 351.97690566805693 + 0.114206453784165 * red - 40.25366309332127 * Math.log(red);
if (red < 0) red = 0;
if (red > 255) red = 255;
}
/* Calculate green */
if (temperature < 66.0) {
green = temperature - 2;
green =
-155.25485562709179 - 0.44596950469579133 * green + 104.49216199393888 * Math.log(green);
if (green < 0) green = 0;
if (green > 255) green = 255;
} else {
green = temperature - 50.0;
green = 325.4494125711974 + 0.07943456536662342 * green - 28.0852963507957 * Math.log(green);
if (green < 0) green = 0;
if (green > 255) green = 255;
}
/* Calculate blue */
if (temperature >= 66.0) {
blue = 255;
} else if (temperature <= 20.0) {
blue = 0;
} else {
blue = temperature - 10;
blue = -254.76935184120902 + 0.8274096064007395 * blue + 115.67994401066147 * Math.log(blue);
if (blue < 0) blue = 0;
if (blue > 255) blue = 255;
}
return [red, green, blue];
}
/**
convert an rgb in JSON format into to a Kelvin color temperature
*/
rgb2kelvin([r, , b]): number {
const epsilon = 0.4;
let temperature;
let minTemperature = 1000;
let maxTemperature = 40000;
while (maxTemperature - minTemperature > epsilon) {
temperature = (maxTemperature + minTemperature) / 2;
const [_r, , _b] = this.kelvin2rgb(temperature);
if (_b / _r >= b / r) {
maxTemperature = temperature;
} else {
minTemperature = temperature;
}
}
return Math.round(temperature);
}
}
const toRgbString = (originRgb: number[], a?: number): string => {
const len = originRgb.length;
let alpha;
if (len === 4) {
alpha = originRgb.pop();
}
const rgb = originRgb.map(item => Math.round(item));
if (len === 4) {
rgb.push(alpha);
return `rgba(${rgb.join(', ')})`;
}
if (a !== undefined && rgb.length === 3) {
rgb.push(a > 1 ? 1 : a < 0 ? 0 : a);
return `rgba(${rgb.join(', ')})`;
}
return `rgb(${rgb.join(', ')})`;
};
const color = new Color();
/*
brightRate = [0-100]
temperatureRate = [0-100]
*/
const calculateWhiteColorForView = (brightRate: number, temperatureRate: number): string => {
const alphaMin = 0.6;
const alphaMax = 1;
const sMin = 0;
const sMax = 60;
const hue = 36.8;
const sat = (temperatureRate * (sMax - sMin)) / 100;
const alpha = alphaMin + (brightRate / 100) * (alphaMax - alphaMin);
const rgb = color.hsb2RgbString(hue, sat, 100, alpha);
return rgb;
};
/**
* @fileOverview 颜色相关工具
* HSV和HSL解释 解释 https://zh.wikipedia.org/wiki/HSL%E5%92%8CHSV%E8%89%B2%E5%BD%A9%E7%A9%BA%E9%97%B4
* @name color.js
*/
/* eslint-disable */
function _gcd(a: number, b: number): number {
return !b ? a : _gcd(b, a % b);
}
function getSolutionOfLinearConguenceEquation(a: number, b: number, n: number): boolean | number[] {
let d;
if (a * b === 0) {
return false;
}
d = _gcd(a, n);
return [b];
}
/**
* hsv转rgb, 来自维基百科的公式的完整实现, 变量名都没改
* @example
* hsvToRgb(0, 1, 1) = {r: 255, g: 0, b: 0}
* hsvToRgb(0.5, 1, 0.5) = {r: 128, g: 1, b: 0}
* @param {Number} h - hue表示色相, 0°~360°
* @param {Number} s - Saturation饱和度,0%~100%
* @param {Number} v - Value表示明度, 0%~100%
* @returns {Object} RGB的颜色值
* r - red, 0~255
* g - green, 0~255
* b - blue, 0~255
*/
function hsvToRgb(h: number, s: number, v: number): { r: number; g: number; b: number } {
let r, g, b, i, f, p, q, t;
// Make sure our arguments stay in-range
h = Math.max(0, Math.min(360, h));
s = Math.max(0, Math.min(1, s));
v = Math.max(0, Math.min(1, v));
i = (getSolutionOfLinearConguenceEquation(1, Math.floor(h / 60), 6) || [0])[0];
f = h / 60 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
}
/**
* RGB的颜色值转换hsv
* @example
* rgbToHsv(255,0,0) = {h: 0, s: 1, v: 1}
* rgbToHsv(128,1,0) = {h: 0, s: 1, v: 0.5019607843137255}
* @param {Number} r - 红色值, 0~255
* @param {Number} g - 绿色值, 0~255
* @param {Number} b - 蓝色值, 0~255
* @returns {object}
* h - hue表示色相
* s - Saturation饱和度
* v - Value表示明度
*/
function rgbToHsv(r: number, g: number, b: number): { h: number; s: number; v: number } {
let h, s, v;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
v = max / 255.0;
if (max === 0) {
return { h: -1, s: 0, v };
}
s = delta / max;
if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h *= 60;
if (h < 0) h += 360;
return { h: Math.round(h), s, v };
}
function _hueToRgb(p: number, q: number, t: number): number {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
/**
* 维基百科的hsl转rgb的完整实现,变量名没有改
* @example
* hslToRgb(0, 1, 0.5) = {r: 255, g: 0, b: 0}
* hslToRgb(120, 1, 0.75) = {r: 128, g: 255, b: 128}
* hslToRgb(240, 1, 0.25) = {r: 0, g: 0, b: 128}
* @param {Number} h - hue表示色相, 0°~360°
* @param {Number} s - Saturation饱和度,0%~100%
* @param {Number} l - Lightness表示亮度, 0%~100%
* @returns {Object} RGB的颜色值
* r - red, 0~255
* g - green, 0~255
* b - blue, 0~255
*/
function hslToRgb(h: number, s: number, l: number): { r: number; g: number; b: number } {
// 360, 1.0, 1.0
const h0 = (((h % 360) + 360) % 360) / 360;
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const r = _hueToRgb(p, q, h0 + 1 / 3);
const g = _hueToRgb(p, q, h0);
const b = _hueToRgb(p, q, h0 - 1 / 3);
return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
}
/**
* RGB转换hsl, 也是来自维基百科的公式实现
* @example
* rgbToHsl(255, 0, 0) = {h: 0, s: 1, l: 0.5}
* rgbToHsl(128, 255, 128) = {h: 120, s: 1, l: 0.7509803921568627}
* rgbToHsl(0,0,128) = {h: 240, s: 1, l: 0.25098039215686274}
* @param {Number} rr - 红色值, 0~255
* @param {Number} gg - 绿色值, 0~255
* @param {Number} bb - 蓝色值, 0~255
* @returns {object}
* h - hue表示色相
* s - Saturation饱和度
* v - Lightness表示亮度
*/
function rgbToHsl(rr: number, gg: number, bb: number): { h: number; s: number; l: number } {
// 255, 255, 255
let r, g, b, h, s, l, min, max;
r = parseFloat(rr.toString()) / 255;
g = parseFloat(gg.toString()) / 255;
b = parseFloat(bb.toString()) / 255;
min = Math.min(r, g, b);
max = Math.max(r, g, b);
l = (max + min) / 2;
if (max === min) {
s = 0;
h = Number.NaN;
} else if (l < 0.5) s = (max - min) / (max + min);
else s = (max - min) / (2 - max - min);
switch (max) {
case r:
h = (g - b) / (max - min);
break;
case g:
h = 2 + (b - r) / (max - min);
break;
case b:
h = 4 + (r - g) / (max - min);
break;
}
h *= 60;
h += h < 0 ? 360 : 0;
return { h, s, l };
}
export default {
calculateWhiteColorForView,
hsvToRgb,
rgbToHsv,
hslToRgb,
rgbToHsl,
}; | the_stack |
import {
Component,
Directive,
QueryList,
ContentChildren,
Input,
AfterViewInit,
OnDestroy,
ElementRef,
ChangeDetectionStrategy,
ChangeDetectorRef,
forwardRef,
OnInit,
Renderer2,
ViewChild
} from '@angular/core';
import {
LyTheme2,
toBoolean,
ThemeVariables,
DirAlias,
ThemeRef,
lyl,
keyframesUniqueId,
StyleCollection,
LyClasses,
StyleTemplate,
shadowBuilder,
StyleRenderer } from '@alyle/ui';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Platform } from '@angular/cdk/platform';
/** Default interval in ms */
const DEFAULT_INTERVAL = 7000;
const DEFAULT_AUTOPLAY = true;
const DEFAULT_HAS_PROGRESS_BAR = false;
const STYLE_PRIORITY = -2;
export interface LyCarouselTheme {
/** Styles for Carousel Component */
root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate);
}
export interface LyCarouselVariables {
carousel?: LyCarouselTheme;
}
export const STYLES = (theme: ThemeVariables & LyCarouselVariables, ref: ThemeRef) => {
const dir = theme.getDirection(DirAlias.before);
const right = dir === 'right' ? 0 : 180;
const left = dir === 'left' ? 0 : 180;
const carousel = ref.selectorsOf(STYLES);
const barAnimation = keyframesUniqueId.next();
const { after, before } = theme;
return {
$priority: STYLE_PRIORITY,
$global: lyl `{
@keyframes ${barAnimation} {
0% {
transform: translateX(0%)
}
100% {
transform: translateX(${dir === 'left' ? '-' : ''}100%)
}
}
}`,
root: ( ) => lyl `{
display: block
-webkit-user-select: none
-moz-user-select: none
-ms-user-select: none
position: relative
& ${carousel.actions}.right {
${after}: 0
transform: rotate(${right}deg)
}
& ${carousel.actions}.left {
${before}: 0
transform: rotate(${left}deg)
}
& svg {
display: block
fill: currentColor
}
{
...${
(theme.carousel
&& theme.carousel.root
&& (theme.carousel.root instanceof StyleCollection
? theme.carousel.root.setTransformer(fn => fn(carousel))
: theme.carousel.root(carousel))
)
}
}
}`,
actions: lyl `{
position: absolute
top: 0
bottom: 0
margin: auto .25em
height: 1em
width: 1em
font-size: 36px
cursor: pointer
background: ${theme.background.primary.default.alpha(.25)}
color: ${theme.text.primary}
will-change: transform
}`,
slideContainer: lyl `{
overflow: hidden
display: block
width: 100%
height: 100%
position: relative
touch-action: pan-y !important
}`,
slide: lyl `{
display: flex
width: 100%
height: 100%
will-change: transform
& > ly-carousel-item {
width: 100%
flex-shrink: 0
position: relative
background-size: cover
background-position: center
background-repeat: no-repeat
}
}`,
slideContent: lyl `{
display: flex
}`,
slideAnim: lyl `{
& > div {
transition: transform 750ms cubic-bezier(.1, 1, 0.5, 1)
}
}`,
slideNoEvent: lyl `{
&>div {
touch-action: initial !important
-webkit-user-drag: initial !important
}
}`,
indicators: () => lyl `{
position: absolute
bottom: 0
left: 0
right: 0
margin: 0
box-sizing: border-box
display: flex
align-items: center
justify-content: center
height: 48px
}`,
indicator: () => lyl `{
display: inline-block
border-radius: 50%
cursor: pointer
position: relative
padding: .5em
outline: none
}`,
indicatorIcon: () => lyl `{
transition: 300ms cubic-bezier(0.65, 0.05, 0.36, 1)
width: 1em
height: 1em
transform: scale(.5)
border-radius: 50%
will-change: transform
display: block
opacity: .65
box-shadow: ${shadowBuilder(8, theme.text.default)}
background: ${theme.background.primary.default}
}`,
indicatorActive: () => lyl `{
${carousel.indicatorIcon} {
transform: scale(1)
opacity: 1
}
}`,
barContainer: lyl `{
background: ${theme.background.primary.default.alpha(.25)}
height: 4px
position: absolute
bottom: 0
width: 100%
}`,
bar: lyl `{
height: 4px
position: absolute
bottom: 0
width: 100%
animation-name: ${barAnimation}
animation-timing-function: linear
animation-iteration-count: infinite
background: ${theme.text.primary}
}`
};
};
/** @docs-private */
export enum CarouselMode {
/** full */
default,
inline
}
@Component({
selector: 'ly-carousel',
templateUrl: './carousel.html',
changeDetection: ChangeDetectionStrategy.OnPush,
preserveWhitespaces: false,
host: {
'(mouseenter)': '_onMouseEnter()',
'(mouseleave)': '_onMouseLeave()'
},
providers: [
StyleRenderer
]
})
export class LyCarousel implements OnInit, AfterViewInit, OnDestroy {
/** @docs-private */
readonly classes = this.sRenderer.renderSheet(STYLES, true);
private _intervalFn: number | null = null;
@ViewChild('slideContainer') slideContainer: ElementRef;
@ViewChild('_slide') _slide: ElementRef;
@ViewChild('_progressBar') _progressBar: ElementRef<HTMLDivElement>;
@ContentChildren(forwardRef(() => LyCarouselItem)) lyItems: QueryList<LyCarouselItem>;
/** @docs-private */
@Input() mode: CarouselMode = CarouselMode.default;
@Input() selectedIndex = 0;
_selectedElement: HTMLElement;
private _touch: boolean;
private _autoplay: boolean;
private _hasProgressBar: boolean;
private _interval = DEFAULT_INTERVAL;
private _slideClass: string;
/** Emits whenever the component is destroyed. */
private readonly _destroy = new Subject<void>();
/** @internal */
get _isIntervalFn() {
return !!this._intervalFn;
}
/**
* It will pause the slide change when the mouse cursor passes
* through the carousel.
*/
@Input()
get pauseOnHover() {
return this._pauseOnHover;
}
set pauseOnHover(val: boolean) {
const newVal = toBoolean(val);
this._pauseOnHover = newVal;
}
private _pauseOnHover: boolean;
@Input()
set touch(val: boolean) {
const newVal = toBoolean(val);
this._touch = newVal;
if (newVal) {
this._renderer.removeClass(this._el.nativeElement, this.classes.slideNoEvent);
} else {
this._renderer.addClass(this._el.nativeElement, this.classes.slideNoEvent);
}
}
get touch() {
return this._touch;
}
@Input()
set autoplay(val: boolean) {
const newVal = toBoolean(val);
this._autoplay = newVal;
if (newVal) {
this._resetInterval();
} else {
this.stop();
}
}
get autoplay() {
return this._autoplay;
}
@Input()
set hasProgressBar(val: boolean) {
const newVal = toBoolean(val);
this._hasProgressBar = newVal;
}
get hasProgressBar() {
return this._hasProgressBar;
}
@Input()
set interval(val: number) {
this._interval = val;
this._resetInterval();
}
get interval() {
return this._interval;
}
@Input()
set hasNavigationArrows(val: boolean) {
this._hasNavigationArrows = toBoolean(val);
}
get hasNavigationArrows() {
return this._hasNavigationArrows;
}
private _hasNavigationArrows: boolean = true;
@Input()
set hasNavigationIndicators(val: boolean) {
this._hasNavigationIndicators = toBoolean(val);
}
get hasNavigationIndicators() {
return this._hasNavigationIndicators;
}
private _hasNavigationIndicators: boolean = true;
constructor(
private _el: ElementRef,
private _cd: ChangeDetectorRef,
private _theme: LyTheme2,
private _renderer: Renderer2,
readonly sRenderer: StyleRenderer,
private _platform: Platform
) { }
ngOnInit() {
if (!this.touch) {
this.touch = false;
}
if (this.autoplay == null) {
this.autoplay = DEFAULT_AUTOPLAY;
}
if (this.hasProgressBar == null) {
this.hasProgressBar = DEFAULT_HAS_PROGRESS_BAR;
}
}
ngAfterViewInit() {
this._renderer.addClass(this.slideContainer.nativeElement, this.classes.slideContainer);
if (this._platform.isBrowser) {
this._renderer.addClass(this.slideContainer.nativeElement, this.classes.slideAnim);
}
this.lyItems.changes.pipe(takeUntil(this._destroy)).subscribe(() => this._markForCheck());
}
ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
if (this._platform.isBrowser) {
this.stop();
}
}
_onMouseEnter() {
if (this.pauseOnHover) {
this.stop();
}
}
_onMouseLeave() {
if (this.pauseOnHover) {
this._resetInterval();
}
}
/** @docs-private */
_onDragStart() {
this.stop();
this._renderer.removeClass(this.slideContainer.nativeElement, this.classes.slideAnim);
this._selectedElement = this.lyItems.find((_item, index) => index === this.selectedIndex)!._nativeElement;
}
_onDrag(e) {
const rect = this._selectedElement.getBoundingClientRect();
if (Math.abs(e.deltaX) < rect.width) {
this._onPan(e.deltaX);
} else {
this._onPan(rect.width * Math.sign(e.deltaX));
}
}
_onDragEnd(e) {
const rect = this._selectedElement.getBoundingClientRect();
const dir = this._theme.variables.getDirection(DirAlias.before);
this._renderer.addClass(this.slideContainer.nativeElement, this.classes.slideAnim);
this._select(this.selectedIndex);
if (Math.abs(e.deltaX) > rect.width / 2) {
if (0 > e.deltaX) {
this.next();
} else if (0 < e.deltaX) {
this.prev();
}
} else if (e.additionalEvent) {
const eventName = e.additionalEvent;
if (Math.abs(e.velocity) >= 0.25) {
if (eventName === 'slideleft') {
if (dir === 'left') {
this.next();
} else {
this.prev();
}
} else if (eventName === 'slideright') {
if (dir === 'right') {
this.next();
} else {
this.prev();
}
}
}
}
this._renderer.removeStyle(this._slide.nativeElement, 'transform');
}
_onDragCancel() {
this._renderer.addClass(this.slideContainer.nativeElement, this.classes.slideAnim);
this._select(this.selectedIndex);
this._resetInterval();
}
_select(val: number, notResetInterval?: boolean) {
this.selectedIndex = val;
if (this.mode === CarouselMode.default) {
this._slideClass = this._theme.addStyle(
`lyCarousel.select:${val.toString(32)}`,
(theme: ThemeVariables) => {
const sign = theme.getDirection(DirAlias.before) === 'left' ? -1 : 1;
return {
transform: `translateX(${100 * val * sign}%)`
};
},
this._slide.nativeElement,
this._slideClass,
STYLE_PRIORITY
);
}
if (!notResetInterval) {
if (this.autoplay && !this.pauseOnHover) {
this._resetInterval();
}
}
}
prev() {
const len = this.lyItems.length - 1;
const prev = this.selectedIndex - 1;
this._select(prev < 0 ? len : prev);
}
next(notResetInterval?: boolean) {
const len = this.lyItems.length - 1;
const next = this.selectedIndex + 1;
this._select(next > len ? 0 : next, notResetInterval);
}
stop() {
if (this._intervalFn !== null) {
clearInterval(this._intervalFn);
this._intervalFn = null;
}
}
private _resetInterval() {
if (this._platform.isBrowser) {
this.stop();
this._restartProgressBarAnimation();
this._markForCheck();
this._intervalFn = setInterval(() => {
this.next(true);
this._restartProgressBarAnimation();
this._markForCheck();
}, this.interval) as any;
}
}
private _restartProgressBarAnimation() {
if (this.hasProgressBar && this._progressBar) {
const el = this._progressBar.nativeElement;
// Hack for restart animation
el.style.animationName = 'øfakeName';
window.getComputedStyle(el).getPropertyValue('opacity');
el.style.animationName = '';
}
}
private _onPan(x) {
const sign = this._theme.variables.getDirection(DirAlias.before) === 'left' ? -1 : 1;
this._renderer.setStyle(this._slide.nativeElement, 'transform', `translateX(calc(${sign * 100 * this.selectedIndex }% + ${x}px))`);
}
private _markForCheck() {
this._cd.markForCheck();
}
}
@Directive({
selector: 'ly-carousel-item'
})
export class LyCarouselItem {
private _className: string;
@Input()
set srcImg(value: string) {
this._className = this._theme.addStyle(
`ly-carousel-img:${value}`, (
`background-image: url('${value}')`
),
this._nativeElement,
this._className, STYLE_PRIORITY
);
}
_nativeElement: HTMLElement;
constructor(
private _theme: LyTheme2,
_el: ElementRef
) {
this._nativeElement = _el.nativeElement;
}
} | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
HostListener,
Input,
Output,
ViewChild
} from "@angular/core";
import {AbstractJigsawComponent} from "../../common/common";
/**
* @internal
*/
type ProcessStatusData = {
status: string;
title?: string;
subTitle: string;
waitingIcon?: string;
doneIcon?: string;
processingIcon?: string;
errorIcon?: string;
warningIcon?: string;
skippedIcon?: string;
context?: any;
};
@Component({
selector: "jigsaw-process-status-multiline, j-process-status-multiline",
template: `
<div [perfectScrollbar]="{ wheelSpeed: 0.5, wheelPropagation: true }" style="width: 100%;height: 100%">
<div #step>
<div
*ngFor="let rowIndex of _$rowIndexes; odd as odd; even as even; index as index; last as last"
style="width: 100%;height: 100%"
>
<jigsaw-process-status
[preSize]="preSize"
[ngClass]="{ 'jigsaw-process-status-multiline-odd': odd, 'jigsaw-process-status-multiline-even': even }"
>
<jigsaw-process-status-item
*ngFor="let step of _$getData(index); index as ind"
[status]="step.status"
[waitingIcon]="step.waitingIcon"
[doneIcon]="step.doneIcon"
[processingIcon]="step.processingIcon"
[errorIcon]="step.errorIcon"
[warningIcon]="step.warningIcon"
[skippedIcon]="step.skippedIcon"
(click)="_$handleItemClick($event, step)"
[ngClass]="{
'jigsaw-process-status-item-overflow': data && index * _$numInlineActual + ind >= data.length,
'jigsaw-process-status-item-last': data && index * _$numInlineActual + ind == data.length - 1
}"
>
<div jigsaw-title class="jigsaw-process-status-multiline-title" [title]="step.title">
{{ step.title }}
</div>
<div
jigsaw-sub-title
trustedHtml="{{ step.subTitle }}"
[trustedHtmlContext]="step.context"
></div>
</jigsaw-process-status-item>
</jigsaw-process-status>
<div *ngIf="!last" style="width: 100%;height: 50px;position: relative">
<div
class="jigsaw-process-status-multiline-v"
style="width: 2px;height: 100%;position: absolute;"
[style.backgroundColor]="_$getColor(rowIndex)"
></div>
</div>
</div>
</div>
</div>
`,
host: {
"[style.width]": "width",
"[style.height]": "height"
},
changeDetection: ChangeDetectionStrategy.OnPush
})
export class JigsawProcessStatusMultiline extends AbstractJigsawComponent {
constructor(public _elementRef: ElementRef, private _changeDetectorRef: ChangeDetectorRef) {
super();
}
private _originWidth: number;
private _dataInSteps: ProcessStatusData[] = [];
private _preSize: "small" | "default" | "large" = "default";
/**
* 设置步骤条图标的预设尺寸
*
* @NoMarkForCheckRequired
*/
@Input()
public get preSize(): "small" | "default" | "large" {
return this._preSize;
}
public set preSize(value: "small" | "default" | "large") {
if (value && value != this._preSize) {
this._preSize = value;
this._setWidth();
}
}
private _data: ProcessStatusData[] = [];
/**
* @NoMarkForCheckRequired
*/
@Input()
public get data(): ProcessStatusData[] {
return this._data;
}
public set data(value: ProcessStatusData[]) {
if (value && value != this._data) {
this._data = value;
this._initData();
this._setWidth();
}
}
private _numInline: number = 5;
/**
* 设置一行放置几个item
*
* @NoMarkForCheckRequired
*/
@Input()
public get numInline(): number {
return this._numInline;
}
public set numInline(value: number) {
if (value == this._numInline || value < 1) {
return;
}
this._numInline = value;
this._initData();
this._setWidth();
}
/**
* @internal
*/
public get _$numInlineActual(): number {
return this.numInline <= this.data.length ? this.numInline : this.data.length;
}
@Output() public select = new EventEmitter<any>();
/**
* @internal
*/
public _$rowIndexes: number[] = [];
/**
* @internal
*/
public _$handleItemClick($event, step: any) {
if ($event.path[0].tagName.toLowerCase() == "i") {
this.select.emit(step);
}
}
/**
* @internal
*/
public _$getData(index): ProcessStatusData[] {
let stepsItemData = [];
for (let i = 0; i < this._$numInlineActual; i++) {
if (index * this._$numInlineActual + i < this._dataInSteps.length) {
stepsItemData.push(this._dataInSteps[index * this._$numInlineActual + i]);
}
}
return stepsItemData;
}
/**
* @internal
*/
public _$getColor(rowIndex): string {
if (this.data && rowIndex < this._$rowIndexes.length - 1) {
switch (this.data[this._$numInlineActual * rowIndex + this._$numInlineActual - 1].status) {
case "processing":
return "#41ADDC";
case "waiting":
return "#666";
case "skipped":
return "#999999";
case "done":
return "#7ACA6B";
case "error":
return "#E67877";
case "warning":
return "orange";
default:
return "#666";
}
}
return "";
}
ngOnInit() {
this._initData();
}
ngAfterViewInit() {
this._originWidth = parseInt(this._step.nativeElement.offsetWidth);
this._setWidth();
}
@ViewChild("step")
private _step: ElementRef;
private _initData() {
this._dataInSteps = [];
this._dataInSteps.push(...this.data);
if (this.data && this.data.length > this._$numInlineActual) {
let remainder = this.data.length % this._$numInlineActual;
if (remainder != 0) {
for (let j = 0; j < this._$numInlineActual - remainder; j++) {
this._dataInSteps.push(this.data[this.data.length - 1]);
}
}
}
let row =
this.data && this._$numInlineActual ? Math.ceil(this._dataInSteps.length / this._$numInlineActual) : 1;
this._$rowIndexes = [];
for (let i = 0; i < row; i++) {
this._$rowIndexes.push(i);
}
this._changeDetectorRef.markForCheck();
}
@HostListener("window:resize")
onResize() {
this._originWidth = parseInt(this._step.nativeElement.parentElement.offsetWidth);
this._setWidth();
}
private _setWidth() {
// preSize为default的最小宽度
const DEFAULT_ICON_MIN_WIDTH = 146;
// preSize为small的最小宽度
const SMALL_ICON_MIN_WIDTH = 140;
// preSize为large的最小宽度
const LARGE_ICON_MIN_WIDTH = 150;
// 每行起始处的留白
const MARGIN_WIDTH = 60;
let minWidth = DEFAULT_ICON_MIN_WIDTH;
let logoWidth = 26;
if (this.preSize == "small") {
minWidth = SMALL_ICON_MIN_WIDTH;
logoWidth = 20;
} else if (this.preSize == "large") {
minWidth = LARGE_ICON_MIN_WIDTH;
logoWidth = 30;
}
if (this._step) {
let overflow = false;
if (minWidth * this._$numInlineActual + MARGIN_WIDTH * 2 > this._originWidth) {
this._step.nativeElement.style.width = minWidth * this._$numInlineActual + MARGIN_WIDTH * 2 + "px";
overflow = true;
} else {
this._step.nativeElement.style.width = this._originWidth + "px";
overflow = false;
}
this.runMicrotask(() => {
let oddStepsSpaces = this._step.nativeElement.querySelectorAll(
".jigsaw-process-status-multiline-odd .jigsaw-process-status-container .jigsaw-step-left-space"
);
let evenStepsSpaces = this._step.nativeElement.querySelectorAll(
".jigsaw-process-status-multiline-even .jigsaw-process-status-container .jigsaw-step-left-space"
);
let oddSteps = this._step.nativeElement.querySelectorAll(".jigsaw-process-status-multiline-odd");
let evenSteps = this._step.nativeElement.querySelectorAll(".jigsaw-process-status-multiline-even");
let vLines = this._step.nativeElement.querySelectorAll(".jigsaw-process-status-multiline-v");
let oddItems = this._step.nativeElement.querySelectorAll(
".jigsaw-process-status-multiline-odd .jigsaw-process-status-container .jigsaw-process-status-item"
);
let evenItems = this._step.nativeElement.querySelectorAll(
".jigsaw-process-status-multiline-even .jigsaw-process-status-container .jigsaw-process-status-item"
);
let items = this._step.nativeElement.querySelectorAll(".jigsaw-process-status-container .jigsaw-process-status-item");
if (evenItems[this._$numInlineActual - 1].offsetWidth == minWidth) {
oddStepsSpaces &&
oddStepsSpaces.forEach((space, index) => {
space.style.flex = 0;
space.style.minWidth = minWidth - logoWidth + "px";
});
if (
oddSteps &&
oddSteps.length > 0 &&
this._step.nativeElement.offsetWidth < oddSteps[0].offsetWidth + MARGIN_WIDTH &&
overflow
) {
this._step.nativeElement.style.width = oddSteps[0].offsetWidth + MARGIN_WIDTH + "px";
}
} else {
oddStepsSpaces &&
oddStepsSpaces.forEach((space, index) => {
space.style.flex = 0.5;
space.style.minWidth = MARGIN_WIDTH + "px";
});
}
if (oddItems && oddItems.length > 0) {
if (oddItems[this._$numInlineActual - 1].offsetWidth == minWidth) {
evenStepsSpaces.forEach((space, index) => {
space.style.flex = 0;
space.style.minWidth = minWidth - logoWidth + "px";
});
if (
this._step.nativeElement.offsetWidth < evenSteps[0].offsetWidth + MARGIN_WIDTH &&
overflow
) {
this._step.nativeElement.style.width = evenSteps[0].offsetWidth + MARGIN_WIDTH + "px";
}
} else {
evenStepsSpaces.forEach((space, index) => {
space.style.flex = 0.5;
space.style.minWidth = MARGIN_WIDTH + "px";
});
}
}
if (this._$numInlineActual == 1) {
vLines &&
vLines.forEach((line, index) => {
line.style.left = items[0].offsetWidth - logoWidth / 2 - 1 + "px";
});
} else {
vLines &&
vLines.forEach((line, index) => {
if (index % 2 == 1) {
line.style.left =
items[index * this._$numInlineActual + this._$numInlineActual - 1].offsetWidth -
logoWidth / 2 -
2 +
"px";
} else {
line.style.left = "";
line.style.right =
items[index * this._$numInlineActual + this._$numInlineActual - 1].offsetWidth -
logoWidth / 2 -
2 +
"px";
}
});
}
});
}
this._changeDetectorRef.markForCheck();
}
} | the_stack |
import { IDataSet } from '../../src/base/engine';
import { pivot_dataset, pivot_nodata } from '../base/datasource.spec';
import { PivotView } from '../../src/pivotview/base/pivotview';
import { createElement, remove, EventHandler, EmitType } from '@syncfusion/ej2-base';
import { GroupingBar } from '../../src/common/grouping-bar/grouping-bar';
import { FieldList } from '../../src/common/actions/field-list';
import { CalculatedField } from '../../src/common/calculatedfield/calculated-field';
import { MenuEventArgs } from '@syncfusion/ej2-navigations';
import { VirtualScroll } from '../../src/pivotview/actions';
import * as util from '../utils.spec';
import { profile, inMB, getMemoryProfile } from '../common.spec';
describe(' - VirtualScrolling', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe(' - VirtualScrolling', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
beforeAll(() => {
document.body.appendChild(elem);
pivotGridObj = new PivotView(
{
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: false,
sortSettings: [{ name: 'company', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
rows: [{ name: 'product' }, { name: 'state' }],
columns: [{ name: 'gender' }, { name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: [],
},
allowCalculatedField: true,
enableVirtualization: true,
width: 600,
height: 300
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-frozencontent')[0].scrollTop = 317;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("touchstart", { clientY: 317, view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
// args = new MouseEvent("touchmove", { view: window, bubbles: true, cancelable: true });
// document.querySelector('.e-frozencontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-frozencontent')[0].scrollTop) === 317).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
done();
}, 1000);
});
it('scroll top false', (done: Function) => {
document.querySelectorAll('.e-frozencontent')[0].scrollTop = 317;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("touchstart", { clientY: 0, view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
args = new MouseEvent("touchmove", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-frozencontent')[0].scrollTop) === 317).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
done();
}, 1000);
});
it('scroll right', (done: Function) => {
document.querySelectorAll('.e-movableheader')[0].scrollLeft = 1360;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("touchstart", { clientX: 1360, view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movableheader').dispatchEvent(args);
// args = new MouseEvent("touchmove", { view: window, bubbles: true, cancelable: true });
// document.querySelector('.e-movableheader').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movableheader').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
done();
}, 1000);
});
it('scroll right false', (done: Function) => {
document.querySelectorAll('.e-movableheader')[0].scrollLeft = 1360;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("touchstart", { clientX: 0, view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movableheader').dispatchEvent(args);
// args = new MouseEvent("touchmove", { view: window, bubbles: true, cancelable: true });
// document.querySelector('.e-movableheader').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movableheader').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
done();
}, 1000);
});
it('scroll top wheel', (done: Function) => {
document.querySelectorAll('.e-frozencontent')[0].scrollTop = 0;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("wheel", { clientY: 0, view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-frozencontent')[0].scrollTop) === 0).toBeTruthy();
done();
}, 1000);
});
it('scroll top wheel false', (done: Function) => {
document.querySelectorAll('.e-frozencontent')[0].scrollTop = 0;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("wheel", { clientY: 0, view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-frozencontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-frozencontent')[0].scrollTop) === 0).toBeTruthy();
done();
}, 1000);
});
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
});
describe(' - VirtualScrolling', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
beforeAll(() => {
document.body.appendChild(elem);
pivotGridObj = new PivotView(
{
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: false,
sortSettings: [{ name: 'company', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
rows: [{ name: 'product' }, { name: 'state' }],
columns: [{ name: 'gender' }, { name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: [],
},
allowCalculatedField: true,
enableVirtualization: true,
width: 600,
height: 300
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('pivotgrid render testing', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
done();
}, 1000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 317;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-frozencontent')[0].scrollTop) === 317).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
done();
}, 1000);
});
it('scroll right', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 1360;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$33,116.92');
done();
}, 1000);
});
it('scroll bottom', (done: Function) => {
pivotGridObj.element.querySelectorAll('.e-movablecontent')[0].scrollTop = 0;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-frozencontent')[0].scrollTop).toBe(0);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$32,045.16');
done();
}, 1000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 400;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft).toBe(400);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('684.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1780px');
done();
}, 1000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 0;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
// expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft).toBe(0);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('684.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1780px');
done();
}, 1000);
});
it('Collapse flight', (done: Function) => {
(document.querySelectorAll('.e-frozencontent tr .e-icons')[0] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1780px');
done();
}, 1000);
});
it('Collapse male', (done: Function) => {
(document.querySelectorAll('.e-movableheader th .e-icons')[0] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('male Total');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$95,040.55');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1120px');
done();
}, 1000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 900;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-frozencontent')[0].scrollTop).toBe(900);
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('Delhi');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$15,264.74');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('432.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1120px');
done();
}, 1000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 890;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-frozencontent')[0].scrollTop).toBe(890);
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('Delhi');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$15,264.74');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('432.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1120px');
done();
}, 1000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 752;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('male Total');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$15,264.74');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('432.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1120px');
done();
}, 1000);
});
it('Collapse bike', (done: Function) => {
(document.querySelectorAll('.e-frozencontent tr .e-icons')[2] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft).toBe(752);
done();
}, 1000);
});
it('Collapse female', (done: Function) => {
(document.querySelectorAll('.e-movableheader th .e-collapse')[0] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-movablecontent')[0].scrollTop).toBe(890);
done();
}, 1000);
});
it('value in row axis', (done: Function) => {
pivotGridObj.setProperties({ dataSourceSettings: { valueAxis: 'row' } }, true);
pivotGridObj.dataSourceSettings.drilledMembers = [];
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('1692.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('790px');
done();
}, 1000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 890;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 890;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
done();
}, 1000);
});
it('append name in column', (done: Function) => {
pivotGridObj.dataSourceSettings.columns = [{ name: 'gender' }, { name: 'eyeColor' }, { name: 'name' }];
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
//expect(document.querySelectorAll('.e-frozencontent')[0].scrollTop).toBe(890);
done();
}, 1000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 50000;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
done();
}, 1000);
});
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
});
describe(' - Grouping Bar', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
beforeAll(() => {
document.body.appendChild(elem);
PivotView.Inject(GroupingBar, FieldList, VirtualScroll);
pivotGridObj = new PivotView(
{
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: false,
sortSettings: [{ name: 'company', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
rows: [{ name: 'product' }, { name: 'state' }],
columns: [{ name: 'gender' }, { name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: [],
},
allowCalculatedField: true,
showGroupingBar: true,
enableVirtualization: true,
showFieldList: true,
showValuesButton: true,
width: 600,
height: 300
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('pivotgrid render testing', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
done();
}, 1000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 317;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-frozencontent')[0].scrollTop) === 317).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
done();
}, 1000);
});
it('scroll right', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 1360;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$33,116.92');
done();
}, 1000);
});
it('scroll bottom', (done: Function) => {
pivotGridObj.element.querySelectorAll('.e-movablecontent')[0].scrollTop = 0;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-frozencontent')[0].scrollTop).toBe(0);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$32,045.16');
done();
}, 1000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 0;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('684.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1730px');
done();
}, 1000);
});
it('Collapse flight', (done: Function) => {
(document.querySelectorAll('.e-frozencontent tr .e-icons')[0] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1730px');
done();
}, 1000);
});
it('Collapse male', (done: Function) => {
(document.querySelectorAll('.e-movableheader th .e-icons')[0] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('male Total');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$95,040.55');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1070px');
done();
}, 1000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 358;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-frozencontent')[0].scrollTop).toBe(358);
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('New Jercy');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$24,452.08');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1070px');
done();
}, 1000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 752;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('male Total');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$24,452.08');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1070px');
done();
}, 1000);
});
it('Collapse bike', (done: Function) => {
(document.querySelectorAll('.e-frozencontent tr .e-icons')[2] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft).toBe(752);
done();
}, 1000);
});
it('Collapse female', (done: Function) => {
(document.querySelectorAll('.e-movableheader th .e-collapse')[0] as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-movablecontent')[0].scrollTop).toBe(358);
done();
}, 1000);
});
it('filter', (done: Function) => {
(document.querySelector('#product.e-pivot-button .e-pv-filter') as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let allNode: HTMLElement = document.querySelector('.e-checkbox-wrapper');
let args: MouseEvent = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
allNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
allNode.querySelector('.e-frame').dispatchEvent(args);
let firstNode: HTMLElement = document.querySelectorAll('.e-checkbox-wrapper')[2] as HTMLElement;
args = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
(document.querySelector('.e-ok-btn') as HTMLElement).click();
done();
}, 1000);
});
it('filter check', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-movableheader')[0].scrollLeft)).toBeGreaterThan(735);
expect(document.querySelectorAll('.e-movablecontent')[0].scrollTop).toBe(358);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
done();
}, 1000);
});
it('value moved to row', (done: Function) => {
let rowAxiscontent: HTMLElement = pivotGridObj.element.querySelector('.e-rows');
let columnAxiscontent: HTMLElement = pivotGridObj.element.querySelector('.e-columns');
let pivotButton: HTMLElement[] = [].slice.call((columnAxiscontent).querySelectorAll('.e-pivot-button'));
expect(pivotButton.length).toEqual(3);
let dragElement: HTMLElement = pivotButton[2].querySelector('.e-content');
let mousedown: any =
util.getEventObject('MouseEvents', 'mousedown', dragElement, dragElement, 15, 10);
EventHandler.trigger(dragElement, 'mousedown', mousedown);
let mousemove: any =
util.getEventObject('MouseEvents', 'mousemove', dragElement, rowAxiscontent, 15, 70);
mousemove.srcElement = mousemove.target = mousemove.toElement = rowAxiscontent;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
let mouseUp: any = util.getEventObject('MouseEvents', 'mouseup', dragElement, rowAxiscontent);
mouseUp.type = 'mouseup';
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = rowAxiscontent;
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
pivotButton = [].slice.call((rowAxiscontent).querySelectorAll('.e-pivot-button'));
expect(pivotButton.length).toEqual(3);
done();
}, 1000);
});
it('value moved to column', (done: Function) => {
let rowAxiscontent: HTMLElement = pivotGridObj.element.querySelector('.e-rows');
let columnAxiscontent: HTMLElement = pivotGridObj.element.querySelector('.e-columns');
let pivotButton: HTMLElement[] = [].slice.call((rowAxiscontent).querySelectorAll('.e-pivot-button'));
expect(pivotButton.length).toEqual(3);
let dragElement: HTMLElement = pivotButton[2].querySelector('.e-content');
let mousedown: any =
util.getEventObject('MouseEvents', 'mousedown', dragElement, dragElement, 15, 10);
EventHandler.trigger(dragElement, 'mousedown', mousedown);
let mousemove: any =
util.getEventObject('MouseEvents', 'mousemove', dragElement, columnAxiscontent, 15, 70);
mousemove.srcElement = mousemove.target = mousemove.toElement = columnAxiscontent;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
let mouseUp: any = util.getEventObject('MouseEvents', 'mouseup', dragElement, columnAxiscontent);
mouseUp.type = 'mouseup';
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = columnAxiscontent;
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
pivotButton = [].slice.call((columnAxiscontent).querySelectorAll('.e-pivot-button'));
expect(pivotButton.length).toEqual(3);
done();
}, 1000);
});
it('value removed', (done: Function) => {
let rowAxiscontent: any = document;
let columnAxiscontent: HTMLElement = pivotGridObj.element.querySelector('.e-columns');
let pivotButton: HTMLElement[] = [].slice.call((columnAxiscontent).querySelectorAll('.e-pivot-button'));
expect(pivotButton.length).toEqual(3);
let dragElement: HTMLElement = pivotButton[2].querySelector('.e-content');
let mousedown: any =
util.getEventObject('MouseEvents', 'mousedown', dragElement, dragElement, 15, 10);
EventHandler.trigger(dragElement, 'mousedown', mousedown);
let mousemove: any =
util.getEventObject('MouseEvents', 'mousemove', dragElement, rowAxiscontent, 15, 70);
mousemove.srcElement = mousemove.target = mousemove.toElement = rowAxiscontent;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
let mouseUp: any = util.getEventObject('MouseEvents', 'mouseup', dragElement, rowAxiscontent);
mouseUp.type = 'mouseup';
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = rowAxiscontent;
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
pivotButton = [].slice.call((rowAxiscontent).querySelectorAll('.e-pivot-button'));
expect(pivotButton.length).toEqual(8);
done();
}, 1000);
});
it('values added', () => {
pivotGridObj.dataSourceSettings.values = [{ name: 'balance' }, { name: 'quantity' }];
});
it('values removed', (done: Function) => {
let columnAxiscontent: HTMLElement = pivotGridObj.element.querySelector('.e-columns');
let valueAxiscontent: HTMLElement = pivotGridObj.element.querySelector('.e-values');
let pivotButton: HTMLElement[] = [].slice.call((columnAxiscontent).querySelectorAll('.e-pivot-button'));
(pivotButton[2].querySelector('.e-remove') as HTMLElement).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
pivotButton = [].slice.call((valueAxiscontent).querySelectorAll('.e-pivot-button'));
expect(pivotButton.length).toEqual(0);
done();
}, 1000);
});
it('values added', () => {
pivotGridObj.dataSourceSettings.values = [{ name: 'balance' }, { name: 'quantity' }];
});
it('RTL', (done: Function) => {
pivotGridObj.enableRtl = true;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-movablecontent')[0].scrollTop).toBe(0);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('0.1px');
done();
}, 1000);
});
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
});
describe(' - ValueSorting', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
beforeAll(() => {
document.body.appendChild(elem);
pivotGridObj = new PivotView(
{
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: false,
sortSettings: [{ name: 'company', order: 'Descending' }],
formatSettings: [{ name: 'balance', format: 'C' }],
rows: [{ name: 'product' }, { name: 'state' }],
columns: [{ name: 'gender' }, { name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: [],
},
enableVirtualization: true,
enableValueSorting: true,
width: 600,
height: 300
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('render testing', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
done();
}, 1000);
});
it('sort male-blue-balance', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
(document.querySelectorAll('.e-movableheader th.e-firstcell')[0] as HTMLElement).click()
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Van');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$43,025.37');
done();
}, 1000);
});
it('scrollTop', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 398;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Van');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$43,025.37');
done();
}, 1000);
});
it('scrollLeft', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 1235;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(25);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Tempo');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$35,784.78');
done();
}, 1000);
});
it('Collapse car', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
(document.querySelectorAll('.e-frozencontent tr')[14].querySelector('.e-icons') as HTMLElement).click()
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(25);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Tempo');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$35,784.78');
done();
}, 1000);
});
it('scrollTop', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 0;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(25);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Tempo');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$23,417.02');
done();
}, 1000);
});
it('scrollLeft', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 0;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Van');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$14,986.08');
done();
}, 1000);
});
it('sort male-green-balance', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
(document.querySelectorAll('.e-movableheader th.e-firstcell')[1] as HTMLElement).click()
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$32,045.16');
done();
}, 1000);
});
it('remove quantity', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.dataSourceSettings.values = [{ name: 'balance' }];
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(9);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
done();
}, 1000);
});
it('sort female-brown', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
(document.querySelectorAll('.e-movableheader th.e-firstcell')[1] as HTMLElement).click();
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(9);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Car');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$32,295.87');
done();
}, 1000);
});
it('insert quantity', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.dataSourceSettings.values = [{ name: 'balance' }, { name: 'quantity' }];
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Car');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$32,295.87');
done();
}, 1000);
});
it('move values to row', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.dataSourceSettings.valueAxis = 'row';
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(36);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(9);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('');
done();
}, 3000);
});
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
});
describe(' - advanced filtering ', () => {
let originalTimeout: number;
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
beforeAll(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
document.body.appendChild(elem);
pivotGridObj = new PivotView(
{
dataSourceSettings: {
allowLabelFilter: true,
allowValueFilter: true,
dataSource: pivot_dataset as IDataSet[],
expandAll: true,
enableSorting: false,
formatSettings: [{ name: 'balance', format: 'C' }],
rows: [{ name: 'product' }, { name: 'state' }],
columns: [{ name: 'gender' }, { name: 'eyeColor' }],
values: [{ name: 'balance' }, { name: 'quantity' }],
filters: [],
},
enableVirtualization: true,
width: 600,
height: 300
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('pivotgrid render testing', (done: Function) => {
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
done();
}, 5000);
});
it('state start with t', (done: Function) => {
pivotGridObj.dataSourceSettings.filterSettings = [
{ name: 'state', type: 'Label', condition: 'BeginWith', value1: 't' }],
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(13);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Van');
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('Tamilnadu');
done();
}, 5000);
});
it('state contains e', (done: Function) => {
pivotGridObj.dataSourceSettings.filterSettings = [
{ name: 'state', type: 'Label', condition: 'Contains', value1: 'e' }],
setTimeout(() => {
expect(document.querySelectorAll('.e-frozencontent tr').length).toBe(24);
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelectorAll('td').length).toBe(14);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('New Jercy');
done();
}, 5000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 317;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(Math.round(document.querySelectorAll('.e-frozencontent')[0].scrollTop) === 317).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$11,131.56');
done();
}, 5000);
});
it('eyeColor equals blue', (done: Function) => {
pivotGridObj.dataSourceSettings.filterSettings = [
{ name: 'state', type: 'Label', condition: 'Contains', value1: 'e' },
{ name: 'eyeColor', type: 'Label', condition: 'Equals', value1: 'blue' }],
setTimeout(() => {
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('blue');
expect(document.querySelectorAll('.e-movableheader th')[4].textContent).toBe('male Total');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$11,131.56');
done();
}, 5000);
});
it('scroll right', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 1360;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Flight');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$11,131.56');
done();
}, 5000);
});
it('product quantity > 100', (done: Function) => {
pivotGridObj.dataSourceSettings.filterSettings = [
{ name: 'product', type: 'Value', condition: 'GreaterThan', measure: 'quantity', value1: '100' }],
setTimeout(() => {
expect(document.querySelectorAll('.e-movableheader th')[4].textContent).toBe('brown');
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('green');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
done();
}, 5000);
});
// it('eyeColor blue quantity < 100', (done: Function) => {
// pivotGridObj.dataSource.filterSettings = [
// { name: 'product', type: 'Value', condition: 'GreaterThan', measure: 'quantity', value1: '100' },
// { name: 'eyeColor', type: 'Value', condition: 'LessThan', measure: 'quantity', value1: '100' }],
// setTimeout(() => {
// expect(document.querySelectorAll('.e-movableheader th')[1].textContent).toBe('balance');
// expect(document.querySelectorAll('.e-movableheader th')[2].textContent).toBe('quantity');
// done();
// }, 1000);
// });
it('product quantity > 100', (done: Function) => {
pivotGridObj.dataSourceSettings.filterSettings = [
{ name: 'product', type: 'Value', condition: 'GreaterThan', measure: 'quantity', value1: '100' }],
setTimeout(() => {
expect(document.querySelectorAll('.e-movableheader th')[4].textContent).toBe('brown');
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('green');
// expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$12,490.89');
done();
}, 5000);
});
it('scroll bottom', (done: Function) => {
pivotGridObj.element.querySelectorAll('.e-movablecontent')[0].scrollTop = 0;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-frozencontent')[0].scrollTop === 0).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
done();
}, 5000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 400;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft).toBe(400);
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('648.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1780px');
done();
}, 5000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 0;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Jet');
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('$27,813.73');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('648.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1780px');
done();
}, 5000);
});
it('Collapse flight', (done: Function) => {
(document.querySelectorAll('.e-frozencontent tr .e-icons')[0] as HTMLElement).click()
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('New Jercy');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$6,416.24');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1780px');
done();
}, 5000);
});
it('Collapse male', (done: Function) => {
(document.querySelectorAll('.e-movableheader th .e-icons')[0] as HTMLElement).click()
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect(document.querySelectorAll('.e-movableheader')[0].scrollLeft === 0).toBeTruthy();
expect(document.querySelectorAll('.e-movableheader th')[3].textContent).toBe('male Total');
expect(document.querySelectorAll('.e-movablecontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('$24,452.08');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('468.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('1120px');
done();
}, 5000);
});
it('value in row axis', (done: Function) => {
pivotGridObj.setProperties({ dataSourceSettings: { valueAxis: 'row' } }, true);
pivotGridObj.dataSourceSettings.drilledMembers = [];
setTimeout(() => {
let mCnt: HTMLElement = document.querySelector('.e-movablecontent') as HTMLElement;
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.height).toBe('1692.1px');
expect((mCnt.querySelectorAll('.e-virtualtrack')[0] as HTMLElement).style.width).toBe('790px');
done();
}, 5000);
});
it('scroll top', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 890;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
document.querySelectorAll('.e-movablecontent')[0].scrollTop = 890;
pivotGridObj.virtualscrollModule.direction = 'vertical';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
done();
}, 5000);
});
it('timeout', (done: Function) => {
// pivotGridObj.dataSource.columns = [{ name: 'gender' }, { name: 'eyeColor' }, { name: 'name' }],
setTimeout(() => {
done();
}, 1000);
});
it('append name in column', (done: Function) => {
pivotGridObj.dataSourceSettings.columns = [{ name: 'gender' }, { name: 'eyeColor' }, { name: 'name' }],
setTimeout(() => {
//expect(document.querySelectorAll('.e-frozencontent')[0].scrollTop).toBe(890);
done();
}, 5000);
});
it('scroll left', (done: Function) => {
document.querySelectorAll('.e-movablecontent')[0].scrollLeft = 50000;
pivotGridObj.virtualscrollModule.direction = 'horizondal';
let args: MouseEvent = new MouseEvent("scroll", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
document.querySelector('.e-movablecontent').dispatchEvent(args);
setTimeout(() => {
expect(pivotGridObj.element.querySelectorAll('.e-movableheader')[0].scrollLeft === document.querySelectorAll('.e-movablecontent')[0].scrollLeft).toBeTruthy();
done();
}, 5000);
});
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
});
describe(' - Coverage', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid' });
let cf: any;
beforeAll(() => {
document.body.appendChild(elem);
PivotView.Inject(VirtualScroll, CalculatedField, GroupingBar, FieldList);
pivotGridObj = new PivotView(
{
dataSourceSettings: {
dataSource: pivot_nodata as IDataSet[],
enableSorting: false,
expandAll: true,
rows: [{ name: 'Country' }, { name: 'State' }],
columns: [{ name: 'Product' }, { name: 'Date' }],
values: [{ name: 'Amount' }, { name: 'Quantity' }],
},
allowCalculatedField: true,
showFieldList: true,
showGroupingBar: true,
enableVirtualization: true,
width: 600,
height: 300
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
let mouseup: MouseEvent = new MouseEvent('mouseup', {
'view': window,
'bubbles': true,
'cancelable': true
});
let mousedown: MouseEvent = new MouseEvent('mousedown', {
'view': window,
'bubbles': true,
'cancelable': true
});
let click: MouseEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
it('drop down menu (Sum of Amount) click', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-values .e-dropdown-icon')).not.toBeUndefined;
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('28550');
document.querySelectorAll('.e-values .e-dropdown-icon')[0].dispatchEvent(click);
done();
}, 1000);
});
it('Sum of Amount -> Count of Amount _using grouping bar dropdown menu', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
let menu: MenuEventArgs = {
element: document.querySelectorAll('.e-menu-item')[1] as HTMLElement,
item: { id: pivotGridObj.element.id + '_Count', text: 'Count' }
};
(pivotGridObj.pivotButtonModule.menuOption as any).selectOptionInContextMenu(menu);
done();
}, 1000);
});
it('Sum of Amount -> Count of Amount _result + enable sorting', () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('6');
pivotGridObj.dataSourceSettings.enableSorting = true;
});
it('Country -> descending _using grouping bar sort icon', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
//expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('');
document.querySelectorAll('.e-group-rows .e-sort')[0].dispatchEvent(click);
done();
}, 1000);
});
it('Country -> descending _result + Switch to ascending', () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('7');
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('United States');
document.querySelectorAll('.e-group-rows .e-sort')[0].dispatchEvent(click);
});
it('Country -> Switch to ascending _result + open field list', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelectorAll('.e-movablecontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('6');
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Canada');
document.querySelectorAll('.e-toggle-field-list')[0].dispatchEvent(click);
done();
}, 1000);
});
it('Open calculated field dialog', (done: Function) => {
cf = new CalculatedField(pivotGridObj);
cf.createCalculatedFieldDialog(pivotGridObj);
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.engineModule.enableSort = false;
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
done();
}, 1000);
});
it('drag and drop Amount(Count) node to drop field', () => {
let treeObj: any = cf.treeObj;
let filterAxiscontent: HTMLElement = document.getElementById(cf.parentID + 'droppable');
let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li');
let mousedown: any =
util.getEventObject('MouseEvents', 'mousedown', treeObj.element, li[0].querySelector('.e-drag'), 15, 10);
EventHandler.trigger(treeObj.element, 'mousedown', mousedown);
let mousemove: any =
util.getEventObject('MouseEvents', 'mousemove', treeObj.element, li[0].querySelector('.e-drag'), 15, 70);
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove.srcElement = mousemove.target = mousemove.toElement = filterAxiscontent;
mousemove = util.setMouseCordinates(mousemove, 150, 400);
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
let mouseup: any = util.getEventObject('MouseEvents', 'mouseup', treeObj.element, filterAxiscontent);
mouseup.type = 'mouseup';
EventHandler.trigger(<any>(document), 'mouseup', mouseup);
expect((document.querySelector('.e-pivot-formula') as HTMLTextAreaElement).value !== null).toBeTruthy;
});
it('set new field as "New" and close the dialog', () => {
cf.inputObj.value = 'New';
(document.querySelector('.e-pivot-calc-input') as HTMLInputElement).value = 'New';
(document.querySelector('.e-pivot-formula') as HTMLInputElement).value = '10';
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
cf.dialog.buttons[0].click();
document.querySelector('.e-pivotfieldlist-container .e-cancel-btn').dispatchEvent(click);
});
it('Country -> open filter dialog + uncheck canada + click ok btn', (done: Function) => {
pivotGridObj.engineModule.enableSort = true;
expect(document.querySelectorAll('.e-movableheader th')[11].textContent).toBe('New');
document.querySelectorAll('#Country .e-btn-filter')[0].dispatchEvent(click);
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[1] as HTMLElement;
firstNode.querySelector('.e-frame').dispatchEvent(mousedown);
firstNode.querySelector('.e-frame').dispatchEvent(mouseup);
firstNode.querySelector('.e-frame').dispatchEvent(click);
document.querySelector('.e-member-editor-dialog .e-ok-btn').dispatchEvent(click);
done();
}, 1000);
});
it('Country -> open filter dialog + check canada + click ok btn', (done: Function) => {
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('France');
expect(document.querySelectorAll('.e-movablecontent td')[0].textContent).toBe('4');
document.querySelectorAll('#Country .e-btn-filter')[0].dispatchEvent(click);
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[1] as HTMLElement;
firstNode.querySelector('.e-frame').dispatchEvent(mousedown);
firstNode.querySelector('.e-frame').dispatchEvent(mouseup);
firstNode.querySelector('.e-frame').dispatchEvent(click);
document.querySelector('.e-member-editor-dialog .e-ok-btn').dispatchEvent(click);
done();
}, 1000);
});
it('Country -> set report as no data', (done: Function) => {
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Canada');
//expect(document.querySelectorAll('.e-movablecontent td')[0].textContent).toBe('');
pivotGridObj.dataSourceSettings.rows[0].showNoDataItems = true;
setTimeout(() => {
//expect(document.querySelectorAll('.e-frozencontent tr')[1].querySelector('td .e-cellvalue').textContent).toBe('Alberta');
done();
}, 1000);
});
it('Country -> open filter dialog + uncheck france + click ok btn', (done: Function) => {
document.querySelectorAll('#Country .e-btn-filter')[0].dispatchEvent(click);
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[2] as HTMLElement;
firstNode.querySelector('.e-frame').dispatchEvent(mousedown);
firstNode.querySelector('.e-frame').dispatchEvent(mouseup);
firstNode.querySelector('.e-frame').dispatchEvent(click);
document.querySelector('.e-member-editor-dialog .e-ok-btn').dispatchEvent(click);
done();
}, 1000);
});
it('Country -> open filter dialog + check france + click ok btn', (done: Function) => {
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Canada');
expect(document.querySelectorAll('.e-movablecontent td')[0].textContent).toBe('6');
document.querySelectorAll('#Country .e-btn-filter')[0].dispatchEvent(click);
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[2] as HTMLElement;
firstNode.querySelector('.e-frame').dispatchEvent(mousedown);
firstNode.querySelector('.e-frame').dispatchEvent(mouseup);
firstNode.querySelector('.e-frame').dispatchEvent(click);
document.querySelector('.e-member-editor-dialog .e-ok-btn').dispatchEvent(click);
done();
}, 1000);
});
it('State -> open filter dialog + uncheck essonnee + click ok btn', (done: Function) => {
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Canada');
expect(document.querySelectorAll('.e-movablecontent td')[0].textContent).toBe('6');
document.querySelectorAll('#State .e-btn-filter')[0].dispatchEvent(click);
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
let treeNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[11] as HTMLElement;
treeNode.querySelector('.e-frame').dispatchEvent(mousedown);
treeNode.querySelector('.e-frame').dispatchEvent(mouseup);
treeNode.querySelector('.e-frame').dispatchEvent(click);
document.querySelector('.e-member-editor-dialog .e-ok-btn').dispatchEvent(click);
done();
}, 1000);
});
it('State -> open filter dialog + check essonnee + click ok btn', (done: Function) => {
document.querySelectorAll('#State .e-btn-filter')[0].dispatchEvent(click);
expect(document.querySelectorAll('.e-frozencontent td')[11].textContent).toBe('Garonne (Haute)');
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
let treeNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[11] as HTMLElement;
treeNode.querySelector('.e-frame').dispatchEvent(mousedown);
treeNode.querySelector('.e-frame').dispatchEvent(mouseup);
treeNode.querySelector('.e-frame').dispatchEvent(click);
document.querySelector('.e-member-editor-dialog .e-ok-btn').dispatchEvent(click);
done();
}, 1000);
});
it('Collapse Car', (done: Function) => {
expect(document.querySelectorAll('.e-frozencontent td')[11].textContent).toBe('Essonne');
expect(document.querySelectorAll('.e-frozencontent tr')[0].querySelector('td .e-cellvalue').textContent).toBe('Canada');
document.querySelectorAll('.e-movableheader th .e-collapse')[1].dispatchEvent(click);
setTimeout(() => {
expect(document.querySelectorAll('.e-movableheader th')[1].getAttribute('aria-rowspan')).toBe('2');
done();
}, 1000);
});
it('Expand Car', (done: Function) => {
document.querySelectorAll('.e-movableheader th .e-expand')[0].dispatchEvent(click);
setTimeout(() => {
expect(document.querySelectorAll('.e-movableheader th')[1].getAttribute('aria-rowspan')).toBe('1');
done();
}, 1000);
});
it('Product -> open filter dialog + uncheck car + click ok btn', (done: Function) => {
document.querySelectorAll('#Product .e-btn-filter')[0].dispatchEvent(click);
setTimeout(() => {
expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy();
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[2] as HTMLElement;
firstNode.querySelector('.e-frame').dispatchEvent(mousedown);
firstNode.querySelector('.e-frame').dispatchEvent(mouseup);
firstNode.querySelector('.e-frame').dispatchEvent(click);
document.querySelector('.e-member-editor-dialog .e-ok-btn').dispatchEvent(click);
done();
}, 1000);
});
it('Refresh data source', (done: Function) => {
(pivotGridObj.engineModule as any).getAxisByFieldName('None');
pivotGridObj.dataSourceSettings.dataSource = [];
done();
});
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
});
describe('Scroll apperance', () => {
describe('Scroll comparison ', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:1000px; width:900px' });
let data: IDataSet[] = [
{ row: 'row1', column: 'column1', value: 1 },
{ row: 'row2', column: 'column2', value: 2 },
{ row: 'row3', column: 'column3', value: 3 },
{ row: 'row4', column: 'column4', value: 4 },
]
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
beforeAll((done: Function) => {
if (!document.getElementById(elem.id)) {
document.body.style.height = '500px';
document.body.appendChild(elem);
}
let dataBound: EmitType<Object> = () => { done(); };
PivotView.Inject(GroupingBar, VirtualScroll);
pivotGridObj = new PivotView({
dataSourceSettings: {
dataSource: data,
expandAll: false,
rows: [{ name: 'row' }],
columns: [{ name: 'column' }],
values: [{ name: 'value' }],
},
width: 900,
height: 300,
enableVirtualization: false,
showGroupingBar: true,
dataBound: dataBound
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('Compare scrollbar', () => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
});
it('Display vertical scrollbar alone', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.height = 200;
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBeGreaterThan(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
it('Display horizondal scrollbar alone', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.setProperties({ height: '100%' }, true);
pivotGridObj.width = 300;
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBeGreaterThan(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
it('Hide both scrollbars', (done: Function) => {
pivotGridObj.setProperties({ height: '100%' }, true);
pivotGridObj.width = '100%';
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
it('Hide both scrollbars by setting auto', (done: Function) => {
pivotGridObj.setProperties({ height: 'auto' }, true);
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
});
describe('Scroll comparison - virtual scrolling', () => {
let pivotGridObj: PivotView;
let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:1000px; width:900px' });
let data: IDataSet[] = [
{ row: 'row1', column: 'column1', value: 1 },
{ row: 'row2', column: 'column2', value: 2 },
{ row: 'row3', column: 'column3', value: 3 },
{ row: 'row4', column: 'column4', value: 4 },
]
afterAll(() => {
if (pivotGridObj) {
pivotGridObj.destroy();
}
remove(elem);
});
beforeAll((done: Function) => {
if (!document.getElementById(elem.id)) {
document.body.style.height = '500px';
document.body.appendChild(elem);
}
let dataBound: EmitType<Object> = () => { done(); };
PivotView.Inject(GroupingBar, VirtualScroll);
pivotGridObj = new PivotView({
dataSourceSettings: {
dataSource: data,
expandAll: false,
rows: [{ name: 'row' }],
columns: [{ name: 'column' }],
values: [{ name: 'value' }],
},
width: 900,
height: 300,
enableVirtualization: true,
showGroupingBar: true,
dataBound: dataBound
});
pivotGridObj.appendTo('#PivotGrid');
});
beforeEach((done: Function) => {
setTimeout(() => { done(); }, 1000);
});
it('Scroll compare', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
it('Display vertical scrollbar alone', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.height = 200;
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBeGreaterThan(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
it('Display horizondal scrollbar alone', (done: Function) => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
pivotGridObj.setProperties({ height: '100%' }, true);
pivotGridObj.width = 300;
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBeGreaterThan(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
it('Hide both scrollbars by setting 100%', (done: Function) => {
pivotGridObj.setProperties({ height: '100%' }, true);
pivotGridObj.width = '100%';
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
it('Hide both scrollbars by setting auto', (done: Function) => {
pivotGridObj.setProperties({ height: 'auto' }, true);
setTimeout(() => {
expect(document.querySelector('.e-movablecontent').scrollHeight).toBe(document.querySelector('.e-movablecontent').clientHeight);
expect(document.querySelector('.e-movablecontent').scrollWidth).toBe(document.querySelector('.e-movablecontent').clientWidth);
done();
}, 1000);
});
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange);
//Check average change in memory samples to not be over 10MB
//expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile());
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import { assert } from 'chai'
import nock from 'nock'
import { PayIdUtils, XrplNetwork } from 'xpring-common-js'
import PayIdClient from '../../src/PayID/pay-id-client'
import PayIdError, { PayIdErrorType } from '../../src/PayID/pay-id-error'
describe('PayIdClient', function (): void {
afterEach(function () {
// Clean nock after each test.
nock.cleanAll()
})
it('cryptoAddressForPayId - invalid PayID', function (done): void {
// GIVEN a PayIDClient and an invalid PayID.
const invalidPayID = 'xpring.money/georgewashington' // Does not contain '$'
const payIDClient = new PayIdClient()
// WHEN an XRPAddress is requested for an invalid pay ID THEN an invalid PayID error is thrown.
payIDClient
.cryptoAddressForPayId(invalidPayID, XrplNetwork.Test)
.catch((error) => {
assert.equal(
(error as PayIdError).errorType,
PayIdErrorType.InvalidPayId,
)
done()
})
})
it('cryptoAddressForPayId - successful response - match found', async function () {
// GIVEN a PayIdClient, valid PayID and mocked networking to return a match for the PayID.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const payIDComponents = PayIdUtils.parsePayId(payId)
if (!payIDComponents) {
throw new Error('Test precondition failed: Could not generate a PayID')
}
const address = 'X7cBcY4bdTTzk3LHmrKAK6GyrirkXfLHGFxzke5zTmYMfw4'
const replyHeaders = {
'content-type': 'application/xrpl-testnet+json',
}
nock('https://xpring.money')
.get('/georgewashington')
.reply(
200,
{
addresses: [
{
addressDetailsType: 'CryptoAddressDetails',
addressDetails: {
address,
},
},
],
},
replyHeaders,
)
// WHEN an XRP address is requested.
const xrpAddressDetails = await payIdClient.cryptoAddressForPayId(
payId,
'xrpl-testnet',
)
// THEN the address exists.
assert.equal(xrpAddressDetails.address, address)
assert.equal(xrpAddressDetails.tag, undefined)
})
it('cryptoAddressForPayId - successful response - match not found', function (done) {
// GIVEN a PayIdClient, valid PayID and mocked networking to return a 404 for the payID.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const network = XrplNetwork.Test
const payIdComponents = PayIdUtils.parsePayId(payId)
if (!payIdComponents) {
throw new Error('Test precondition failed: Could not parse PayID')
}
nock('https://xpring.money').get('/georgewashington').reply(404, {})
// WHEN an XRPAddress is requested.
payIdClient.cryptoAddressForPayId(payId, 'xrpl-testnet').catch((error) => {
// THEN an unexpected response is thrown with the details of the error.
assert.equal(
(error as PayIdError).errorType,
PayIdErrorType.MappingNotFound,
)
const { message } = error
assert.include(message, payId)
assert.include(message, network)
done()
})
})
it('cryptoAddressForPayId - unknown mime type', function (done) {
// GIVEN a PayIdClient and with mocked networking to return a server error.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const serverErrorCode = 415
const serverError = {
statusCode: serverErrorCode,
error: 'Unsupported Media Type',
message: 'Unknown MIME type requested.',
}
nock('https://xpring.money')
.get('/georgewashington')
.reply(serverErrorCode, serverError)
// WHEN an XRPAddress is requested for a PayID.
payIdClient.cryptoAddressForPayId(payId, 'xrpl-testnet').catch((error) => {
// THEN an unexpected response is thrown with the details of the error.
assert.equal(
(error as PayIdError).errorType,
PayIdErrorType.UnexpectedResponse,
)
const { message } = error
assert.include(message, `${serverErrorCode}`)
assert.include(message, serverError.message)
done()
})
})
it('cryptoAddressForPayId - failed request', function (done) {
// GIVEN a PayIdClient and with mocked networking to return a server error.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const serverErrorCode = 503
const serverError = {
statusCode: serverErrorCode,
error: 'Internal error',
message: 'Something went wrong and it is not your fault',
}
nock('https://xpring.money')
.get('/georgewashington')
.reply(serverErrorCode, serverError)
// WHEN an XRPAddress is requested for a PayID.
payIdClient.cryptoAddressForPayId(payId, `xrpl-network`).catch((error) => {
// THEN an unexpected response is thrown with the details of the error.
assert.equal(
(error as PayIdError).errorType,
PayIdErrorType.UnexpectedResponse,
)
const { message } = error
assert.include(message, `${serverErrorCode}`)
assert.include(message, serverError.message)
done()
})
})
it('cryptoAddressForPayId - successful response - unexpected response format', function (done) {
// GIVEN a PayID client, valid PayID and mocked networking to return a match for the PayID.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const payIdComponents = PayIdUtils.parsePayId(payId)
if (!payIdComponents) {
throw new Error('Test precondition failed: Could not parse PayID')
}
// Field isn't named `address` in response.
nock('https://xpring.money').get('/georgewashington').reply(200, {
incorrectFieldName: 'X7cBcY4bdTTzk3LHmrKAK6GyrirkXfLHGFxzke5zTmYMfw4',
})
// WHEN an XRPAddress is requested for a PayID.
payIdClient.cryptoAddressForPayId(payId, 'xrpl-testnet').catch((error) => {
// THEN an unexpected response is thrown.
assert.equal(
(error as PayIdError).errorType,
PayIdErrorType.UnexpectedResponse,
)
done()
})
})
it('cryptoAddressForPayId - successful response - mismatched headers', function (done) {
// GIVEN mocked networking to return a match for the PayID on the wrong network.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const payIDComponents = PayIdUtils.parsePayId(payId)
if (!payIDComponents) {
throw new Error('Test precondition failed: Could not generate a PayID')
}
const address = 'X7cBcY4bdTTzk3LHmrKAK6GyrirkXfLHGFxzke5zTmYMfw4'
const replyHeaders = {
'content-type': 'application/btc-testnet+json',
}
nock('https://xpring.money')
.get('/georgewashington')
.reply(
200,
{
addresses: [
{
addressDetailsType: 'CryptoAddressDetails',
addressDetails: {
address,
},
},
],
},
replyHeaders,
)
// WHEN an address is requested for the PayID.
payIdClient.cryptoAddressForPayId(payId, 'xrpl-testnet').catch((error) => {
// THEN an unexpected response is thrown.
assert.equal(
(error as PayIdError).errorType,
PayIdErrorType.UnexpectedResponse,
)
done()
})
})
it('allAddressesForPayId - invalid PayID', function (done): void {
// GIVEN an PayIdClient and an invalid PayID.
const invalidPayID = 'xpring.money/georgewashington' // Does not contain '$'
const payIdClient = new PayIdClient()
// WHEN all addresses are resolved THEN an invalid PayID error is thrown.
payIdClient.allAddressesForPayId(invalidPayID).catch((error) => {
assert.equal((error as PayIdError).errorType, PayIdErrorType.InvalidPayId)
done()
})
})
it('allAddressesForPayId - successful response - match found', async function () {
// GIVEN a PayIdClient, a valid PayID and mocked networking to return a set of matches for the PayID.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const payIdComponents = PayIdUtils.parsePayId(payId)
if (!payIdComponents) {
throw new Error('Test precondition failed: Could not generate a PayID')
}
const replyHeaders = {
'content-type': 'application/payid+json',
}
const addresses = [
{
addressDetailsType: 'CryptoAddressDetails',
addressDetails: {
address: 'X7cBcY4bdTTzk3LHmrKAK6GyrirkXfLHGFxzke5zTmYMfw4',
},
},
{
addressDetailsType: 'CryptoAddressDetails',
addressDetails: {
address: 'XV5sbjUmgPpvXv4ixFWZ5ptAYZ6PD28Sq49uo34VyjnmK5H',
},
},
]
nock('https://xpring.money').get('/georgewashington').reply(
200,
{
addresses: addresses,
},
replyHeaders,
)
// WHEN all addresses are resolved.
const resolvedAddresses = await payIdClient.allAddressesForPayId(payId)
// THEN the returned data is as expected.
assert.deepEqual(addresses, resolvedAddresses)
})
it('allAddressesForPayId - successful response - match not found', function (done) {
// GIVEN a PayIdClient, a valid PayID and mocked networking to return a 404 for the payID.
const payId = 'georgewashington$xpring.money'
const payIdClient = new PayIdClient()
const payIdComponents = PayIdUtils.parsePayId(payId)
if (!payIdComponents) {
throw new Error('Test precondition failed: Could not parse PayID')
}
nock('https://xpring.money').get('/georgewashington').reply(404, {})
// WHEN all addresses are resolved
payIdClient.allAddressesForPayId(payId).catch((error) => {
// THEN an unexpected response is thrown with the details of the error.
assert.equal(
(error as PayIdError).errorType,
PayIdErrorType.MappingNotFound,
)
const { message } = error
assert.include(message, payId)
done()
})
})
}) | the_stack |
import ConfigFile, { ValueType } from './config-file';
import * as path from 'path';
import { ProcessedPackageConfig, DepType, PackageTarget, processPackageTarget, serializePackageConfig,
serializePackageTargetCanonical, resourceInstallRegEx, parsePackageName, processPackageConfig } from '../install/package';
import { Project } from '../project';
export default class PackageJson extends ConfigFile {
private jspmPrefix: boolean;
private depsPrefixed: boolean;
private dir: string;
private project: Project;
jspmAware: boolean;
name: string;
version: string;
type: string;
src: string;
dist: string;
main: string;
baseURL: string;
packages: string;
private: boolean;
dependencies: {
[name: string]: {
type: DepType,
target: string | PackageTarget
}
};
overrides: { target: PackageTarget | string, override: ProcessedPackageConfig, fresh: boolean }[];
hooks: {
[hook: string]: string
};
scripts: {
[name: string]: string;
};
configFile: string;
constructor (pjsonPath: string, project: Project, hasJspmConfig: boolean) {
super(pjsonPath, [
'name',
'version',
'main',
['directories', [
'src',
'dist',
'baseURL',
'packages'
]],
'dependencies',
'devDependencies',
'peerDependencies',
'optionalDependencies',
['jspm', [
'name',
'version',
['directories', [
'src',
'dist',
'baseURL',
'packages'
]],
'dependencies',
'devDependencies',
'peerDependencies',
'optionalDependencies',
'private',
'scripts',
['hooks', [
'preinstall',
'postinstall'
]],
'overrides'
]],
'private',
'scripts',
'type',
['hooks', [
'preinstall',
'postinstall'
]],
'overrides'
]);
this.project = project;
this.lock();
this.read();
// auto-inject "type": "module" for jspm projects
this.type = this.getValue(['type'], 'string') || hasJspmConfig && 'module';
this.dir = path.dirname(this.fileName);
this.jspmPrefix = this.has(['jspm']);
this.jspmAware = this.jspmPrefix || this.has(['registry']);
// jspm: true is allowed
try {
if (this.getValue(['jspm'], 'boolean'))
this.jspmPrefix = false;
}
catch (e) {}
//if (!this.jspmAware)
// this.jspmPrefix = true;
this.name = this.prefixedGetValue(['name'], 'string') || !this.jspmAware && 'app';
this.version = this.prefixedGetValue(['version'], 'string');
this.hooks = this.prefixedGetObject(['hooks'], true) || {};
this.scripts = this.prefixedGetObject(['scripts'], false) || {};
this.private = this.prefixedGetValue(['private'], 'boolean');
this.setBaseURL(this.prefixedGetValue(['directories', 'baseURL'], 'string') || '');
this.depsPrefixed = this.jspmPrefix;
if (this.jspmAware &&
!this.has(['jspm', 'dependencies']) &&
!this.has(['jspm', 'peerDependencies']) &&
!this.has(['jspm', 'devDependencies']) &&
!this.has(['jspm', 'optionalDependencies']) &&
(this.has(['dependencies']) ||
this.has(['peerDependencies']) ||
this.has(['devDependencies']) ||
this.has(['optionalDependencies'])))
this.depsPrefixed = false;
this.dependencies = {};
const optionalDependencies = this.readDependencies('optionalDependencies');
if (optionalDependencies)
Object.keys(optionalDependencies).forEach(dep => {
this.dependencies[dep] = {
type: DepType.optional,
target: processPackageTarget(dep, optionalDependencies[dep], this.project.defaultRegistry, false)
};
});
const devDependencies = this.readDependencies('devDependencies');
if (devDependencies)
Object.keys(devDependencies).forEach(dep => {
this.dependencies[dep] = {
type: DepType.dev,
target: processPackageTarget(dep, devDependencies[dep], this.project.defaultRegistry, false)
};
});
const dependencies = this.readDependencies('dependencies');
if (dependencies)
Object.keys(dependencies).forEach(dep => {
this.dependencies[dep] = {
type: DepType.primary,
target: processPackageTarget(dep, dependencies[dep], this.project.defaultRegistry, false)
};
});
const peerDependencies = this.readDependencies('peerDependencies');
if (peerDependencies)
Object.keys(peerDependencies).forEach(dep => {
this.dependencies[dep] = {
type: DepType.peer,
target: processPackageTarget(dep, peerDependencies[dep], this.project.defaultRegistry, false)
};
});
const overrides = this.prefixedGetObject(['overrides']);
this.overrides = [];
if (overrides) {
Object.keys(overrides).forEach(name => {
let target;
if (name.match(resourceInstallRegEx)) {
target = name;
}
else {
const pkgName = parsePackageName(name);
target = new PackageTarget(pkgName.registry, pkgName.name, pkgName.version);
}
this.overrides.push({
target,
override: processPackageConfig(overrides[name]),
fresh: false
});
});
}
}
dispose () {
this.unlock();
}
setBaseURL (baseURL: string) {
if (baseURL[0] === '/' || baseURL.indexOf('//') !== -1 || baseURL.indexOf('\\\\') !== -1 || baseURL.indexOf(':') !== -1) {
this.project.log.warn('Server baseURL should be a relative file path. Reverting to current project folder.');
baseURL = '';
}
this.baseURL = path.resolve(this.dir, baseURL);
let src = this.prefixedGetValue(['directories', 'src']);
if (src === undefined)
this.src = path.resolve(this.baseURL, 'src');
else
this.src = path.resolve(this.dir, src);
let dist = this.prefixedGetValue(['directories', 'dist']);
if (dist === undefined)
this.dist = path.resolve(this.baseURL, 'dist');
else
this.dist = path.resolve(this.dir, dist);
let packages = this.prefixedGetValue(['directories', 'packages']);
if (packages === undefined)
this.packages = path.resolve(this.baseURL, 'jspm_packages');
else
this.packages = path.resolve(this.dir, packages);
}
write () {
// sync public properties with underlying file representation
if (this.name) {
this.prefixedSetValue(['name'], this.name);
}
else {
this.remove(['name']);
this.remove(['jspm', 'name']);
}
if (this.main)
this.setValue(['main'], this.main);
if (this.type) {
this.remove(['type']);
this.setValue(['type'], this.type);
}
if (this.private !== undefined) {
this.prefixedSetValue(['private'], this.private);
}
const dependencies = {};
const peerDependencies = {};
const devDependencies = {};
const optionalDependencies = {};
Object.keys(this.dependencies).forEach(dep => {
const entry = this.dependencies[dep];
const defaultRegistry = this.project.defaultRegistry;
switch (entry.type) {
case DepType.primary:
dependencies[dep] = serializePackageTargetCanonical(dep, entry.target, defaultRegistry);
break;
case DepType.peer:
peerDependencies[dep] = serializePackageTargetCanonical(dep, entry.target, defaultRegistry);
break;
case DepType.dev:
devDependencies[dep] = serializePackageTargetCanonical(dep, entry.target, defaultRegistry);
break;
case DepType.optional:
optionalDependencies[dep] = serializePackageTargetCanonical(dep, entry.target, defaultRegistry);
break;
}
});
this.writeDependencies('dependencies', dependencies);
this.writeDependencies('peerDependencies', peerDependencies);
this.writeDependencies('devDependencies', devDependencies);
this.writeDependencies('optionalDependencies', optionalDependencies);
const overrides = {};
this.overrides.sort(({ target: targetA }, { target: targetB }) => {
if (typeof targetA === 'string')
return typeof targetB === 'string' ? (targetA > targetB ? 1 : -1) : 1;
else if (typeof targetB === 'string')
return -1;
if (targetA.registry !== targetB.registry)
return targetA.registry > targetB.registry ? 1 : -1;
if (targetA.name !== targetB.name)
return targetA.name > targetB.name ? 1 : -1;
return targetA.range.gt(targetB.range) ? 1 : -1;
})
.forEach(({ target, override }) => {
overrides[target.toString()] = serializePackageConfig(override, typeof target !== 'string' ? target.registry : undefined);
});
this.prefixedSetObject(['overrides'], overrides, !this.jspmPrefix || !this.has(['overrides']));
let baseURL = this.toRelativePath(this.baseURL);
let baseURLPath = baseURL + (baseURL ? '/' : '');
this.prefixedSetValue(['directories', 'baseURL'], baseURL || '.', '.');
this.prefixedSetValue(['directories', 'packages'], this.toRelativePath(this.packages), baseURLPath + 'jspm_packages');
this.prefixedSetValue(['directories', 'src'], this.toRelativePath(this.src) || '.', baseURLPath + 'src');
this.prefixedSetValue(['directories', 'dist'], this.toRelativePath(this.dist), baseURLPath + 'dist');
// always ensure we save as jspm aware
if (!this.has(['jspm']) && !this.has(['registry'])) {
if (this.jspmPrefix)
this.setObject(['jspm'], {});
//else
//this.setValue(['jspm'], true);
}
return super.write();
}
setPrefix (jspmPrefix: boolean) {
// removes the "jspm" property in the package.json
// flattening it down the to base-level
if (this.jspmPrefix && this.has(['jspm']) && !jspmPrefix) {
var jspmProperties = this.getProperties(['jspm']);
var baseProperties = this.getProperties([]);
var depsPrefixed = this.depsPrefixed;
if (depsPrefixed) {
this.remove(['dependencies']);
this.remove(['peerDependencies']);
this.remove(['devDependencies']);
}
jspmProperties.forEach(prop => {
this.remove([prop.key]);
baseProperties.push(prop);
});
this.remove(['jspm']);
this.changed = true;
}
else if (!this.jspmPrefix && jspmPrefix) {
if (this.getValue(['jspm']))
this.remove(['jspm']);
}
this.jspmPrefix = this.depsPrefixed = jspmPrefix;
}
private readDependencies (depName: string) {
if (this.depsPrefixed)
return this.getObject(['jspm', depName]);
else
return this.getObject([depName]);
}
private writeDependencies (depName: string, value: Object) {
if (this.depsPrefixed)
return this.setObject(['jspm', depName], value, !this.has(['jspm', depName]));
else
this.setObject([depName], value, !this.has([depName]));
}
private prefixedSetObject (memberArray, object, clearIfEmpty = false) {
var prefixed = ['jspm'].concat(memberArray);
var newPrefixed = this.jspmPrefix && !this.jspmAware;
if (!newPrefixed && this.has(prefixed))
this.setObject(prefixed, object, clearIfEmpty);
else if (!newPrefixed && this.has(memberArray))
this.setObject(memberArray, object, clearIfEmpty);
else if (this.jspmPrefix)
this.setObject(prefixed, object, clearIfEmpty);
else
this.setObject(memberArray, object, clearIfEmpty);
}
private prefixedSetValue (memberArray, value, defaultValue?) {
var prefixed = ['jspm', ...memberArray];
var newPrefixed = this.jspmPrefix && !this.jspmAware;
// if already specified, continue to specify
if (!newPrefixed && this.has(prefixed))
this.setValue(prefixed, value);
else if (!newPrefixed && this.has(memberArray))
this.setValue(memberArray, value);
// otherwise only specify if not default
else if (this.jspmPrefix && value !== defaultValue)
this.setValue(prefixed, value);
else if (value !== defaultValue)
this.setValue(memberArray, value);
}
private prefixedGetValue (memberArray: string[], type?: ValueType) {
var value;
if (this.jspmPrefix)
value = this.getValue(['jspm'].concat(memberArray), type);
if (typeof value == 'undefined')
value = this.getValue(memberArray, type);
return value;
}
private prefixedGetObject (memberArray: string[], nested = true) {
return this.jspmPrefix && this.getObject(['jspm'].concat(memberArray), nested) || this.getObject(memberArray, nested);
}
private toRelativePath (absPath: string) {
return path.relative(this.dir, absPath).replace(/\\/g, '/');
}
} | the_stack |
import * as Constants from '../../../constants/chat2'
import * as React from 'react'
import * as RPCTypes from '../../../constants/types/rpc-gen'
import * as Types from '../../../constants/types/chat2'
import * as Chat2Gen from '../../../actions/chat2-gen'
import ProfileResetNotice from './system-profile-reset-notice/container'
import RetentionNotice from './retention-notice/container'
import shallowEqual from 'shallowequal'
import * as Kb from '../../../common-adapters'
import * as Container from '../../../util/container'
import * as Styles from '../../../styles'
import NewChatCard from './cards/new-chat'
import HelloBotCard from './cards/hello-bot'
import MakeTeamCard from './cards/make-team'
import * as FsConstants from '../../../constants/fs'
import * as FsTypes from '../../../constants/types/fs'
type OwnProps = {
conversationIDKey: Types.ConversationIDKey
measure: (() => void) | null
}
type Props = {
conversationIDKey: Types.ConversationIDKey
createConversationDisallowedUsers: Array<string>
createConversationErrorDescription: string
createConversationErrorHeader: string
hasOlderResetConversation: boolean
isHelloBotConversation: boolean
isSelfConversation: boolean
loadMoreType: 'moreToLoad' | 'noMoreToLoad'
measure: (() => void) | null
onBack: (() => void) | null
onCreateWithoutThem: (() => void) | null
openPrivateFolder: () => void
pendingState: 'waiting' | 'error' | 'done'
showRetentionNotice: boolean
showTeamOffer: boolean
}
class SpecialTopMessage extends React.PureComponent<Props> {
componentDidUpdate(prevProps: Props) {
if (this.props.measure && !shallowEqual(this.props, prevProps)) {
this.props.measure()
}
}
render() {
return (
<Kb.Box>
{this.props.loadMoreType === 'noMoreToLoad' && this.props.showRetentionNotice && (
<RetentionNotice conversationIDKey={this.props.conversationIDKey} measure={this.props.measure} />
)}
<Kb.Box style={styles.spacer} />
{this.props.hasOlderResetConversation && (
<ProfileResetNotice conversationIDKey={this.props.conversationIDKey} />
)}
{this.props.pendingState === 'waiting' && (
<Kb.Box style={styles.more}>
<Kb.Text type="BodySmall">Loading...</Kb.Text>
</Kb.Box>
)}
{this.props.pendingState === 'error' && (
<Kb.Box2
direction="vertical"
fullWidth={true}
fullHeight={true}
gap="small"
gapStart={true}
centerChildren={true}
>
<Kb.Icon color={Styles.globalColors.black_20} sizeType="Huge" type="iconfont-warning" />
<Kb.Text center={true} style={styles.errorText} type="Header">
{this.props.createConversationErrorHeader}
</Kb.Text>
{this.props.createConversationDisallowedUsers &&
this.props.createConversationDisallowedUsers.length > 0 && (
<>
{this.props.createConversationDisallowedUsers.map((username, idx) => (
<Kb.ListItem2
key={username}
type={Styles.isMobile ? 'Large' : 'Small'}
icon={<Kb.Avatar size={Styles.isMobile ? 48 : 32} username={username} />}
firstItem={idx === 0}
body={
<Kb.Box2 direction="vertical" fullWidth={true}>
<Kb.Text type="BodySemibold">{username}</Kb.Text>
</Kb.Box2>
}
/>
))}
</>
)}
<Kb.Text center={true} type="BodyBig" style={styles.errorText} selectable={true}>
{this.props.createConversationErrorDescription}
</Kb.Text>
<Kb.ButtonBar
direction={Styles.isMobile ? 'column' : 'row'}
fullWidth={true}
style={styles.buttonBar}
>
{this.props.onCreateWithoutThem && (
<Kb.WaitingButton
type="Default"
label="Create without them"
onClick={this.props.onCreateWithoutThem}
waitingKey={null}
/>
)}
{this.props.onBack && (
<Kb.WaitingButton
type={this.props.onCreateWithoutThem ? 'Dim' : 'Default'}
label={this.props.onCreateWithoutThem ? 'Cancel' : 'Okay'}
onClick={this.props.onBack}
waitingKey={null}
/>
)}
</Kb.ButtonBar>
</Kb.Box2>
)}
{this.props.loadMoreType === 'noMoreToLoad' &&
!this.props.showRetentionNotice &&
this.props.pendingState === 'done' && (
<Kb.Box style={styles.more}>
{this.props.isHelloBotConversation ? (
<HelloBotCard />
) : (
<NewChatCard
self={this.props.isSelfConversation}
openPrivateFolder={this.props.openPrivateFolder}
/>
)}
</Kb.Box>
)}
{this.props.showTeamOffer && (
<Kb.Box style={styles.more}>
<MakeTeamCard conversationIDKey={this.props.conversationIDKey} />
</Kb.Box>
)}
{this.props.loadMoreType === 'moreToLoad' && this.props.pendingState === 'done' && (
<Kb.Box style={styles.more}>
<Kb.Text type="BodyBig">
<Kb.Emoji size={16} emojiName=":moyai:" />
</Kb.Text>
<Kb.Text type="BodySmallSemibold">Digging ancient messages...</Kb.Text>
</Kb.Box>
)}
</Kb.Box>
)
}
}
const styles = Styles.styleSheetCreate(
() =>
({
buttonBar: {
padding: Styles.globalMargins.small,
},
errorText: {
padding: Styles.globalMargins.small,
},
more: {
...Styles.globalStyles.flexBoxColumn,
alignItems: 'center',
paddingBottom: Styles.globalMargins.medium,
width: '100%',
},
spacer: {
height: Styles.globalMargins.small,
},
} as const)
)
export default Container.namedConnect(
(state, ownProps: OwnProps) => {
const hasLoadedEver = state.chat2.messageOrdinals.get(ownProps.conversationIDKey) !== undefined
const meta = Constants.getMeta(state, ownProps.conversationIDKey)
const participantInfo = Constants.getParticipantInfo(state, ownProps.conversationIDKey)
let pendingState: Props['pendingState']
switch (ownProps.conversationIDKey) {
case Constants.pendingWaitingConversationIDKey:
pendingState = 'waiting'
break
case Constants.pendingErrorConversationIDKey:
pendingState = 'error'
break
default:
pendingState = 'done'
break
}
const loadMoreType =
state.chat2.moreToLoadMap.get(ownProps.conversationIDKey) !== false
? ('moreToLoad' as const)
: ('noMoreToLoad' as const)
const showTeamOffer =
hasLoadedEver &&
loadMoreType === 'noMoreToLoad' &&
meta.teamType === 'adhoc' &&
participantInfo.all.length > 2
const hasOlderResetConversation = meta.supersedes !== Constants.noConversationIDKey
// don't show default header in the case of the retention notice being visible
const showRetentionNotice =
meta.retentionPolicy.type !== 'retain' &&
!(meta.retentionPolicy.type === 'inherit' && meta.teamRetentionPolicy.type === 'retain')
const isHelloBotConversation =
meta.teamType === 'adhoc' &&
participantInfo.all.length === 2 &&
participantInfo.all.includes('hellobot')
const isSelfConversation =
meta.teamType === 'adhoc' &&
participantInfo.all.length === 1 &&
participantInfo.all.includes(state.config.username)
return {
conversationIDKey: ownProps.conversationIDKey,
createConversationError: state.chat2.createConversationError,
hasOlderResetConversation,
isHelloBotConversation,
isSelfConversation,
loadMoreType,
measure: ownProps.measure,
pendingState,
showRetentionNotice,
showTeamOffer,
username: state.config.username,
}
},
dispatch => ({
_onBack: () => dispatch(Chat2Gen.createNavigateToInbox()),
_onCreateWithoutThem: (allowedUsers: Array<string>) =>
dispatch(Chat2Gen.createCreateConversation({participants: allowedUsers})),
_openPrivateFolder: (username: string) =>
dispatch(
FsConstants.makeActionForOpenPathInFilesTab(FsTypes.stringToPath(`/keybase/private/${username}`))
),
}),
(stateProps, dispatchProps, __: OwnProps) => {
const {username, ...props} = stateProps
let createConversationDisallowedUsers: Array<string> = []
let createConversationErrorDescription = ''
let createConversationErrorHeader = ''
let onCreateWithoutThem: (() => void) | null = null
if (stateProps.createConversationError) {
const {allowedUsers, code, disallowedUsers, message} = stateProps.createConversationError
if (code === RPCTypes.StatusCode.scteamcontactsettingsblock) {
if (disallowedUsers.length === 1 && allowedUsers.length === 0) {
// One-on-one conversation.
createConversationErrorHeader = `You cannot start a conversation with @${disallowedUsers[0]}.`
createConversationErrorDescription = `@${disallowedUsers[0]}'s contact restrictions prevent you from getting in touch. Contact them outside Keybase to proceed.`
} else {
// Group conversation.
createConversationDisallowedUsers = disallowedUsers
createConversationErrorHeader = 'The following people cannot be added to the conversation:'
createConversationErrorDescription =
'Their contact restrictions prevent you from getting in touch. Contact them outside Keybase to proceed.'
if (disallowedUsers.length > 0 && allowedUsers.length > 0) {
onCreateWithoutThem = () => dispatchProps._onCreateWithoutThem(allowedUsers)
}
}
} else {
createConversationErrorHeader = 'There was an error creating the conversation.'
createConversationErrorDescription = message
}
}
return {
createConversationDisallowedUsers,
createConversationErrorDescription,
createConversationErrorHeader,
onBack: Styles.isMobile ? dispatchProps._onBack : null,
onCreateWithoutThem,
openPrivateFolder: () => dispatchProps._openPrivateFolder(username),
...props,
}
},
'SpecialTopMessage'
)(SpecialTopMessage) | the_stack |
import { TtfTableInfo } from './ttf-table-info';
import { Dictionary } from './../../collections/dictionary';
import { TtfNameTable } from './ttf-name-table';
import { TtfNameRecord } from './ttf-name-record';
import { TtfHeadTable } from './ttf-head-table';
import { TtfMetrics } from './ttf-metrics';
import { TtfHorizontalHeaderTable } from './ttf-horizontal-header-table';
import { TtfOS2Table } from './ttf-OS2-Table';
import { TtfPostTable } from './ttf-post-table';
import { TtfLongHorMetric } from './ttf-long-hor-metric';
import { TtfCmapSubTable } from './ttf-cmap-sub-table';
import { TtfCmapTable } from './ttf-cmap-table';
import { TtfGlyphInfo } from './ttf-glyph-info';
import { TtfLocaTable } from './ttf-loca-table';
import { TtfAppleCmapSubTable } from './ttf-apple-cmap-sub-table';
import { TtfMicrosoftCmapSubTable } from './ttf-microsoft-cmap-sub-table';
import { TtfTrimmedCmapSubTable } from './ttf-trimmed-cmap-sub-table';
import { TtfGlyphHeader } from './ttf-glyph-header';
import { Rectangle } from './../../drawing/pdf-drawing';
import { StringTokenizer } from './string-tokenizer';
import { TtfCmapFormat, TtfCmapEncoding, TtfPlatformID } from './enum';
import { TtfMicrosoftEncodingID, TtfMacintoshEncodingID, TtfCompositeGlyphFlags } from './enum';
import { BigEndianWriter } from './../../input-output/big-endian-writer';
export class TtfReader {
//Fields
private fontData : Uint8Array;
private readonly int32Size : number = 4;
private offset : number;
public tableDirectory : Dictionary<string, TtfTableInfo>;
private isTtcFont : boolean = false;
private isMacTtf : boolean = false;
private lowestPosition : number;
private metricsName : string = '';
public metrics : TtfMetrics;
private maxMacIndex : number;
private isFontPresent : boolean;
private isMacTTF : boolean = false;
private missedGlyphs : number = 0;
private tableNames : string[] = ['cvt ', 'fpgm', 'glyf', 'head', 'hhea', 'hmtx', 'loca', 'maxp', 'prep'];
private entrySelectors : number[] = [0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4];
/**
* Width table.
*/
private width : number[];
/**
* Indicates whether loca table is short.
*/
public bIsLocaShort : boolean;
/**
* Glyphs for Macintosh or Symbol fonts.
*/
private macintoshDictionary : Dictionary<number, TtfGlyphInfo>;
/**
* Glyphs for Microsoft or Symbol fonts.
*/
private microsoftDictionary : Dictionary<number, TtfGlyphInfo>;
/**
* Glyphs for Macintosh or Symbol fonts (glyph index - key, glyph - value).
*/
private internalMacintoshGlyphs : Dictionary<number, TtfGlyphInfo>;
/**
* Glyphs for Microsoft or Symbol fonts (glyph index - key, glyph - value).
*/
private internalMicrosoftGlyphs : Dictionary<number, TtfGlyphInfo>;
//Properties
/**
* Gets glyphs for Macintosh or Symbol fonts (char - key, glyph - value).
*/
private get macintosh() : Dictionary<number, TtfGlyphInfo> {
if (this.macintoshDictionary === null || this.macintoshDictionary === undefined) {
this.macintoshDictionary = new Dictionary<number, TtfGlyphInfo>();
}
return this.macintoshDictionary;
}
/**
* Gets glyphs for Microsoft or Symbol fonts (char - key, glyph - value).
*/
private get microsoft() : Dictionary<number, TtfGlyphInfo> {
if (this.microsoftDictionary === null || this.microsoftDictionary === undefined) {
this.microsoftDictionary = new Dictionary<number, TtfGlyphInfo>();
}
return this.microsoftDictionary;
}
/**
* Gets glyphs for Macintosh or Symbol fonts (glyph index - key, glyph - value).
*/
private get macintoshGlyphs() : Dictionary<number, TtfGlyphInfo> {
if (this.internalMacintoshGlyphs === null || this.internalMacintoshGlyphs === undefined) {
this.internalMacintoshGlyphs = new Dictionary<number, TtfGlyphInfo>();
}
return this.internalMacintoshGlyphs;
}
/**
* Gets glyphs for Microsoft Unicode fonts (glyph index - key, glyph - value).
*/
private get microsoftGlyphs() : Dictionary<number, TtfGlyphInfo> {
if (this.internalMicrosoftGlyphs === null || this.internalMicrosoftGlyphs === undefined) {
this.internalMicrosoftGlyphs = new Dictionary<number, TtfGlyphInfo>();
}
return this.internalMicrosoftGlyphs;
}
//Constructors
public constructor(fontData : Uint8Array) {
this.fontData = fontData;
this.initialize();
}
//Implementation
private initialize() : void {
if (this.metrics === undefined) {
this.metrics = new TtfMetrics();
}
this.readFontDictionary();
let nameTable : TtfNameTable = this.readNameTable();
let headTable : TtfHeadTable = this.readHeadTable();
this.initializeFontName(nameTable);
this.metrics.macStyle = headTable.macStyle;
}
private readFontDictionary() : void {
this.offset = 0;
let version : number = this.checkPreambula();
//this.offset += 4;
let numTables : number = this.readInt16(this.offset);
let searchRange : number = this.readInt16(this.offset);
let entrySelector : number = this.readInt16(this.offset);
let rangeShift : number = this.readInt16(this.offset);
if (this.tableDirectory === undefined) {
this.tableDirectory = new Dictionary<string, TtfTableInfo>();
}
for (let i : number = 0; i < numTables; ++i) {
let table : TtfTableInfo = new TtfTableInfo();
let tableKey : string = this.readString(this.int32Size);
table.checksum = this.readInt32(this.offset);
table.offset = this.readInt32(this.offset);
table.length = this.readInt32(this.offset);
this.tableDirectory.setValue(tableKey, table);
}
this.lowestPosition = this.offset;
if (!this.isTtcFont) {
this.fixOffsets();
}
}
private fixOffsets() : void {
let minOffset : number = Number.MAX_VALUE;
// Search for a smallest offset and compare it with the lowest position found.
let tableKeys : string[] = this.tableDirectory.keys();
for (let i : number = 0; i < tableKeys.length; i++) {
let value : TtfTableInfo = this.tableDirectory.getValue(tableKeys[i]);
let offset : number = value.offset;
if (minOffset > offset) {
minOffset = offset;
if (minOffset <= this.lowestPosition) {
break;
}
}
}
let shift : number = minOffset - this.lowestPosition;
if (shift !== 0) {
let table : Dictionary<string, TtfTableInfo> = new Dictionary<string, TtfTableInfo>();
for (let i : number = 0; i < tableKeys.length; i++) {
let value : TtfTableInfo = this.tableDirectory.getValue(tableKeys[i]);
value.offset -= shift;
table.setValue(tableKeys[i], value);
}
this.tableDirectory = table;
}
}
private checkPreambula() : number {
let version : number = this.readInt32(this.offset);
this.isMacTtf = (version === 0x74727565) ? true : false;
if (version !== 0x10000 && version !== 0x74727565 && version !== 0x4f54544f) {
this.isTtcFont = true;
this.offset = 0;
let fontTag : string = this.readString(4);
if (fontTag !== 'ttcf') {
throw new Error('Can not read TTF font data');
}
//skip 4
this.offset += 4;
let ttcIdentificationNumber : number = this.readInt32(this.offset);
if (ttcIdentificationNumber < 0) {
throw new Error('Can not read TTF font data');
}
this.offset = this.readInt32(this.offset);
version = this.readInt32(this.offset);
}
return version;
}
private readNameTable() : TtfNameTable {
let tableInfo : TtfTableInfo = this.getTable('name');
this.offset = tableInfo.offset;
let table : TtfNameTable = new TtfNameTable();
table.formatSelector = this.readUInt16(this.offset);
table.recordsCount = this.readUInt16(this.offset);
table.offset = this.readUInt16(this.offset);
table.nameRecords = [];
let recordSize : number = 12;
let position : number = this.offset;
for (let i : number = 0; i < table.recordsCount; i++) {
this.offset = position;
let record : TtfNameRecord = new TtfNameRecord();
record.platformID = this.readUInt16(this.offset);
record.encodingID = this.readUInt16(this.offset);
record.languageID = this.readUInt16(this.offset);
record.nameID = this.readUInt16(this.offset);
record.length = this.readUInt16(this.offset);
record.offset = this.readUInt16(this.offset);
this.offset = tableInfo.offset + table.offset + record.offset;
let unicode : boolean = (record.platformID === 0 || record.platformID === 3);
record.name = this.readString(record.length, unicode);
table.nameRecords[i] = record;
position += recordSize;
}
return table;
}
private readHeadTable() : TtfHeadTable {
let tableInfo : TtfTableInfo = this.getTable('head');
this.offset = tableInfo.offset;
let table : TtfHeadTable = new TtfHeadTable();
table.version = this.readFixed(this.offset);
table.fontRevision = this.readFixed(this.offset);
table.checkSumAdjustment = this.readUInt32(this.offset);
table.magicNumber = this.readUInt32(this.offset);
table.flags = this.readUInt16(this.offset);
table.unitsPerEm = this.readUInt16(this.offset);
table.created = this.readInt64(this.offset);
table.modified = this.readInt64(this.offset);
table.xMin = this.readInt16(this.offset);
table.yMin = this.readInt16(this.offset);
table.xMax = this.readInt16(this.offset);
table.yMax = this.readInt16(this.offset);
table.macStyle = this.readUInt16(this.offset);
table.lowestReadableSize = this.readUInt16(this.offset);
table.fontDirectionHint = this.readInt16(this.offset);
table.indexToLocalFormat = this.readInt16(this.offset);
table.glyphDataFormat = this.readInt16(this.offset);
return table;
}
private readHorizontalHeaderTable() : TtfHorizontalHeaderTable {
let tableInfo : TtfTableInfo = this.getTable('hhea');
this.offset = tableInfo.offset;
let table : TtfHorizontalHeaderTable = new TtfHorizontalHeaderTable();
table.version = this.readFixed(this.offset);
table.ascender = this.readInt16(this.offset);
table.descender = this.readInt16(this.offset);
table.lineGap = this.readInt16(this.offset);
table.advanceWidthMax = this.readUInt16(this.offset);
table.minLeftSideBearing = this.readInt16(this.offset);
table.minRightSideBearing = this.readInt16(this.offset);
table.xMaxExtent = this.readInt16(this.offset);
table.caretSlopeRise = this.readInt16(this.offset);
table.caretSlopeRun = this.readInt16(this.offset);
//skip 2 * 5
this.offset += 10;
table.metricDataFormat = this.readInt16(this.offset);
table.numberOfHMetrics = this.readUInt16(this.offset);
return table;
}
private readOS2Table() : TtfOS2Table {
let tableInfo : TtfTableInfo = this.getTable('OS/2');
this.offset = tableInfo.offset;
let table : TtfOS2Table = new TtfOS2Table();
table.version = this.readUInt16(this.offset);
table.xAvgCharWidth = this.readInt16(this.offset);
table.usWeightClass = this.readUInt16(this.offset);
table.usWidthClass = this.readUInt16(this.offset);
table.fsType = this.readInt16(this.offset);
table.ySubscriptXSize = this.readInt16(this.offset);
table.ySubscriptYSize = this.readInt16(this.offset);
table.ySubscriptXOffset = this.readInt16(this.offset);
table.ySubscriptYOffset = this.readInt16(this.offset);
table.ySuperscriptXSize = this.readInt16(this.offset);
table.ySuperscriptYSize = this.readInt16(this.offset);
table.ySuperscriptXOffset = this.readInt16(this.offset);
table.ySuperscriptYOffset = this.readInt16(this.offset);
table.yStrikeoutSize = this.readInt16(this.offset);
table.yStrikeoutPosition = this.readInt16(this.offset);
table.sFamilyClass = this.readInt16(this.offset);
table.panose = this.readBytes(10);
table.ulUnicodeRange1 = this.readUInt32(this.offset);
table.ulUnicodeRange2 = this.readUInt32(this.offset);
table.ulUnicodeRange3 = this.readUInt32(this.offset);
table.ulUnicodeRange4 = this.readUInt32(this.offset);
table.vendorIdentifier = this.readBytes(4);
table.fsSelection = this.readUInt16(this.offset);
table.usFirstCharIndex = this.readUInt16(this.offset);
table.usLastCharIndex = this.readUInt16(this.offset);
table.sTypoAscender = this.readInt16(this.offset);
table.sTypoDescender = this.readInt16(this.offset);
table.sTypoLineGap = this.readInt16(this.offset);
table.usWinAscent = this.readUInt16(this.offset);
table.usWinDescent = this.readUInt16(this.offset);
table.ulCodePageRange1 = this.readUInt32(this.offset);
table.ulCodePageRange2 = this.readUInt32(this.offset);
if (table.version > 1) {
table.sxHeight = this.readInt16(this.offset);
table.sCapHeight = this.readInt16(this.offset);
table.usDefaultChar = this.readUInt16(this.offset);
table.usBreakChar = this.readUInt16(this.offset);
table.usMaxContext = this.readUInt16(this.offset);
} else {
table.sxHeight = 0;
table.sCapHeight = 0;
table.usDefaultChar = 0;
table.usBreakChar = 0;
table.usMaxContext = 0;
}
return table;
}
private readPostTable() : TtfPostTable {
let tableInfo : TtfTableInfo = this.getTable('post');
this.offset = tableInfo.offset;
let table : TtfPostTable = new TtfPostTable();
table.formatType = this.readFixed(this.offset);
table.italicAngle = this.readFixed(this.offset);
table.underlinePosition = this.readInt16(this.offset);
table.underlineThickness = this.readInt16(this.offset);
table.isFixedPitch = this.readUInt32(this.offset);
table.minType42 = this.readUInt32(this.offset);
table.maxType42 = this.readUInt32(this.offset);
table.minType1 = this.readUInt32(this.offset);
table.maxType1 = this.readUInt32(this.offset);
return table;
}
/**
* Reads Width of the glyphs.
*/
private readWidthTable(glyphCount : number, unitsPerEm : number) : number[] {
let tableInfo : TtfTableInfo = this.getTable('hmtx');
this.offset = tableInfo.offset;
let width : number[] = [];
for (let i : number = 0; i < glyphCount; i++) {
let glyph : TtfLongHorMetric = new TtfLongHorMetric();
glyph.advanceWidth = this.readUInt16(this.offset);
glyph.lsb = this.readInt16(this.offset);
let glyphWidth : number = glyph.advanceWidth * 1000 / unitsPerEm;
width.push(Math.floor(glyphWidth));
}
return width;
}
/**
* Reads the cmap table.
*/
private readCmapTable() : TtfCmapSubTable[] {
let tableInfo : TtfTableInfo = this.getTable('cmap');
this.offset = tableInfo.offset;
let table : TtfCmapTable = new TtfCmapTable();
table.version = this.readUInt16(this.offset);
table.tablesCount = this.readUInt16(this.offset);
let position : number = this.offset;
let subTables : TtfCmapSubTable[] = [];
for (let i : number = 0; i < table.tablesCount; i++) {
this.offset = position;
let subTable : TtfCmapSubTable = new TtfCmapSubTable();
subTable.platformID = this.readUInt16(this.offset);
subTable.encodingID = this.readUInt16(this.offset);
subTable.offset = this.readUInt32(this.offset);
position = this.offset;
this.readCmapSubTable(subTable);
subTables[i] = subTable;
}
return subTables;
}
/**
* Reads the cmap sub table.
*/
private readCmapSubTable(subTable : TtfCmapSubTable) : void {
let tableInfo : TtfTableInfo = this.getTable('cmap');
this.offset = tableInfo.offset + subTable.offset;
let format : TtfCmapFormat = this.readUInt16(this.offset) as TtfCmapFormat;
let encoding : TtfCmapEncoding = this.getCmapEncoding(subTable.platformID, subTable.encodingID);
let platform : TtfPlatformID = (encoding === TtfCmapEncoding.Macintosh) ? TtfPlatformID.Macintosh : TtfPlatformID.Microsoft;
if (encoding !== TtfCmapEncoding.Unknown) {
switch (format) {
case TtfCmapFormat.Apple:
this.readAppleCmapTable(subTable, encoding);
break;
case TtfCmapFormat.Microsoft:
this.readMicrosoftCmapTable(subTable, encoding);
break;
case TtfCmapFormat.Trimmed:
this.readTrimmedCmapTable(subTable, encoding);
break;
}
}
}
/**
* Reads Symbol cmap table.
*/
private readAppleCmapTable(subTable : TtfCmapSubTable, encoding : TtfCmapEncoding) : void {
let tableInfo : TtfTableInfo = this.getTable('cmap');
this.offset = tableInfo.offset + subTable.offset;
let table : TtfAppleCmapSubTable = new TtfAppleCmapSubTable();
table.format = this.readUInt16(this.offset);
table.length = this.readUInt16(this.offset);
table.version = this.readUInt16(this.offset);
if (this.maxMacIndex === null || this.maxMacIndex === undefined) {
this.maxMacIndex = 0;
}
for (let i : number = 0; i < 256; ++i) {
let glyphInfo : TtfGlyphInfo = new TtfGlyphInfo();
glyphInfo.index = this.readByte(this.offset) as number;
glyphInfo.width = this.getWidth(glyphInfo.index);
glyphInfo.charCode = i;
this.macintosh.setValue(i, glyphInfo);
this.addGlyph(glyphInfo, encoding);
// NOTE: this code fixes char codes that extends 0x100. However, it might corrupt something.
this.maxMacIndex = Math.max(i, this.maxMacIndex);
}
}
/**
* Reads Symbol cmap table.
*/
private readMicrosoftCmapTable(subTable : TtfCmapSubTable, encoding : TtfCmapEncoding) : void {
let tableInfo : TtfTableInfo = this.getTable('cmap');
this.offset = tableInfo.offset + subTable.offset;
let collection : Dictionary<number, TtfGlyphInfo> = (encoding === TtfCmapEncoding.Unicode) ? this.microsoft : this.macintosh;
let table : TtfMicrosoftCmapSubTable = new TtfMicrosoftCmapSubTable();
table.format = this.readUInt16(this.offset);
table.length = this.readUInt16(this.offset);
table.version = this.readUInt16(this.offset);
table.segCountX2 = this.readUInt16(this.offset);
table.searchRange = this.readUInt16(this.offset);
table.entrySelector = this.readUInt16(this.offset);
table.rangeShift = this.readUInt16(this.offset);
let segCount : number = table.segCountX2 / 2;
table.endCount = this.readUshortArray(segCount);
table.reservedPad = this.readUInt16(this.offset);
table.startCount = this.readUshortArray(segCount);
table.idDelta = this.readUshortArray(segCount);
table.idRangeOffset = this.readUshortArray(segCount);
let length : number = (table.length / 2 - 8) - (segCount * 4);
table.glyphID = this.readUshortArray(length);
// Process glyphIdArray array.
let codeOffset : number = 0;
let index : number = 0;
for (let j : number = 0; j < segCount; j++) {
for (let k : number = table.startCount[j]; k <= table.endCount[j] && k !== 65535; k++) {
if (table.idRangeOffset[j] === 0) {
codeOffset = (k + table.idDelta[j]) & 65535;
} else {
index = j + table.idRangeOffset[j] / 2 - segCount + k - table.startCount[j];
if (index >= table.glyphID.length) {
continue;
}
codeOffset = (table.glyphID[index] + table.idDelta[j]) & 65535;
}
let glyph : TtfGlyphInfo = new TtfGlyphInfo();
glyph.index = codeOffset;
glyph.width = this.getWidth(glyph.index);
let id : number = (encoding === TtfCmapEncoding.Symbol) ? ((k & 0xff00) === 0xf000 ? k & 0xff : k) : k;
glyph.charCode = id;
collection.setValue(id, glyph);
this.addGlyph(glyph, encoding);
}
}
}
/**
* Reads Trimed cmap table.
*/
private readTrimmedCmapTable(subTable : TtfCmapSubTable, encoding : TtfCmapEncoding) : void {
let tableInfo : TtfTableInfo = this.getTable('cmap');
this.offset = tableInfo.offset + subTable.offset;
let table : TtfTrimmedCmapSubTable = new TtfTrimmedCmapSubTable();
table.format = this.readUInt16(this.offset);
table.length = this.readUInt16(this.offset);
table.version = this.readUInt16(this.offset);
table.firstCode = this.readUInt16(this.offset);
table.entryCount = this.readUInt16(this.offset);
for (let i : number = 0; i < table.entryCount; ++i) {
let glyphInfo : TtfGlyphInfo = new TtfGlyphInfo();
glyphInfo.index = this.readUInt16(this.offset);
glyphInfo.width = this.getWidth(glyphInfo.index);
glyphInfo.charCode = i + table.firstCode;
this.macintosh.setValue(i, glyphInfo);
this.addGlyph(glyphInfo, encoding);
// NOTE: this code fixes char codes that extends 0x100. However, it might corrupt something.
this.maxMacIndex = Math.max(i, this.maxMacIndex);
}
}
private initializeFontName(nameTable : TtfNameTable) : void {
for (let i : number = 0; i < nameTable.recordsCount; i++) {
let record : TtfNameRecord = nameTable.nameRecords[i];
if (record.nameID === 1) {
//font family
this.metrics.fontFamily = record.name;
} else if (record.nameID === 6) {
//post script name
this.metrics.postScriptName = record.name;
}
/* tslint:disable */
if (this.metrics.fontFamily !== null && this.metrics.fontFamily !== undefined && this.metrics.postScriptName !== null && this.metrics.postScriptName !== undefined) {
break;
}
/* tslint:disable */
}
}
private getTable(name : string) : TtfTableInfo {
// if (name === null) {
// throw new Error('Argument Null Exception : name');
// }
let table : TtfTableInfo = new TtfTableInfo();
let obj : TtfTableInfo;
if (this.tableDirectory.containsKey(name)) {
obj = this.tableDirectory.getValue(name);
}
if (obj !== null && obj !== undefined) {
table = obj as TtfTableInfo;
}
return table;
}
/**
* Returns width of the glyph.
*/
private getWidth(glyphCode : number) : number {
glyphCode = (glyphCode < this.width.length) ? glyphCode : this.width.length - 1;
return this.width[glyphCode];
}
/**
* Gets CMAP encoding based on platform ID and encoding ID.
*/
/* tslint:disable */
private getCmapEncoding(platformID : number, encodingID : number) : TtfCmapEncoding {
let format : TtfCmapEncoding = TtfCmapEncoding.Unknown;
if (platformID == (TtfPlatformID.Microsoft as number) && encodingID == (TtfMicrosoftEncodingID.Undefined as number)) {
// When building a symbol font for Windows,
// the platform ID should be 3 and the encoding ID should be 0.
format = TtfCmapEncoding.Symbol;
} else if (platformID == (TtfPlatformID.Microsoft as number) && encodingID == (TtfMicrosoftEncodingID.Unicode as number)) {
// When building a Unicode font for Windows,
// the platform ID should be 3 and the encoding ID should be 1.
format = TtfCmapEncoding.Unicode;
} else if (platformID == (TtfPlatformID.Macintosh as number) && encodingID == (TtfMacintoshEncodingID.Roman as number)) {
// When building a font that will be used on the Macintosh,
// the platform ID should be 1 and the encoding ID should be 0.
format = TtfCmapEncoding.Macintosh;
}
return format;
}
/* tslint:enable */
/**
* Adds glyph to the collection.
*/
private addGlyph(glyph : TtfGlyphInfo, encoding : TtfCmapEncoding) : void {
let collection : Dictionary<number, TtfGlyphInfo> = null;
switch (encoding) {
case TtfCmapEncoding.Unicode:
collection = this.microsoftGlyphs;
break;
case TtfCmapEncoding.Macintosh:
case TtfCmapEncoding.Symbol:
collection = this.macintoshGlyphs;
break;
}
collection.setValue(glyph.index, glyph);
}
/**
* Initializes metrics.
*/
/* tslint:disable */
private initializeMetrics(nameTable : TtfNameTable, headTable : TtfHeadTable, horizontalHeadTable : TtfHorizontalHeaderTable, os2Table : TtfOS2Table, postTable : TtfPostTable, cmapTables : TtfCmapSubTable[]) : void {
/* tslint:enable */
// if (cmapTables === null) {
// throw new Error('ArgumentNullException : cmapTables');
// }
this.initializeFontName(nameTable);
// Get font encoding.
let bSymbol : boolean = false;
for (let i : number = 0; i < cmapTables.length; i++) {
let subTable : TtfCmapSubTable = cmapTables[i];
let encoding : TtfCmapEncoding = this.getCmapEncoding(subTable.platformID, subTable.encodingID);
if (encoding === TtfCmapEncoding.Symbol) {
bSymbol = true;
break;
}
}
this.metrics.isSymbol = bSymbol;
this.metrics.macStyle = headTable.macStyle;
this.metrics.isFixedPitch = (postTable.isFixedPitch !== 0);
this.metrics.italicAngle = postTable.italicAngle;
let factor : number = 1000 / headTable.unitsPerEm;
this.metrics.winAscent = os2Table.sTypoAscender * factor;
this.metrics.macAscent = horizontalHeadTable.ascender * factor;
//m_metrics.MacAscent = os2Table.UsWinAscent * factor;
// NOTE: This is stange workaround. The value is good if os2Table.SCapHeight != 0, otherwise it should be properly computed.
this.metrics.capHeight = (os2Table.sCapHeight !== 0) ? os2Table.sCapHeight : 0.7 * headTable.unitsPerEm * factor;
this.metrics.winDescent = os2Table.sTypoDescender * factor;
this.metrics.macDescent = horizontalHeadTable.descender * factor;
//m_metrics.MacDescent = -os2Table.UsWinDescent * factor;
this.metrics.leading = (os2Table.sTypoAscender - os2Table.sTypoDescender + os2Table.sTypoLineGap) * factor;
this.metrics.lineGap = Math.ceil(horizontalHeadTable.lineGap * factor);
let left : number = headTable.xMin * factor;
let top : number = Math.ceil(this.metrics.macAscent + this.metrics.lineGap);
let right : number = headTable.xMax * factor;
let bottom : number = this.metrics.macDescent;
this.metrics.fontBox = new Rectangle(left, top, right, bottom);
// NOTE: Strange!
this.metrics.stemV = 80;
this.metrics.widthTable = this.updateWidth();
this.metrics.contains = this.tableDirectory.containsKey('CFF');
this.metrics.subScriptSizeFactor = headTable.unitsPerEm / os2Table.ySubscriptYSize;
this.metrics.superscriptSizeFactor = headTable.unitsPerEm / os2Table.ySuperscriptYSize;
}
/**
* Updates chars structure which is used in the case of ansi encoding (256 bytes).
*/
private updateWidth() : number[] {
let count : number = 256;
let bytes : number[] = [];
if (this.metrics.isSymbol) {
for (let i : number = 0; i < count; i++) {
let glyphInfo : TtfGlyphInfo = this.getGlyph(String.fromCharCode(i));
bytes[i] = (glyphInfo.empty) ? 0 : glyphInfo.width;
}
} else {
let byteToProcess : number[] = [];
let unknown : string = '?';
let space : string = String.fromCharCode(32);
for (let i : number = 0; i < count; i++) {
byteToProcess[0] = i;
let text : string = this.getString(byteToProcess, 0, byteToProcess.length);
let ch : string = (text.length > 0) ? text[0] : unknown;
let glyphInfo : TtfGlyphInfo = this.getGlyph(ch);
if (!glyphInfo.empty) {
bytes[i] = glyphInfo.width;
} else {
glyphInfo = this.getGlyph(space);
bytes[i] = (glyphInfo.empty) ? 0 : glyphInfo.width;
}
}
}
return bytes;
}
/**
* Returns default glyph.
*/
private getDefaultGlyph() : TtfGlyphInfo {
let glyph : TtfGlyphInfo = this.getGlyph(StringTokenizer.whiteSpace);
return glyph;
}
/**
* Reads unicode string from byte array.
*/
private getString(byteToProcess : number[], start : number, length : number) : string {
let result : string = '';
for (let index : number = 0; index < length; index++) {
result += String.fromCharCode(byteToProcess[index + start]);
}
return result;
}
/**
* Reads loca table.
*/
private readLocaTable(bShort : boolean) : TtfLocaTable {
let tableInfo : TtfTableInfo = this.getTable('loca');
this.offset = tableInfo.offset;
let table : TtfLocaTable = new TtfLocaTable();
let buffer : number[] = null;
if (bShort) {
let len : number = tableInfo.length / 2;
buffer = [];
for (let i : number = 0; i < len; i++) {
buffer[i] = this.readUInt16(this.offset) * 2;
}
} else {
let len : number = tableInfo.length / 4;
buffer = [];
for (let i : number = 0; i < len; i++) {
buffer[i] = this.readUInt32(this.offset);
}
}
table.offsets = buffer;
return table;
}
/**
* Updates hash table of used glyphs.
*/
private updateGlyphChars(glyphChars : Dictionary<number, number>, locaTable : TtfLocaTable) : void {
// if (glyphChars === null) {
// throw new Error('Argument Null Exception : glyphChars');
// }
// Add zero key.
if (!glyphChars.containsKey(0)) {
glyphChars.setValue(0, 0);
}
let clone : Dictionary<number, number> = new Dictionary<number, number>();
let glyphCharKeys : number[] = glyphChars.keys();
for (let i : number = 0; i < glyphCharKeys.length; i++) {
clone.setValue(glyphCharKeys[i], glyphChars.getValue(glyphCharKeys[i]));
}
for (let i : number = 0; i < glyphCharKeys.length; i++) {
let nextKey : number = glyphCharKeys[i];
this.processCompositeGlyph(glyphChars, nextKey, locaTable);
}
}
/**
* Checks if glyph is composite or not.
*/
private processCompositeGlyph(glyphChars : Dictionary<number, number>, glyph : number, locaTable : TtfLocaTable) : void {
// if (glyphChars === null) {
// throw new Error('Argument Null Exception : glyphChars');
// }
// Is in range.
if (glyph < locaTable.offsets.length - 1) {
let glyphOffset : number = locaTable.offsets[glyph];
if (glyphOffset !== locaTable.offsets[glyph + 1]) {
let tableInfo : TtfTableInfo = this.getTable('glyf');
this.offset = tableInfo.offset + glyphOffset;
let glyphHeader : TtfGlyphHeader = new TtfGlyphHeader();
glyphHeader.numberOfContours = this.readInt16(this.offset);
glyphHeader.xMin = this.readInt16(this.offset);
glyphHeader.yMin = this.readInt16(this.offset);
glyphHeader.xMax = this.readInt16(this.offset);
glyphHeader.yMax = this.readInt16(this.offset);
// Glyph is composite.
if (glyphHeader.numberOfContours < 0) {
let skipBytes : number = 0;
let entry : boolean = true;
while (entry) {
let flags : number = this.readUInt16(this.offset);
let glyphIndex : number = this.readUInt16(this.offset);
if (!glyphChars.containsKey(glyphIndex)) {
glyphChars.setValue(glyphIndex, 0);
}
if ((flags & TtfCompositeGlyphFlags.MoreComponents) === 0) {
break;
}
skipBytes = ((flags & TtfCompositeGlyphFlags.Arg1And2AreWords) !== 0) ? 4 : 2;
if ((flags & TtfCompositeGlyphFlags.WeHaveScale) !== 0) {
skipBytes += 2;
} else if ((flags & TtfCompositeGlyphFlags.WeHaveAnXyScale) !== 0) {
skipBytes += 4;
} else if ((flags & TtfCompositeGlyphFlags.WeHaveTwoByTwo) !== 0) {
skipBytes += 2 * 4;
}
this.offset += skipBytes;
}
}
}
}
}
/**
* Creates new glyph tables based on chars that are used for output.
*/
/* tslint:disable */
private generateGlyphTable(glyphChars : Dictionary<number, number>, locaTable : TtfLocaTable, newLocaTable : number[], newGlyphTable : number[]) : { glyphTableSize : number, newLocaTable : number[], newGlyphTable : number[] } {
/* tslint:enable */
// if (glyphChars === null) {
// throw new Error('Argument Null Exception : glyphChars');
// }
newLocaTable = [];
// Sorting used glyphs keys.
let activeGlyphs : number[] = glyphChars.keys();
activeGlyphs.sort((a : number, b : number) => a - b);
let glyphSize : number = 0;
for (let i : number = 0; i < activeGlyphs.length; i++) {
let glyphIndex : number = activeGlyphs[i];
if (locaTable.offsets.length > 0) {
glyphSize += locaTable.offsets[glyphIndex + 1] - locaTable.offsets[glyphIndex];
}
}
let glyphSizeAligned : number = this.align(glyphSize);
newGlyphTable = [];
for (let i : number = 0; i < glyphSizeAligned; i++) {
newGlyphTable.push(0);
}
let nextGlyphOffset : number = 0;
let nextGlyphIndex : number = 0;
let table : TtfTableInfo = this.getTable('glyf');
// Creating NewLocaTable - that would hold offsets for filtered glyphs.
for (let i : number = 0; i < locaTable.offsets.length; i++) {
newLocaTable.push(nextGlyphOffset);
if (nextGlyphIndex < activeGlyphs.length && activeGlyphs[nextGlyphIndex] === i) {
++nextGlyphIndex;
newLocaTable[i] = nextGlyphOffset;
let oldGlyphOffset : number = locaTable.offsets[i];
let oldNextGlyphOffset : number = locaTable.offsets[i + 1] - oldGlyphOffset;
if (oldNextGlyphOffset > 0) {
this.offset = table.offset + oldGlyphOffset;
let result : { buffer : number[], written : number } = this.read(newGlyphTable, nextGlyphOffset, oldNextGlyphOffset);
newGlyphTable = result.buffer;
nextGlyphOffset += oldNextGlyphOffset;
}
}
}
return { glyphTableSize : glyphSize, newLocaTable : newLocaTable, newGlyphTable : newGlyphTable };
}
/**
* Updates new Loca table.
*/
/* tslint:disable */
private updateLocaTable(newLocaTable : number[], bLocaIsShort : boolean, newLocaTableOut : number[]) : { newLocaUpdated : number[], newLocaSize : number } {
/* tslint:enable */
if (newLocaTable === null) {
throw new Error('Argument Null Exception : newLocaTable');
}
let size : number = (bLocaIsShort) ? newLocaTable.length * 2 : newLocaTable.length * 4;
let count : number = this.align(size);
//BigEndianWiter
let writer : BigEndianWriter = new BigEndianWriter(count);
for (let i : number = 0; i < newLocaTable.length; i++) {
let value : number = newLocaTable[i];
if (bLocaIsShort) {
value /= 2;
writer.writeShort(value);
} else {
writer.writeInt(value);
}
}
return { newLocaUpdated : writer.data, newLocaSize : size };
}
/**
* Aligns number to be divisible on 4.
*/
private align(value : number) : number {
return (value + 3) & (~3);
}
/**
* Returns font program data.
*/
/* tslint:disable */
private getFontProgram(newLocaTableOut : number[], newGlyphTable : number[], glyphTableSize : number, locaTableSize : number) : number[] {
/* tslint:enable */
if (newLocaTableOut === null) {
throw new Error('Argument Null Exception : newLocaTableOut');
}
if (newGlyphTable === null) {
throw new Error('Argument Null Exception : newGlyphTable');
}
let tableNames : string[] = this.tableNames;
let result : {fontProgramLength : number, numTables : number} = this.getFontProgramLength(newLocaTableOut, newGlyphTable, 0);
let fontProgramLength : number = result.fontProgramLength;
let numTables : number = result.numTables;
let writer : BigEndianWriter = new BigEndianWriter(fontProgramLength);
writer.writeInt(0x10000);
writer.writeShort(numTables);
let entrySelector : number = this.entrySelectors[numTables];
writer.writeShort((1 << (entrySelector & 31)) * 16);
writer.writeShort(entrySelector);
writer.writeShort((numTables - (1 << (entrySelector & 31))) * 16);
// Writing to destination buffer - checksums && sizes of used tables.
this.writeCheckSums(writer, numTables, newLocaTableOut, newGlyphTable, glyphTableSize, locaTableSize);
// // Writing to destination buffer - used glyphs.
this.writeGlyphs(writer, newLocaTableOut, newGlyphTable);
return writer.data;
}
/* tslint:disable */
private getFontProgramLength(newLocaTableOut : number[], newGlyphTable : number[], numTables : number) : {fontProgramLength : number, numTables : number} {
/* tslint:enable */
if (newLocaTableOut === null) {
throw new Error('Argument Null Exception : newLocaTableOut');
}
if (newGlyphTable === null) {
throw new Error('Argument Null Exception : newGlyphTable');
}
// glyf and loca are used by default;
numTables = 2;
let tableNames : string[] = this.tableNames;
let fontProgramLength : number = 0;
for (let i : number = 0; i < tableNames.length; i++) {
let tableName : string = tableNames[i];
if (tableName !== 'glyf' && tableName !== 'loca') {
let table : TtfTableInfo = this.getTable(tableName);
if (!table.empty) {
++numTables;
fontProgramLength += this.align(table.length);
}
}
}
fontProgramLength += newLocaTableOut.length;
fontProgramLength += newGlyphTable.length;
let usedTablesSize : number = numTables * 16 + (3 * 4);
fontProgramLength += usedTablesSize;
return { fontProgramLength : fontProgramLength, numTables : numTables};
}
/**
* Writing to destination buffer - checksums and sizes of used tables.
*/
/* tslint:disable */
private writeCheckSums(writer : BigEndianWriter, numTables : number, newLocaTableOut : number[], newGlyphTable : number[], glyphTableSize : number, locaTableSize : number) : void {
/* tslint:enable */
if (writer === null) {
throw new Error('Argument Null Exception : writer');
}
if (newLocaTableOut === null) {
throw new Error('Argument Null Exception : newLocaTableOut');
}
if (newGlyphTable === null) {
throw new Error('Argument Null Exception : newGlyphTable');
}
let tableNames : string[] = this.tableNames;
let usedTablesSize : number = numTables * 16 + (3 * 4);
let nextTableSize : number = 0;
for (let i : number = 0; i < tableNames.length; i++) {
let tableName : string = tableNames[i];
let tableInfo : TtfTableInfo = this.getTable(tableName);
if (tableInfo.empty) {
continue;
}
writer.writeString(tableName);
if (tableName === 'glyf') {
let checksum : number = this.calculateCheckSum(newGlyphTable);
writer.writeInt(checksum);
nextTableSize = glyphTableSize;
} else if (tableName === 'loca') {
let checksum : number = this.calculateCheckSum(newLocaTableOut);
writer.writeInt(checksum);
nextTableSize = locaTableSize;
} else {
writer.writeInt(tableInfo.checksum);
nextTableSize = tableInfo.length;
}
writer.writeUInt(usedTablesSize);
writer.writeUInt(nextTableSize);
usedTablesSize += this.align(nextTableSize);
}
}
/**
* Gets checksum from source buffer.
*/
private calculateCheckSum(bytes : number[]) : number {
if (bytes === null) {
throw new Error('Argument Null Exception : bytes');
}
let pos : number = 0;
let byte1 : number = 0;
let byte2 : number = 0;
let byte3 : number = 0;
let byte4 : number = 0;
for (let i : number = 0; i < (bytes.length + 1) / 4; i++) {
byte4 += (bytes[pos++] & 255);
byte3 += (bytes[pos++] & 255);
byte2 += (bytes[pos++] & 255);
byte1 += (bytes[pos++] & 255);
}
let result : number = byte1;
result += (byte2 << 8);
result += (byte3 << 16);
result += (byte4 << 24);
return result;
}
/**
* Writing to destination buffer - used glyphs.
*/
private writeGlyphs(writer : BigEndianWriter, newLocaTable : number[], newGlyphTable : number[]) : void {
if (writer === null) {
throw new Error('Argument Null Exception : writer');
}
if (newLocaTable === null) {
throw new Error('Argument Null Exception : newLocaTableOut');
}
if (newGlyphTable === null) {
throw new Error('Argument Null Exception : newGlyphTable');
}
let tableNames : string[] = this.tableNames;
for (let i : number = 0; i < tableNames.length; i++) {
let tableName : string = tableNames[i];
let tableInfo : TtfTableInfo = this.getTable(tableName);
if (tableInfo.empty) {
continue;
}
if (tableName === 'glyf') {
writer.writeBytes(newGlyphTable);
} else if (tableName === 'loca') {
writer.writeBytes(newLocaTable);
} else {
let count : number = this.align(tableInfo.length);
let buff : number[] = [];
for (let i : number = 0; i < count; i++) {
buff.push(0);
}
this.offset = tableInfo.offset;
let result : {buffer : number[], written : number} = this.read(buff, 0, tableInfo.length);
writer.writeBytes(result.buffer);
}
}
}
//public methods
/**
* Sets position value of font data.
*/
public setOffset(offset : number) : void {
this.offset = offset;
}
/**
* Creates font Internals
* @private
*/
public createInternals() : void {
this.metrics = new TtfMetrics();
let nameTable : TtfNameTable = this.readNameTable();
let headTable : TtfHeadTable = this.readHeadTable();
this.bIsLocaShort = (headTable.indexToLocalFormat === 0);
let horizontalHeadTable : TtfHorizontalHeaderTable = this.readHorizontalHeaderTable();
let os2Table : TtfOS2Table = this.readOS2Table();
let postTable : TtfPostTable = this.readPostTable();
this.width = this.readWidthTable(horizontalHeadTable.numberOfHMetrics, headTable.unitsPerEm);
let subTables : TtfCmapSubTable[] = this.readCmapTable();
this.initializeMetrics(nameTable, headTable, horizontalHeadTable, os2Table, postTable, subTables);
}
/**
* Gets glyph's info by char code.
*/
public getGlyph(charCode : string ) : TtfGlyphInfo
public getGlyph(charCode : number ) : TtfGlyphInfo
public getGlyph(charCode ?: string | number) : TtfGlyphInfo {
if (typeof charCode === 'number') {
let obj1 : object = null;
if (!this.metrics.isSymbol && this.microsoftGlyphs != null) {
if (this.microsoftGlyphs.containsKey(charCode)) {
obj1 = this.microsoftGlyphs.getValue(charCode);
}
} else if (this.metrics.isSymbol && this.macintoshGlyphs != null) {
if (this.macintoshGlyphs.containsKey(charCode)) {
obj1 = this.macintoshGlyphs.getValue(charCode);
}
}
let glyph : TtfGlyphInfo = (obj1 != null) ? obj1 as TtfGlyphInfo : this.getDefaultGlyph();
return glyph;
} else {
let obj : object = null;
let code : number = charCode.charCodeAt(0);
if (!this.metrics.isSymbol && this.microsoft !== null) {
if (this.microsoft.containsKey(code)) {
obj = this.microsoft.getValue(code);
if (code !== StringTokenizer.whiteSpace.charCodeAt(0)) {
this.isFontPresent = true;
}
} else if (code !== StringTokenizer.whiteSpace.charCodeAt(0)) {
this.isFontPresent = false;
}
} else if (this.metrics.isSymbol && this.macintosh !== null || this.isMacTTF) {
// NOTE: this code fixes char codes that extends 0x100. However, it might corrupt something.
if (this.maxMacIndex !== 0) {
code %= this.maxMacIndex + 1;
} else {
code = ((code & 0xff00) === 0xf000 ? code & 0xff : code);
}
if (this.macintosh.containsKey(code)) {
obj = this.macintosh.getValue(code);
this.isFontPresent = true;
}
}
// Fix for StackOverFlow exception in XPS to PDF converter
if (charCode === StringTokenizer.whiteSpace && obj === null) {
obj = new TtfGlyphInfo();
}
let glyph : TtfGlyphInfo = (obj !== null) ? obj as TtfGlyphInfo : this.getDefaultGlyph();
return glyph;
}
}
/**
* Gets hash table with chars indexed by glyph index.
*/
public getGlyphChars(chars : Dictionary<string, string>) : Dictionary<number, number> {
if (chars === null || chars === undefined) {
throw new Error('Argument Null Exception : chars');
}
let dictionary : Dictionary<number, number> = new Dictionary<number, number>();
let charKeys : string[] = chars.keys();
for (let i : number = 0; i < charKeys.length; i++) {
let ch : string = charKeys[i];
let glyph : TtfGlyphInfo = this.getGlyph(ch);
if (!glyph.empty) {
dictionary.setValue(glyph.index, ch.charCodeAt(0));
}
}
return dictionary;
}
/**
* Gets all glyphs.
*/
public getAllGlyphs() : TtfGlyphInfo[] {
let allGlyphInfo : TtfGlyphInfo[] = [];
let info : TtfGlyphInfo = new TtfGlyphInfo();
let index : number = 0;
for (let i : number = 0; i < this.width.length; i++) {
let width : number = this.width[i];
info.index = index;
info.width = width;
allGlyphInfo.push(info);
index++;
}
return allGlyphInfo;
}
/**
* Reads a font's program.
* @private
*/
public readFontProgram(chars : Dictionary<string, string>) : number[] {
let glyphChars : Dictionary<number, number> = this.getGlyphChars(chars);
let locaTable : TtfLocaTable = this.readLocaTable(this.bIsLocaShort);
if (glyphChars.size() < chars.size()) {
this.missedGlyphs = chars.size() - glyphChars.size();
}
this.updateGlyphChars(glyphChars, locaTable);
/* tslint:disable */
let result1 : { glyphTableSize : number, newLocaTable : number[], newGlyphTable : number[] } = this.generateGlyphTable(glyphChars, locaTable, null, null);
/* tslint:enable */
let glyphTableSize : number = result1.glyphTableSize;
let newLocaTable : number[] = result1.newLocaTable;
let newGlyphTable : number[] = result1.newGlyphTable;
let result2 : { newLocaUpdated : number[], newLocaSize : number } = this.updateLocaTable(newLocaTable, this.bIsLocaShort, null);
let newLocaSize : number = result2.newLocaSize;
let newLocaUpdated : number[] = result2.newLocaUpdated;
let fontProgram : number[] = this.getFontProgram(newLocaUpdated, newGlyphTable, glyphTableSize, newLocaSize);
return fontProgram;
}
/**
* Reconverts string to be in proper format saved into PDF file.
*/
public convertString(text : string) : string {
if (text === null) {
throw new Error('Argument Null Exception : text');
}
let glyph : string = '';
let i : number = 0;
for (let k : number = 0; k < text.length; k++) {
let ch : string = text[k];
let glyphInfo : TtfGlyphInfo = this.getGlyph(ch);
if (!glyphInfo.empty) {
glyph += String.fromCharCode(glyphInfo.index);
i++;
}
}
return glyph;
}
/**
* Gets char width.
*/
public getCharWidth(code : string) : number {
let glyphInfo : TtfGlyphInfo = this.getGlyph(code);
glyphInfo = (!glyphInfo.empty) ? glyphInfo : this.getDefaultGlyph();
let codeWidth : number = (!glyphInfo.empty) ? glyphInfo.width : 0;
return codeWidth;
}
//Stream reader
private readString(length : number) : string
private readString(length : number, isUnicode : boolean) : string
private readString(length : number, isUnicode ?: boolean) : string {
if (isUnicode === undefined) {
return this.readString(length, false);
} else {
//let buffer : number[] = this.readBytes(length);
let result : string = '';
if (isUnicode) {
for (let i : number = 0; i < length; i++) {
if (i % 2 !== 0) {
result += String.fromCharCode(this.fontData[this.offset]);
}
this.offset += 1;
}
} else {
for (let i : number = 0; i < length; i++) {
result += String.fromCharCode(this.fontData[this.offset]);
this.offset += 1;
}
}
return result;
}
}
private readFixed(offset : number) : number {
let integer : number = this.readInt16(offset);
let sFraction : number = this.readInt16(offset + 2);
let fraction : number = sFraction / 16384;
return integer + fraction;
}
private readInt32(offset : number) : number {
let i1 : number = this.fontData[offset + 3];
let i2 : number = this.fontData[offset + 2];
let i3 : number = this.fontData[offset + 1];
let i4 : number = this.fontData[offset];
this.offset += 4;
return i1 + (i2 << 8) + (i3 << 16) + (i4 << 24);
}
private readUInt32(offset : number) : number {
let i1 : number = this.fontData[offset + 3];
let i2 : number = this.fontData[offset + 2];
let i3 : number = this.fontData[offset + 1];
let i4 : number = this.fontData[offset];
this.offset += 4;
return (i1 | i2 << 8 | i3 << 16 | i4 << 24);
}
// private readInt16(offset : number) : number {
// let result : number = (this.fontData[offset] << 8) + this.fontData[offset + 1];
// this.offset += 2;
// return result;
// }
private readInt16(offset : number) : number {
let result : number = (this.fontData[offset] << 8) + this.fontData[offset + 1];
result = result & (1 << 15) ? result - 0x10000 : result;
this.offset += 2;
return result;
}
private readInt64(offset : number) : number {
let low : number = this.readInt32(offset + 4);
let n : number = this.readInt32(offset) * 4294967296.0 + low;
if (low < 0) {
n += 4294967296;
}
return n;
}
private readUInt16(offset : number) : number {
let result : number = (this.fontData[offset] << 8) | this.fontData[offset + 1];
this.offset += 2;
return result;
}
/**
* Reads ushort array.
*/
private readUshortArray(length : number) : number[] {
let buffer : number[] = [];
for (let i : number = 0; i < length; i++) {
buffer[i] = this.readUInt16(this.offset);
}
return buffer;
}
private readBytes(length : number) : number[] {
let result : number[] = [];
for (let i : number = 0; i < length; i++) {
result.push(this.fontData[this.offset]);
this.offset += 1;
}
return result;
}
private readByte(offset : number) : number {
let result : number = this.fontData[offset];
this.offset += 1;
return result;
}
/**
* Reads bytes to array in BigEndian order.
* @private
*/
public read(buffer : number[], index : number, count : number) : { buffer : number[], written : number } {
if (buffer === null) {
throw new Error('Argument Null Exception : buffer');
}
let written : number = 0;
let read : number = 0;
do {
for (let i : number = 0; (i < count - written) && (this.offset + i < this.fontData.length); i++) {
buffer[index + i] = this.fontData[this.offset + i];
}
read = count - written;
this.offset += read;
written += read;
} while (written < count);
return { buffer : buffer, written : written };
}
} | the_stack |
import { Component, OnInit, OnDestroy, Input, Output, ViewChild, EventEmitter } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { CustomValidators } from './../../shared/validation/validators';
import { CategoryVO, AttrValueCategoryVO, ProductTypeInfoVO, Pair, CategoryNavigationPriceTiersVO, CategoryNavigationPriceTierVO, ValidationRequestVO } from './../../shared/model/index';
import { FormValidationEvent, Futures, Future } from './../../shared/event/index';
import { Util } from './../../shared/services/index';
import { UiUtil } from './../../shared/ui/index';
import { CategoryMinSelectComponent, ProductTypeSelectComponent } from './../../shared/catalog/index';
import { AttributeValuesComponent } from './../../shared/attributes/index';
import { ModalComponent, ModalAction, ModalResult } from './../../shared/modal/index';
import { LogUtil } from './../../shared/log/index';
@Component({
selector: 'cw-category',
templateUrl: 'category.component.html',
})
export class CategoryComponent implements OnInit, OnDestroy {
@Output() dataChanged: EventEmitter<FormValidationEvent<Pair<CategoryVO, Array<Pair<AttrValueCategoryVO, boolean>>>>> = new EventEmitter<FormValidationEvent<Pair<CategoryVO, Array<Pair<AttrValueCategoryVO, boolean>>>>>();
private _category:CategoryVO;
private _attributes:AttrValueCategoryVO[] = [];
public attributeFilter:string;
public attributeSort:Pair<string, boolean> = { first: 'name', second: false };
public navigationByPriceTiers:CategoryNavigationPriceTiersVO;
public navigationByPriceTiersAddCurrency:string;
private _changes:Array<Pair<AttrValueCategoryVO, boolean>>;
public selectedRow:AttrValueCategoryVO;
public imageOnlyMode:boolean = false;
public delayedChange:Future;
public categoryForm:any;
@ViewChild('attributeValuesComponent')
private attributeValuesComponent:AttributeValuesComponent;
@ViewChild('categoryParentSelectComponent')
private categoryParentSelectComponent:CategoryMinSelectComponent;
@ViewChild('categoryProductTypeSelectComponent')
private categoryProductTypeSelectComponent:ProductTypeSelectComponent;
@ViewChild('categoryPriceTiersModalDialog')
private categoryPriceTiersModalDialog:ModalComponent;
public searchHelpShow:boolean = false;
constructor(fb: FormBuilder) {
LogUtil.debug('CategoryComponent constructed');
let that = this;
let validUri = function(control:any):any {
let uri = control.value;
if (uri == null || uri == '' || that._category == null || !that.categoryForm || (!that.categoryForm.dirty && that._category.categoryId > 0)) {
return null;
}
let basic = CustomValidators.validSeoUri255(control);
if (basic == null) {
let req:ValidationRequestVO = { subject: 'category', subjectId: that._category.categoryId, field: 'uri', value: uri };
return CustomValidators.validRemoteCheck(control, req);
}
return basic;
};
let validCode = function(control:any):any {
let code = control.value;
if (code == null || code == '' || that._category == null|| !that.categoryForm || (!that.categoryForm.dirty && that._category.categoryId > 0)) {
return null;
}
let basic = CustomValidators.validCode36(control);
if (basic == null) {
let req:ValidationRequestVO = { subject: 'category', subjectId: that._category.categoryId, field: 'guid', value: code };
return CustomValidators.validRemoteCheck(control, req);
}
return basic;
};
this.categoryForm = fb.group({
'guid': ['', validCode],
'parentName': ['', Validators.required],
'linkToName': [''],
'description': [''],
'rank': ['', CustomValidators.requiredRank],
'uitemplate': ['', CustomValidators.nonBlankTrimmed],
'disabled': [''],
'availablefrom': [''],
'availableto': [''],
'uri': ['', validUri],
'navigationByAttributes': [''],
'navigationByPrice': [''],
'productTypeName': [''],
'name': [''],
'title': [''],
'keywords': [''],
'meta': [''],
});
this.delayedChange = Futures.perpetual(function() {
that.formChange();
}, 200);
}
formBind():void {
UiUtil.formBind(this, 'categoryForm', 'delayedChange');
}
formUnbind():void {
UiUtil.formUnbind(this, 'categoryForm');
}
formChange():void {
LogUtil.debug('CategoryComponent formChange', this.categoryForm.valid, this._category);
this.dataChanged.emit({ source: new Pair(this._category, this._changes), valid: (this._category.categoryId != 100 && this.categoryForm.valid) });
}
@Input()
set category(category:CategoryVO) {
UiUtil.formInitialise(this, 'categoryForm', '_category', category);
this._changes = [];
}
get category():CategoryVO {
return this._category;
}
onAvailableFrom(event:FormValidationEvent<any>) {
if (event.valid) {
this.category.availablefrom = event.source;
}
UiUtil.formDataChange(this, 'categoryForm', 'availablefrom', event);
}
onAvailableTo(event:FormValidationEvent<any>) {
if (event.valid) {
this.category.availableto = event.source;
}
UiUtil.formDataChange(this, 'categoryForm', 'availableto', event);
}
onNameDataChange(event:FormValidationEvent<any>) {
UiUtil.formI18nDataChange(this, 'categoryForm', 'name', event);
}
onTitleDataChange(event:FormValidationEvent<any>) {
UiUtil.formI18nDataChange(this, 'categoryForm', 'title', event);
}
onKeywordsDataChange(event:FormValidationEvent<any>) {
UiUtil.formI18nDataChange(this, 'categoryForm', 'keywords', event);
}
onMetaDataChange(event:FormValidationEvent<any>) {
UiUtil.formI18nDataChange(this, 'categoryForm', 'meta', event);
}
@Input()
set attributes(attributes:AttrValueCategoryVO[]) {
this._attributes = attributes;
}
get attributes():AttrValueCategoryVO[] {
return this._attributes;
}
onAttributeDataChanged(event:any) {
LogUtil.debug('CategoryComponent attr data changed', this._category);
this._changes = event.source;
this.delayedChange.delay();
}
ngOnInit() {
LogUtil.debug('CategoryComponent ngOnInit');
this.formBind();
}
ngOnDestroy() {
LogUtil.debug('CategoryComponent ngOnDestroy');
this.formUnbind();
}
tabSelected(tab:any) {
LogUtil.debug('CategoryComponent tabSelected', tab);
}
onImageOnlyMode() {
this.imageOnlyMode = !this.imageOnlyMode;
}
onRowDeleteSelected() {
if (this.selectedRow != null) {
this.attributeValuesComponent.onRowDeleteSelected();
}
}
onRowEditSelected() {
if (this.selectedRow != null) {
this.attributeValuesComponent.onRowEditSelected();
}
}
onPageSelected(page:number) {
LogUtil.debug('CategoryComponent onPageSelected', page);
}
onSortSelected(sort:Pair<string, boolean>) {
LogUtil.debug('CategoryComponent ononSortSelected', sort);
if (sort == null) {
this.attributeSort = { first: 'name', second: false };
} else {
this.attributeSort = sort;
}
}
onSelectRow(row:AttrValueCategoryVO) {
LogUtil.debug('CategoryComponent onSelectRow handler', row);
if (row == this.selectedRow) {
this.selectedRow = null;
} else {
this.selectedRow = row;
}
}
onEditParent() {
LogUtil.debug('CategoryComponent onEditParent handler');
this.categoryParentSelectComponent.showDialog(this.category.parentId);
}
onCategoryParentSelected(event:FormValidationEvent<CategoryVO>) {
LogUtil.debug('CategoryComponent onCategoryParentSelected handler', event);
if (event.valid) {
this.category.parentId = event.source.categoryId;
this.category.parentName = event.source.name;
this.delayedChange.delay();
}
}
onClearProductType() {
LogUtil.debug('CategoryComponent onClearProductType handler');
if (this._category) {
this._category.productTypeId = 0;
this._category.productTypeName = null;
this.delayedChange.delay();
}
}
onEditProductType() {
LogUtil.debug('CategoryComponent onEditProductType handler');
this.categoryProductTypeSelectComponent.showDialog();
}
onCategoryProductTypeSelected(event:FormValidationEvent<ProductTypeInfoVO>) {
LogUtil.debug('CategoryComponent onCategoryProductTypeSelected handler', event);
if (event.valid) {
this.category.productTypeId = event.source.producttypeId;
this.category.productTypeName = event.source.name;
this.delayedChange.delay();
}
}
onEditPriceTiers() {
LogUtil.debug('CategoryComponent onCategoryProductTypeSelected handler');
if (this._category.navigationByPriceTiers != null && this._category.navigationByPriceTiers.tiers != null) {
this.navigationByPriceTiers = Util.clone(this._category.navigationByPriceTiers);
} else {
this.navigationByPriceTiers = { tiers: [] };
}
this.categoryPriceTiersModalDialog.show();
}
onEditPriceTiersModalResult(modalresult: ModalResult) {
LogUtil.debug('CategoryComponent onEditPriceTiersModalResult modal result is ', modalresult);
if (ModalAction.POSITIVE === modalresult.action) {
this._category.navigationByPriceTiers = this.navigationByPriceTiers;
this.navigationByPriceTiers = null;
this.categoryForm.updateValueAndValidity();
this.delayedChange.delay();
} else {
this.navigationByPriceTiers = null;
}
}
onNavPriceTierDelete(tier:Pair<string, Array<CategoryNavigationPriceTierVO>>, item:CategoryNavigationPriceTierVO) {
LogUtil.debug('CategoryComponent onNavPriceTierDelete handler', tier, item);
let idx = tier.second.indexOf(item);
if (idx != -1) {
tier.second.splice(idx, 1);
tier.second = tier.second.slice(0, tier.second.length);
}
}
onNavPriceTierAdd(tier:Pair<string, Array<CategoryNavigationPriceTierVO>>) {
LogUtil.debug('CategoryComponent onNavPriceTierAdd handler', tier);
tier.second.push({ from: 0, to: 99 });
}
onEditPriceTiersAddCurrency() {
LogUtil.debug('CategoryComponent onEditPriceTiersAddCurrency handler');
if (this.navigationByPriceTiersAddCurrency != null && this.navigationByPriceTiersAddCurrency.length == 3) {
this.navigationByPriceTiers.tiers.push({ first: this.navigationByPriceTiersAddCurrency, second: [] });
}
}
onClearFilter() {
this.attributeFilter = '';
}
onSearchHelpToggle() {
this.searchHelpShow = !this.searchHelpShow;
}
onSearchValues() {
this.searchHelpShow = false;
this.attributeFilter = '###';
}
onSearchValuesNew() {
this.searchHelpShow = false;
this.attributeFilter = '##0';
}
onSearchValuesNewOnly() {
this.searchHelpShow = false;
this.attributeFilter = '#00';
}
onSearchValuesChanges() {
this.searchHelpShow = false;
this.attributeFilter = '#0#';
}
} | the_stack |
import { Client, Intents, Message, TextChannel, User } from 'discord.js'
import emojiStrip from 'emoji-strip'
import axios from 'axios'
import type { Config } from './Config'
import Rcon from './Rcon'
import { escapeUnicode } from './lib/util'
class Discord {
config: Config
client: Client
channel: TextChannel | null
uuidCache: Map<string, string>
mentionCache: Map<string, User>
constructor (config: Config, onReady?: () => void) {
this.config = config
this.client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
if (onReady) this.client.once('ready', () => onReady())
this.client.on('messageCreate', (message: Message) => this.onMessage(message))
this.channel = null
this.uuidCache = new Map()
this.mentionCache = new Map()
}
public async init () {
try {
await this.client.login(this.config.DISCORD_TOKEN)
} catch (e) {
console.log('[ERROR] Could not authenticate with Discord: ' + e)
if (this.config.DEBUG) console.error(e)
process.exit(1)
}
if (this.config.DISCORD_CHANNEL_NAME && !this.config.DISCORD_CHANNEL_ID) {
await this.getChannelIdFromName(this.config.DISCORD_CHANNEL_NAME)
} else if (this.config.DISCORD_CHANNEL_ID) {
const channel = await this.client.channels.fetch(this.config.DISCORD_CHANNEL_ID) as TextChannel
if (!channel) {
console.log(`[INFO] Could not find channel with ID ${this.config.DISCORD_CHANNEL_ID}. Please check that the ID is correct and that the bot has access to it.`)
process.exit(1)
}
this.channel = channel
}
if (this.channel) {
console.log(`[INFO] Using channel #${this.channel.name} (id: ${this.channel.id}) in the server "${this.channel.guild.name}"`)
}
}
private async getChannelIdFromName (name: string) {
// remove the # if there is one
if (name.startsWith('#')) name = name.substring(1, name.length)
// fetch all the channels in every server
for (const guild of this.client.guilds.cache.values()) {
await guild.channels.fetch()
}
const channel = this.client.channels.cache.find((c) => c.isText() && c.type === 'GUILD_TEXT' && c.name === name && !c.deleted)
if (channel) {
this.channel = channel as TextChannel
} else {
console.log(`[INFO] Could not find channel ${name}! Check that the name is correct or use the ID of the channel instead (DISCORD_CHANNEL_ID)!`)
process.exit(1)
}
}
private parseDiscordWebhook (url: string) {
const re = /discord[app]?.com\/api\/webhooks\/([^\/]+)\/([^\/]+)/
// the is of the webhook
let id = null
let token = null
if (!re.test(url)) {
// In case the url changes at some point, I will warn if it still works
console.log('[WARN] The Webhook URL may not be valid!')
} else {
const match = url.match(re)
if (match) {
id = match[1]
token = match[2]
}
}
return { id, token }
}
private async onMessage (message: Message) {
// no channel, done
if (!this.channel) return
// don't want to check other channels
if (message.channel.id !== this.channel.id || message.channel.type !== 'GUILD_TEXT') return
// if using webhooks, ignore this!
if (message.webhookId) {
// backwards compatability with older config
if (this.config.USE_WEBHOOKS && this.config.IGNORE_WEBHOOKS === undefined) return
// if ignoring all webhooks, ignore
if (this.config.IGNORE_WEBHOOKS) {
return
} else if (this.config.USE_WEBHOOKS) {
// otherwise, ignore all webhooks that are not the same as this one
const { id } = this.parseDiscordWebhook(this.config.WEBHOOK_URL)
if (id === message.webhookId) {
if (this.config.DEBUG) console.log('[INFO] Ignoring webhook from self')
return
}
}
}
// ensure that the message has a sender
if (!message.author) return
// ensure that the message is a text message
if (message.type !== 'DEFAULT') return
// if the same user as the bot, ignore
if (message.author.id === this.client.user?.id) return
// ignore any attachments
if (message.attachments.size) return
const rcon = new Rcon(this.config.MINECRAFT_SERVER_RCON_IP, this.config.MINECRAFT_SERVER_RCON_PORT, this.config.DEBUG)
try {
await rcon.auth(this.config.MINECRAFT_SERVER_RCON_PASSWORD)
} catch (e) {
console.log('[ERROR] Could not auth with the server!')
if (this.config.DEBUG) console.error(e)
}
let command: string | undefined;
if (this.config.ALLOW_SLASH_COMMANDS && this.config.SLASH_COMMAND_ROLES && message.cleanContent.startsWith('/') && message.member) {
const hasSlashCommandRole = message.member.roles.cache.find(r => this.config.SLASH_COMMAND_ROLES.includes(r.name))
if (hasSlashCommandRole) {
// send the raw command, can be dangerous...
command = message.cleanContent
} else {
console.log('[INFO] User attempted a slash command without a role')
}
} else {
if (this.config.MINECRAFT_TELLRAW_DOESNT_EXIST) {
command = `/say ${this.makeMinecraftMessage(message)}`
} else {
command = `/tellraw @a ${this.makeMinecraftMessage(message)}`
}
}
if (this.config.DEBUG) console.log(`[DEBUG] Sending command "${command}" to the server`)
if (command) {
let response: string | undefined;
try {
response = await rcon.command(command)
} catch (e) {
console.log('[ERROR] Could not send command!')
if (this.config.DEBUG) console.error(e)
}
if (response?.startsWith('Unknown command') || response?.startsWith('Unknown or incomplete command')) {
console.log('[ERROR] Could not send command! (Unknown command)')
if (command.startsWith('/tellraw')) {
console.log('Your Minecraft version may not support tellraw, please look into MINECRAFT_TELLRAW_DOESNT_EXIST!')
}
}
}
rcon.close()
}
private makeMinecraftMessage(message: Message): string {
const username = emojiStrip(message.author.username)
const variables: {[index: string]: string} = {
username,
nickname: !!message.member?.nickname ? emojiStrip(message.member.nickname) : username,
discriminator: message.author.discriminator,
text: emojiStrip(message.cleanContent),
}
// use JSON to encode the strings for tellraw
for (const [k, v] of Object.entries(variables)) {
variables[k] = JSON.stringify(v).slice(1,-1)
}
if (this.config.MINECRAFT_TELLRAW_DOESNT_EXIST) {
return this.config.MINECRAFT_TELLRAW_DOESNT_EXIST_SAY_TEMPLATE
.replace(/%username%/g, variables.username)
.replace(/%nickname%/g, variables.nickname)
.replace(/%discriminator%/g, variables.discriminator)
.replace(/%message%/g, variables.text)
}
variables.text = escapeUnicode(variables.text)
return this.config.MINECRAFT_TELLRAW_TEMPLATE
.replace(/%username%/g, variables.username)
.replace(/%nickname%/g, variables.nickname)
.replace(/%discriminator%/g, variables.discriminator)
.replace(/%message%/g, variables.text)
}
private async replaceDiscordMentions(message: string): Promise<string> {
const possibleMentions = message.match(/@[^#\s]*[#]?[0-9]{4}/gim)
if (possibleMentions) {
for (let mention of possibleMentions) {
const mentionParts = mention.split('#')
let username = mentionParts[0].replace('@', '')
if (mentionParts.length > 1) {
if (this.config.ALLOW_USER_MENTIONS) {
let user = this.mentionCache.get(mention)
if (!user) {
// try fetching members by username to update cache
await this.channel!.guild.members.fetch({ query: username })
user = this.client.users.cache.find(user => user.username === username && user.discriminator === mentionParts[1])
}
if (user) {
message = message.replace(mention, '<@' + user.id + '>')
if (!this.mentionCache.has(mention)) this.mentionCache.set(mention, user)
} else {
console.log(`[ERROR] Could not find user by mention: "${mention}"`)
}
}
}
if (['here', 'everyone'].includes(username)) {
// remove these large pings
if (!this.config.ALLOW_HERE_EVERYONE_MENTIONS) {
message = message
.replace('@everyone', '@ everyone')
.replace('@here', '@ here')
}
}
}
}
return message
}
private async getUUIDFromUsername (username: string): Promise<string | null> {
username = username.toLowerCase()
if (this.uuidCache.has(username)) return this.uuidCache.get(username)!
// otherwise fetch and store
try {
const response = await (await axios.get('https://api.mojang.com/users/profiles/minecraft/' + username)).data
const uuid = response.id
this.uuidCache.set(username, uuid)
if (this.config.DEBUG) console.log(`[DEBUG] Fetched UUID ${uuid} for username "${username}"`)
return uuid
} catch (e) {
console.log(`[ERROR] Could not fetch uuid for ${username}, falling back to Steve for the skin`)
return null
}
}
private getHeadUrl(uuid: string): string {
const url = this.config.HEAD_IMAGE_URL || 'https://mc-heads.net/avatar/%uuid%/256'
return url.replace(/%uuid%/, uuid)
}
private async makeDiscordWebhook (username: string, message: string) {
const defaultHead = this.getHeadUrl(this.config.DEFAULT_PLAYER_HEAD || 'c06f89064c8a49119c29ea1dbd1aab82') // MHF_Steve
let avatarURL
if (username === this.config.SERVER_NAME + ' - Server') { // use avatar for the server
avatarURL = this.config.SERVER_IMAGE || defaultHead
} else { // use avatar for player
const uuid = await this.getUUIDFromUsername(username)
avatarURL = !!uuid ? this.getHeadUrl(uuid) : defaultHead
}
return {
username,
content: message,
'avatar_url': avatarURL,
}
}
private makeDiscordMessage(username: string, message: string) {
return this.config.DISCORD_MESSAGE_TEMPLATE
.replace('%username%', username)
.replace('%message%', message)
}
public async sendMessage (username: string, message: string) {
message = await this.replaceDiscordMentions(message)
if (this.config.USE_WEBHOOKS) {
const webhook = await this.makeDiscordWebhook(username, message)
try {
await axios.post(this.config.WEBHOOK_URL, webhook, { headers: { 'Content-Type': 'application/json' } })
return
} catch (e) {
console.log('[ERROR] Could not send Discord message through WebHook! Falling back to sending through bot.')
if (this.config.DEBUG) console.log(e)
}
}
const messageContent = this.makeDiscordMessage(username, message)
try {
await this.channel!.send(messageContent)
} catch (e) {
console.log('[ERROR] Could not send Discord message through bot!')
process.exit(1)
}
}
}
export default Discord | the_stack |
import { Client, ApiResponse, RequestParams } from "@elastic/elasticsearch";
import _ = require("lodash");
import {
Query,
FacetType,
FacetSearchResult,
Region,
FacetOption,
SearchResult,
ISODate
} from "../../model";
import SearchQueryer from "../SearchQueryer";
import getFacetDefinition from "./getFacetDefinition";
/**
* A field within the dataset document indexed in ES that will be searched
* using a certain analyzer. Includes a value for how much this individual
* field should be boosted by.
*/
type AnalysisField = {
path: string;
boost?: number;
};
/**
* Fields that will be analyzed using a language analyzer (i.e. they have
* features like plurals that need to be taken into account)
*/
const DATASETS_LANGUAGE_FIELDS: AnalysisField[] = [
{ path: "title", boost: 50 },
{ path: "description", boost: 2 },
{ path: "publisher.name" },
{ path: "keywords", boost: 10 },
{ path: "themes" }
];
/**
* Fields that should not be analyzed using a language analyzer
*/
const NON_LANGUAGE_FIELDS: AnalysisField[] = [
{ path: "_id" },
{ path: "catalog" },
{ path: "accrualPeriodicity" },
{ path: "contactPoint.identifier" },
{ path: "publisher.acronym" }
];
/**
* A `SearchQueryer` that uses ElasticSearch to query the index
*/
export default class ElasticSearchQueryer implements SearchQueryer {
/**
* The ES client to use for querying. This is an HTTP client, so it doesn't
* need a lot of management around setup/teardown.
*/
private client = new Client({ node: this.url });
/**
* @param url The base URL to call ElasticSearch at
* @param datasetsIndexId The id of the datasets index in ES
* @param regionsIndexId The id of the regions index in ES
* @param publishersIndexId The id of the publishers index in ES
*/
constructor(
readonly url: string,
readonly datasetsIndexId: string,
readonly regionsIndexId: string,
readonly publishersIndexId: string
) {}
async searchFacets(
facetType: FacetType,
generalQuery: Query,
start: number,
limit: number,
facetQuery: string | undefined
): Promise<FacetSearchResult> {
const facetDef = getFacetDefinition(facetType);
const esQueryBody: RequestParams.Search = {
index: this.publishersIndexId,
body: {
query: {
dis_max: {
tie_breaker: 0,
queries: [
{
match_phrase_prefix: {
value: facetQuery || ""
}
},
{
match_phrase_prefix: {
acronym: facetQuery || ""
}
}
]
}
}
},
size: limit,
from: start
};
// console.log(JSON.stringify(esQueryBody, null, 2));
const result: ApiResponse = await this.client.search(esQueryBody);
const { body } = result;
if (body.totalHits === 0) {
return { hitCount: 0, options: [] };
} else {
type Hit = {
value: string;
identifier: string;
};
const hits: Hit[] = body.hits.hits.map((hit: any) => hit._source);
// Create a dataset filter aggregation for each hit in the initial query
const filters = hits.reduce(
(soFar: any, { value }: Hit) => ({
...soFar,
[value]: {
filter: facetDef.exactMatchQuery(value)
}
}),
{}
);
// Do a datasets query WITHOUT filtering for this facet and with an aggregation for each of the hits we
// got back on our keyword - this allows us to get an accurate count of dataset hits for each result
const generalEsQueryBody = {
from: 0,
size: 0,
body: {
query: await this.buildESBody(
facetDef.removeFromQuery(generalQuery)
),
aggs: filters
},
index: this.datasetsIndexId
};
// console.log(JSON.stringify(generalEsQueryBody, null, 2));
const resultWithout = await this.client.search(generalEsQueryBody);
const aggregationsResult = _(
resultWithout.body.aggregations as {
[aggName: string]: any;
}
)
.map((value, key) => ({
countErrorUpperBound: 0,
hitCount: value.doc_count || 0,
matched: false,
value: key
}))
.keyBy("value")
.value();
const options: FacetOption[] = _(hits)
.map((hit) => ({
...aggregationsResult[hit.value],
identifier: hit.identifier
}))
.sortBy((hit) => -hit.hitCount)
.drop(start)
.take(limit)
.value();
return {
hitCount: resultWithout.body.hits.total,
options
};
}
}
async search(
query: Query,
start: number,
limit: number,
facetSize: number
): Promise<SearchResult> {
const searchParams: RequestParams.Search = {
from: start,
size: limit,
body: {
query: await this.buildESBody(query),
aggs: {
minDate: {
min: {
field: "temporal.start.date"
}
},
maxDate: {
max: {
field: "temporal.end.date"
}
}
}
},
index: this.datasetsIndexId
};
// For debugging! Use this to explain how a certain dataset is rated.
// console.log(
// JSON.stringify(
// (await this.client.explain({
// body: {
// query: await this.buildESDatasetsQuery(query)
// // aggs: filters
// },
// index: this.datasetsIndexId,
// id: "ds-6",
// type: "datasets"
// })).body,
// null,
// 2
// )
// );
// console.log(JSON.stringify(searchParams, null, 2));
const response: ApiResponse = await this.client.search(searchParams);
// console.log(response.body);
return {
query,
hitCount: response.body.hits.total,
dataSets: response.body.hits.hits.map((hit: any) => ({
...hit._source,
score: hit._score,
years: undefined
})),
temporal: {
start: {
date: response.body.aggregations.minDate.value_as_string // new Date().toISOString() //TODO
},
end: {
date: response.body.aggregations.maxDate.value_as_string //TODO
}
},
facets: [],
strategy: "match-all"
};
}
/**
* Get the regions to apply a boost to, based off the search text in a query.
*
* E.g. if a user searches for "trees marrickville", then datasets that match the
* "Marrickville" SA regions should be boosted above ones that don't.
*/
async getBoostRegions(query: Query): Promise<Region[]> {
if (!query.freeText || query.freeText === "") {
return [];
}
const regionsResult = await this.client.search({
index: this.regionsIndexId,
body: {
query: {
match: {
regionSearchId: {
query: query.freeText,
operator: "or"
}
}
}
},
size: 50
});
return regionsResult.body.hits.hits.map((x: any) => x._source);
}
/**
* Uses the Search API query to build an object that can be passed
* to ElasticSearch in the body.
*/
async buildESBody(query: Query): Promise<any> {
const boostRegions = await this.getBoostRegions(query);
const geomScorerQueries = boostRegions.map(
this.regionToGeoshapeQuery,
this
);
const qualityFactor = {
filter: {
term: {
hasQuality: true
}
},
field_value_factor: {
field: "quality",
missing: 1
}
};
const esQuery = {
function_score: {
query: this.queryToEsQuery(query, boostRegions),
functions: [
{
weight: 1
},
qualityFactor,
{
filter: {
bool: {
should: geomScorerQueries
}
},
weight: 1
}
],
score_mode: "sum"
}
};
return esQuery;
}
/**
* Turns a query recieved by the search API into a query recognisable by ES.
*/
queryToEsQuery(query: Query, boostRegions: Region[]): any {
const freeText = (() => {
const sanitisedFreeText =
!query.freeText || query.freeText === "" ? "*" : query.freeText;
const textQuery = this.textQuery(sanitisedFreeText);
if (boostRegions.length === 0) {
return textQuery;
} else {
const regionNames: string[] = _(boostRegions)
.flatMap((region) => [
region.regionName,
region.regionShortName
])
.filter((x) => !!x && x !== "")
.map((x) => x as string)
.sortBy((x: string) => x.length)
.value();
// Remove these regions from the text
const textWithoutRegions = regionNames
.reduce(
(soFar, currentRegion) =>
soFar.replace(new RegExp(currentRegion, "ig"), ""),
sanitisedFreeText
)
.trim();
const textQueryNoRegions = this.textQuery(
textWithoutRegions.length > 0 ? textWithoutRegions : "*"
);
const geomScorerQueries = boostRegions.map(
this.regionToGeoshapeQuery,
this
);
return {
bool: {
should: [
textQuery,
{
bool: {
must: [
textQueryNoRegions,
...geomScorerQueries
]
}
}
],
minimum_should_match: 1
}
};
}
})();
const dateQuery = (date: ISODate, comparator: "gte" | "lte") => ({
bool: {
should: [
{
range: {
"temporal.end.date": {
[comparator]: date
}
}
},
{
range: {
"temporal.start.date": {
[comparator]: date
}
}
}
],
minimum_should_match: 1
}
});
return {
bool: {
must: [
freeText,
...query.regions.map((queryRegion) =>
this.regionIdToGeoshapeQuery(
queryRegion.regionType + "/" + queryRegion.regionId
)
),
query.dateFrom &&
dateQuery(query.dateFrom.toISOString(), "gte"),
query.dateTo && dateQuery(query.dateTo.toISOString(), "lte")
].filter((x) => !!x)
}
};
}
/** Turns a string into an ElasticSearch text query */
textQuery(inputText: string) {
const simpleQueryStringQuery = {
query: inputText,
default_operator: "and",
quote_field_suffix: ".quote"
};
// Surprise! english analysis doesn't work on nested objects unless you have a nested query, even though
// other analysis does. So we do this silliness
const distributionsEnglishQuery = {
nested: {
path: "distributions",
score_mode: "max",
query: {
simple_query_string: {
query: inputText,
fields: [
"distributions.title",
"distributions.description",
"distributions.format"
],
default_operator: "and"
}
}
}
};
/**
* Unfortunately, when default operator is AND, we can't put NON_LANGUAGE_FIELDS & DATASETS_LANGUAGE_FIELDS
* into one SimpleStringQuery as they have different searchAnalylzer
* It will result a term like +(catalog:at | _id:at) will never be matched
* We need to fix on our side as elasticsearch won't know our intention for this case
*/
const queries = [
{
bool: {
should: [
{
simple_query_string: {
...simpleQueryStringQuery,
fields: DATASETS_LANGUAGE_FIELDS.map(
fieldDefToEs
)
}
},
{
simple_query_string: {
...simpleQueryStringQuery,
fields: NON_LANGUAGE_FIELDS.map(fieldDefToEs)
}
}
],
minimum_should_match: 1
}
},
distributionsEnglishQuery
];
return {
dis_max: {
queries
}
};
}
regionToGeoshapeQuery(region: Region) {
return this.regionIdToGeoshapeQuery(region.regionSearchId);
}
regionIdToGeoshapeQuery(id: string) {
return {
geo_shape: {
"spatial.geoJson": {
indexed_shape: {
index: this.regionsIndexId,
type: "regions",
id,
path: "geometry"
}
}
}
};
}
}
function fieldDefToEs(def: AnalysisField): string {
if (typeof def.boost !== "undefined") {
return `${def.path}^${def.boost}`;
} else {
return def.path;
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type fairRoutes_FaiArticlesQueryVariables = {
slug: string;
};
export type fairRoutes_FaiArticlesQueryResponse = {
readonly fair: {
readonly " $fragmentRefs": FragmentRefs<"FairArticles_fair">;
} | null;
};
export type fairRoutes_FaiArticlesQuery = {
readonly response: fairRoutes_FaiArticlesQueryResponse;
readonly variables: fairRoutes_FaiArticlesQueryVariables;
};
/*
query fairRoutes_FaiArticlesQuery(
$slug: String!
) {
fair(id: $slug) @principalField {
...FairArticles_fair
id
}
}
fragment FairArticles_fair on Fair {
slug
articlesConnection(first: 7) {
totalCount
edges {
node {
internalID
title
href
author {
name
id
}
publishedAt(format: "MMM Do, YYYY")
thumbnailTitle
thumbnailImage {
large: cropped(width: 733, height: 550) {
width
height
src
srcSet
}
medium: cropped(width: 267, height: 150) {
width
height
src
srcSet
}
}
id
__typename
}
cursor
}
pageInfo {
endCursor
hasNextPage
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "slug",
"type": "String!"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "slug"
}
],
v2 = [
{
"kind": "Literal",
"name": "first",
"value": 7
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v4 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "width",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "height",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "src",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "srcSet",
"storageKey": null
}
];
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "fairRoutes_FaiArticlesQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "FairArticles_fair"
}
],
"storageKey": null
}
],
"type": "Query"
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "fairRoutes_FaiArticlesQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "ArticleConnection",
"kind": "LinkedField",
"name": "articlesConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "totalCount",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArticleEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Article",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Author",
"kind": "LinkedField",
"name": "author",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "MMM Do, YYYY"
}
],
"kind": "ScalarField",
"name": "publishedAt",
"storageKey": "publishedAt(format:\"MMM Do, YYYY\")"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "thumbnailTitle",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "thumbnailImage",
"plural": false,
"selections": [
{
"alias": "large",
"args": [
{
"kind": "Literal",
"name": "height",
"value": 550
},
{
"kind": "Literal",
"name": "width",
"value": 733
}
],
"concreteType": "CroppedImageUrl",
"kind": "LinkedField",
"name": "cropped",
"plural": false,
"selections": (v4/*: any*/),
"storageKey": "cropped(height:550,width:733)"
},
{
"alias": "medium",
"args": [
{
"kind": "Literal",
"name": "height",
"value": 150
},
{
"kind": "Literal",
"name": "width",
"value": 267
}
],
"concreteType": "CroppedImageUrl",
"kind": "LinkedField",
"name": "cropped",
"plural": false,
"selections": (v4/*: any*/),
"storageKey": "cropped(height:150,width:267)"
}
],
"storageKey": null
},
(v3/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "articlesConnection(first:7)"
},
{
"alias": null,
"args": (v2/*: any*/),
"filters": null,
"handle": "connection",
"key": "FairArticlesQuery_articlesConnection",
"kind": "LinkedHandle",
"name": "articlesConnection"
},
(v3/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": null,
"metadata": {},
"name": "fairRoutes_FaiArticlesQuery",
"operationKind": "query",
"text": "query fairRoutes_FaiArticlesQuery(\n $slug: String!\n) {\n fair(id: $slug) @principalField {\n ...FairArticles_fair\n id\n }\n}\n\nfragment FairArticles_fair on Fair {\n slug\n articlesConnection(first: 7) {\n totalCount\n edges {\n node {\n internalID\n title\n href\n author {\n name\n id\n }\n publishedAt(format: \"MMM Do, YYYY\")\n thumbnailTitle\n thumbnailImage {\n large: cropped(width: 733, height: 550) {\n width\n height\n src\n srcSet\n }\n medium: cropped(width: 267, height: 150) {\n width\n height\n src\n srcSet\n }\n }\n id\n __typename\n }\n cursor\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n}\n"
}
};
})();
(node as any).hash = '3a804b0eed7cc5ae52329dc763f9773a';
export default node; | the_stack |
import {
Component,
Input,
Output,
ElementRef,
EventEmitter,
OnInit,
OnDestroy,
ViewEncapsulation,
} from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { dia } from 'jointjs';
import { Flo } from '../shared/flo-common';
import { Shapes, Constants } from '../shared/shapes';
import { Utils } from './editor-utils';
import { CompositeDisposable, Disposable } from 'ts-disposables';
import * as _$ from 'jquery';
import * as _ from 'lodash';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { Logger } from '../shared/logger';
const joint: any = Flo.joint;
const $: any = _$;
export interface VisibilityState {
visibility: string;
children: Array<VisibilityState>;
}
const SCROLLBAR_SIZE = 17;
@Component({
selector: 'flo-editor',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class EditorComponent implements OnInit, OnDestroy {
/**
* Joint JS Graph object representing the Graph model
*/
private graph: dia.Graph;
/**
* Joint JS Paper object representing the canvas control containing the graph view
*/
private paper: dia.Paper;
/**
* Currently selected element
*/
private _selection: dia.CellView;
/**
* Current DnD descriptor for frag in progress
*/
private highlighted: Flo.DnDDescriptor;
/**
* Flag specifying whether the Flo-Editor is in read-only mode.
*/
private _readOnlyCanvas = false;
/**
* Grid size
*/
private _gridSize = 1;
private _hiddenPalette = false;
private paletteSizeValue = 170;
private editorContext: Flo.EditorContext;
private textToGraphEventEmitter = new EventEmitter<void>();
private graphToTextEventEmitter = new EventEmitter<void>();
private _graphToTextSyncEnabled = true;
private validationEventEmitter = new EventEmitter<void>();
private _disposables = new CompositeDisposable();
private _dslText = '';
private textToGraphConversionCompleted = new Subject<void>();
private graphToTextConversionCompleted = new Subject<void>();
private paletteReady = new BehaviorSubject<boolean>(false);
/**
* Metamodel. Retrieves metadata about elements that can be shown in Flo
*/
@Input()
metamodel: Flo.Metamodel;
/**
* Renders elements.
*/
@Input()
renderer: Flo.Renderer;
/**
* Editor. Provides domain specific editing capabilities on top of standard Flo features
*/
@Input()
editor: Flo.Editor;
/**
* Size (Width) of the palette
*/
@Input()
get paletteSize(): number {
return this.paletteSizeValue;
}
@Output()
paletteSizeChange = new EventEmitter<number>();
set paletteSize(newSize: number) {
this.paletteSizeValue = newSize;
this.paletteSizeChange.emit(newSize);
}
@Input()
searchFilterPlaceHolder = 'Search...';
/**
* Palette entry padding
*/
@Input()
paletteEntryPadding: dia.Size;
/**
* Min zoom percent value
*/
@Input()
minZoom = 5;
/**
* Max zoom percent value
*/
@Input()
maxZoom = 400;
/**
* Zoom percent increment/decrement step
*/
@Input()
zoomStep = 5;
@Input()
paperPadding = 0;
@Output()
floApi = new EventEmitter<Flo.EditorContext>();
@Output()
validationMarkers = new EventEmitter<Map<string | number, Array<Flo.Marker>>>();
@Output()
contentValidated = new EventEmitter<boolean>();
@Output()
private dslChange = new EventEmitter<string>();
@Output()
onProperties = new EventEmitter<any>();
private _resizeHandler = () => this.autosizePaper();
constructor(private element: ElementRef) {
let self = this;
this.editorContext = new (class DefaultRunnableContext implements Flo.EditorContext {
set zoomPercent(percent: number) {
self.zoomPercent = percent;
}
get zoomPercent(): number {
return self.zoomPercent;
}
set noPalette(noPalette: boolean) {
self.noPalette = noPalette;
}
get noPalette(): boolean {
return self.noPalette;
}
set gridSize(gridSize: number) {
self.gridSize = gridSize;
}
get gridSize(): number {
return self.gridSize;
}
set readOnlyCanvas(readOnly: boolean) {
self.readOnlyCanvas = readOnly;
}
get readOnlyCanvas(): boolean {
return self.readOnlyCanvas;
}
setDsl(dsl: string) {
self.dsl = dsl;
}
updateGraph(): Promise<any> {
return self.updateGraphRepresentation();
}
updateText(): Promise<any> {
return self.updateTextRepresentation();
}
performLayout(): Promise<void> {
return self.doLayout();
}
clearGraph(): Promise<void> {
self.selection = undefined;
self.graph.clear();
if (self.metamodel && self.metamodel.load && self.editor && self.editor.setDefaultContent) {
return self.metamodel.load().then(data => {
self.editor.setDefaultContent(this, data);
if (!self.graphToTextSync) {
return self.updateTextRepresentation();
}
});
} else {
if (!self.graphToTextSync) {
return self.updateTextRepresentation();
}
}
}
getGraph() {
return self.graph;
}
getPaper() {
return self.paper;
}
get graphToTextSync(): boolean {
return self.graphToTextSync;
}
set graphToTextSync(sync: boolean) {
self.graphToTextSync = sync;
}
getMinZoom() {
return self.minZoom;
}
getMaxZoom() {
return self.maxZoom;
}
getZoomStep() {
return self.zoomStep;
}
fitToPage() {
self.fitToPage();
}
createNode(metadata: Flo.ElementMetadata, props?: Map<string, any>, position?: dia.Point): dia.Element {
return self.createNode(metadata, props, position);
}
createLink(source: Flo.LinkEnd, target: Flo.LinkEnd, metadata?: Flo.ElementMetadata, props?: Map<string, any>): dia.Link {
return self.createLink(source, target, metadata, props);
}
get selection(): dia.CellView {
return self.selection;
}
set selection(newSelection: dia.CellView) {
self.selection = newSelection;
}
deleteSelectedNode(): void {
self.deleteSelected();
}
delete(cell: dia.Cell) {
self.delete(cell);
}
get textToGraphConversionObservable(): Observable<void> {
return self.textToGraphConversionCompleted;
}
get graphToTextConversionObservable(): Observable<void> {
return self.graphToTextConversionCompleted;
}
get paletteReady(): Observable<boolean> {
return self.paletteReady;
}
})();
}
onPropertiesHandle() {
if (this.editorContext.selection) {
this.onProperties.emit(this.editorContext.selection.model)
}
}
ngOnInit() {
this.initGraph();
this.initPaper();
this.initGraphListeners();
this.initPaperListeners();
this.initMetamodel();
$(window).on('resize', this._resizeHandler);
this._disposables.add(Disposable.create(() => $(window).off('resize', this._resizeHandler)));
/*
* Execute resize to get the right size for the SVG element on the editor canvas.
* Executed via timeout to let angular render the DOM first and elements to have the right width and height
*/
window.setTimeout(this._resizeHandler);
this.floApi.emit(this.editorContext);
}
ngOnDestroy() {
this._disposables.dispose();
}
deleteSelected() {
if (this.selection) {
this.delete(this.selection.model);
}
}
delete(cell: dia.Cell) {
this.graph.trigger('startDeletion', cell);
}
get noPalette(): boolean {
return this._hiddenPalette;
}
set noPalette(hidden: boolean) {
this._hiddenPalette = hidden;
// If palette is not shown ensure that canvas starts from the left==0!
if (hidden) {
$('#paper-container', this.element.nativeElement).css('left', 0);
}
}
get graphToTextSync(): boolean {
return this._graphToTextSyncEnabled;
}
set graphToTextSync(sync: boolean) {
this._graphToTextSyncEnabled = sync;
// Try commenting the sync out. Just set the flag but don't kick off graph->text conversion
// this.performGraphToTextSyncing();
}
private performGraphToTextSyncing() {
if (this._graphToTextSyncEnabled) {
this.graphToTextEventEmitter.emit();
}
}
createHandle(element: dia.CellView, kind: string, action: () => void, location: dia.Point): dia.Element {
if (!location) {
let bbox: any = (<any>element.model).getBBox();
location = bbox.origin().offset(bbox.width / 2, bbox.height / 2);
}
let handle = Shapes.Factory.createHandle({
renderer: this.renderer,
paper: this.paper,
parent: element.model,
kind: kind,
position: location
});
const view: dia.ElementView = this.paper.findViewByModel(handle);
view.on('cell:pointerdown', () => {
if (action) {
action();
}
});
view.on('cell:mouseover', () => {
handle.attr('image/filter', {
name: 'dropShadow',
args: {dx: 1, dy: 1, blur: 1, color: 'black'}
});
});
view.on('cell:mouseout', () => {
handle.removeAttr('image/filter');
});
view.setInteractivity(false);
return handle;
}
removeEmbeddedChildrenOfType(element: dia.Cell, types: Array<string>): void {
let embeds = element.getEmbeddedCells();
for (let i = 0; i < embeds.length; i++) {
if (types.indexOf(embeds[i].get('type')) >= 0) {
embeds[i].remove();
}
}
}
get selection(): dia.CellView {
return this._selection;
}
set selection(newSelection: dia.CellView) {
if (newSelection && (newSelection.model.get('type') === joint.shapes.flo.DECORATION_TYPE || newSelection.model.get('type') === joint.shapes.flo.HANDLE_TYPE)) {
newSelection = this.paper.findViewByModel(this.graph.getCell(newSelection.model.get('parent')));
}
if (newSelection && (!newSelection.model.get('metadata') || newSelection.model.get('metadata')?.metadata?.unselectable)) {
newSelection = undefined;
}
if (newSelection !== this._selection) {
if (this._selection) {
const elementview = this.paper.findViewByModel(this._selection.model);
if (elementview) { // May have been removed from the graph
this.removeEmbeddedChildrenOfType(elementview.model, joint.shapes.flo.HANDLE_TYPE);
elementview.unhighlight();
}
}
if (newSelection) {
newSelection.highlight();
if (this.editor && this.editor.createHandles) {
this.editor.createHandles(this.editorContext, (owner: dia.CellView, kind: string, action: () => void, location: dia.Point) => this.createHandle(owner, kind, action, location), newSelection);
}
}
this._selection = newSelection;
}
}
get readOnlyCanvas(): boolean {
return this._readOnlyCanvas;
}
set readOnlyCanvas(value: boolean) {
if (this._readOnlyCanvas === value) {
// Nothing to do
return
}
if (value) {
this.selection = undefined;
}
if (this.graph) {
this.graph.getLinks().forEach((link: dia.Link) => {
if (value) {
link.attr('.link-tools/display', 'none');
link.attr('.marker-vertices/display', 'none');
link.attr('.connection-wrap/display', 'none');
} else {
link.removeAttr('.link-tools/display');
if (this.editor && this.editor.allowLinkVertexEdit) {
link.removeAttr('.marker-vertices/display');
}
link.removeAttr('.connection-wrap/display');
}
});
}
this._readOnlyCanvas = value;
}
/**
* Displays graphical feedback for the drag and drop in progress based on current drag and drop descriptor object
*
* @param dragDescriptor DnD info object. Has on info on graph node being dragged (drag source) and what it is
* being dragged over at the moment (drop target)
*/
showDragFeedback(dragDescriptor: Flo.DnDDescriptor): void {
if (this.editor && this.editor.showDragFeedback) {
this.editor.showDragFeedback(this.editorContext, dragDescriptor);
} else {
let magnet: SVGElement;
if (dragDescriptor.source && dragDescriptor.source.view) {
joint.V(dragDescriptor.source.view.el).addClass('dnd-source-feedback');
if (dragDescriptor.source.cssClassSelector) {
magnet = Flo.findMagnetByClass(dragDescriptor.source.view, dragDescriptor.source.cssClassSelector);
if (magnet) {
joint.V(magnet).addClass('dnd-source-feedback');
}
}
}
if (dragDescriptor.target && dragDescriptor.target.view) {
joint.V(dragDescriptor.target.view.el).addClass('dnd-target-feedback');
if (dragDescriptor.target.cssClassSelector) {
magnet = Flo.findMagnetByClass(dragDescriptor.target.view, dragDescriptor.target.cssClassSelector);
if (magnet) {
joint.V(magnet).addClass('dnd-target-feedback');
}
}
}
}
}
/**
* Hides graphical feedback for the drag and drop in progress based on current drag and drop descriptor object
*
* @param dragDescriptor DnD info object. Has on info on graph node being dragged (drag source) and what it is
* being dragged over at the moment (drop target)
*/
hideDragFeedback(dragDescriptor: Flo.DnDDescriptor): void {
if (this.editor && this.editor.hideDragFeedback) {
this.editor.hideDragFeedback(this.editorContext, dragDescriptor);
} else {
let magnet: SVGElement;
if (dragDescriptor.source && dragDescriptor.source.view) {
joint.V(dragDescriptor.source.view.el).removeClass('dnd-source-feedback');
if (dragDescriptor.source.cssClassSelector) {
magnet = Flo.findMagnetByClass(dragDescriptor.source.view, dragDescriptor.source.cssClassSelector);
if (magnet) {
joint.V(magnet).removeClass('dnd-source-feedback');
}
}
}
if (dragDescriptor.target && dragDescriptor.target.view) {
joint.V(dragDescriptor.target.view.el).removeClass('dnd-target-feedback');
if (dragDescriptor.target.cssClassSelector) {
magnet = Flo.findMagnetByClass(dragDescriptor.target.view, dragDescriptor.target.cssClassSelector);
if (magnet) {
joint.V(magnet).removeClass('dnd-target-feedback');
}
}
}
}
}
/**
* Sets the new DnD info object - the descriptor for DnD
*
* @param dragDescriptor DnD info object. Has on info on graph node being dragged (drag source) and what it is
* being dragged over at the moment (drop target)
*/
setDragDescriptor(dragDescriptor?: Flo.DnDDescriptor): void {
if (this.highlighted === dragDescriptor) {
return;
}
if (this.highlighted && dragDescriptor && _.isEqual(this.highlighted.sourceComponent, dragDescriptor.sourceComponent)) {
if (this.highlighted.source === dragDescriptor.source && this.highlighted.target === dragDescriptor.target) {
return;
}
if (this.highlighted.source &&
dragDescriptor.source &&
this.highlighted.target &&
dragDescriptor.target &&
this.highlighted.source.view.model === dragDescriptor.source.view.model &&
this.highlighted.source.cssClassSelector === dragDescriptor.source.cssClassSelector &&
this.highlighted.target.view.model === dragDescriptor.target.view.model &&
this.highlighted.target.cssClassSelector === dragDescriptor.target.cssClassSelector) {
return;
}
}
if (this.highlighted) {
this.hideDragFeedback(this.highlighted);
}
this.highlighted = dragDescriptor;
if (this.highlighted) {
this.showDragFeedback(this.highlighted);
}
}
/**
* Handles DnD events when a node is being dragged over canvas
*
* @param draggedView The Joint JS view object being dragged
* @param targetUnderMouse The Joint JS view under mouse cursor
* @param x X coordinate of the mouse on the canvas
* @param y Y coordinate of the mosue on the canvas
* @param context DnD context (palette or canvas)
*/
handleNodeDragging(draggedView: dia.CellView, targetUnderMouse: dia.CellView, x: number, y: number, sourceComponent: string) {
if (this.editor && this.editor.calculateDragDescriptor) {
this.setDragDescriptor(this.editor.calculateDragDescriptor(this.editorContext, draggedView, targetUnderMouse, joint.g.point(x, y), sourceComponent));
}
}
/**
* Handles DnD drop event when a node is being dragged and dropped on the main canvas
*/
handleNodeDropping() {
if (this.highlighted && this.editor && this.editor.handleNodeDropping) {
this.editor.handleNodeDropping(this.editorContext, this.highlighted);
}
this.setDragDescriptor(undefined);
}
/**
* Hides DOM Node (used to determine drop target DOM element)
* @param domNode DOM node to hide
* @returns
*/
private _hideNode(domNode: HTMLElement): VisibilityState {
let oldVisibility: VisibilityState = {
visibility: domNode.style ? domNode.style.display : undefined,
children: []
};
for (let i = 0; i < domNode.children.length; i++) {
let node = domNode.children.item(i);
if (node instanceof HTMLElement) {
oldVisibility.children.push(this._hideNode(<HTMLElement> node));
}
}
domNode.style.display = 'none';
return oldVisibility;
}
/**
* Restored DOM node original visibility (used to determine drop target DOM element)
* @param domNode DOM node to restore visibility of
* @param oldVisibility original visibility parameter
*/
_restoreNodeVisibility(domNode: HTMLElement, oldVisibility: VisibilityState) {
if (domNode.style) {
domNode.style.display = oldVisibility.visibility;
}
let j = 0;
for (let i = 0; i < domNode.childNodes.length; i++) {
if (j < oldVisibility.children.length) {
let node = domNode.children.item(i);
if (node instanceof HTMLElement) {
this._restoreNodeVisibility(<HTMLElement> node, oldVisibility.children[j++]);
}
}
}
}
/**
* Unfortunately we can't just use event.target because often draggable shape on the canvas overlaps the target.
* We can easily find the element(s) at location, but only nodes :-( Unclear how to find links at location
* (bounding box of a link for testing is bad).
* The result of that is that links can only be the drop target when dragging from the palette currently.
* When DnDing shapes on the canvas drop target cannot be a link.
*
* Excluded views enables you to choose to filter some possible answers (useful in the case where elements are stacked
* - e.g. Drag-n-Drop)
*/
getTargetViewFromEvent(event: MouseEvent, x: number, y: number, excludeViews: Array<dia.CellView> = []): dia.CellView {
if (!x && !y) {
let l = this.paper.snapToGrid({x: event.clientX, y: event.clientY});
x = l.x;
y = l.y;
}
// TODO: See if next code paragraph is needed. Most likely it's just code executed for nothing
// let elements = this.graph.findModelsFromPoint(joint.g.point(x, y));
// let underMouse = elements.find(e => !_.isUndefined(excludeViews.find(x => x === this.paper.findViewByModel(e))));
// if (underMouse) {
// return underMouse;
// }
let oldVisibility = excludeViews.map(_x => this._hideNode(_x.el));
let targetElement = document.elementFromPoint(event.clientX, event.clientY);
excludeViews.forEach((excluded, i) => {
this._restoreNodeVisibility(excluded.el, oldVisibility[i]);
});
return this.paper.findView($(targetElement));
}
handleDnDFromPalette(dndEvent: Flo.DnDEvent) {
switch (dndEvent.type) {
case Flo.DnDEventType.DRAG:
this.handleDragFromPalette(dndEvent);
break;
case Flo.DnDEventType.DROP:
this.handleDropFromPalette(dndEvent);
break;
default:
break;
}
}
handleDragFromPalette(dnDEvent: Flo.DnDEvent) {
if (dnDEvent.view && !this.readOnlyCanvas) {
let location = this.paper.snapToGrid({x: dnDEvent.event.clientX, y: dnDEvent.event.clientY});
this.handleNodeDragging(dnDEvent.view, this.getTargetViewFromEvent(dnDEvent.event, location.x, location.y, [dnDEvent.view]), location.x, location.y, Constants.PALETTE_CONTEXT);
}
}
createNode(metadata: Flo.ElementMetadata, props: Map<string, any>, position: dia.Point): dia.Element {
return Shapes.Factory.createNode({
renderer: this.renderer,
paper: this.paper,
metadata: metadata,
props: props,
position: position
});
}
createLink(source: Flo.LinkEnd, target: Flo.LinkEnd, metadata: Flo.ElementMetadata, props: Map<string, any>): dia.Link {
return Shapes.Factory.createLink({
renderer: this.renderer,
paper: this.paper,
source: source,
target: target,
metadata: metadata,
props: props
});
}
handleDropFromPalette(event: Flo.DnDEvent) {
let cellview = event.view;
let evt = event.event;
if (this.paper.el === evt.target || $.contains(this.paper.el, evt.target)) {
if (this.readOnlyCanvas) {
this.setDragDescriptor(undefined);
} else {
let metadata = cellview.model.get('metadata');
let props = cellview.model.attr('props');
let position = this.paper.snapToGrid({x: evt.clientX, y: evt.clientY});
/* Calculate target element before creating the new
* element under mouse location. Otherwise target
* element would be the newly created element because
* it's under the mouse pointer
*/
let targetElement = this.getTargetViewFromEvent(evt, position.x, position.y, [ event.view ]);
let newNode = this.createNode(metadata, props, position);
let newView = this.paper.findViewByModel(newNode);
this.handleNodeDragging(newView, targetElement, position.x, position.y, Constants.PALETTE_CONTEXT);
this.handleNodeDropping();
}
}
}
private fitToContent(gridWidth: number, gridHeight: number, padding: number, opt: any) {
const paper = this.paper;
if (joint.util.isObject(gridWidth)) {
// first parameter is an option object
opt = gridWidth;
gridWidth = opt.gridWidth || 1;
gridHeight = opt.gridHeight || 1;
padding = opt.padding || 0;
} else {
opt = opt || {};
gridWidth = gridWidth || 1;
gridHeight = gridHeight || 1;
padding = padding || 0;
}
const paddingJson = joint.util.normalizeSides(padding);
// Calculate the paper size to accomodate all the graph's elements.
const bbox = joint.V(paper.viewport).getBBox();
const currentScale = paper.scale();
const currentTranslate = paper.translate();
bbox.x *= currentScale.sx;
bbox.y *= currentScale.sy;
bbox.width *= currentScale.sx;
bbox.height *= currentScale.sy;
let calcWidth = Math.max((bbox.width + bbox.x) / gridWidth, 1) * gridWidth;
let calcHeight = Math.max((bbox.height + bbox.y) / gridHeight, 1) * gridHeight;
let tx = 0;
let ty = 0;
if ((opt.allowNewOrigin === 'negative' && bbox.x < 0) || (opt.allowNewOrigin === 'positive' && bbox.x >= 0) || opt.allowNewOrigin === 'any') {
tx = (-bbox.x / gridWidth) * gridWidth;
tx += paddingJson.left;
} else if (opt.allowNewOrigin === 'same') {
tx = currentTranslate.tx;
}
calcWidth += tx;
if ((opt.allowNewOrigin === 'negative' && bbox.y < 0) || (opt.allowNewOrigin === 'positive' && bbox.y >= 0) || opt.allowNewOrigin === 'any') {
ty = (-bbox.y / gridHeight) * gridHeight;
ty += paddingJson.top;
} else if (opt.allowNewOrigin === 'same') {
ty = currentTranslate.ty;
}
calcHeight += ty;
calcWidth += paddingJson.right;
calcHeight += paddingJson.bottom;
// Make sure the resulting width and height are greater than minimum.
calcWidth = Math.max(calcWidth, opt.minWidth || 0);
calcHeight = Math.max(calcHeight, opt.minHeight || 0);
// Make sure the resulting width and height are lesser than maximum.
calcWidth = Math.min(calcWidth, opt.maxWidth || Number.MAX_VALUE);
calcHeight = Math.min(calcHeight, opt.maxHeight || Number.MAX_VALUE);
const dimensionChange = calcWidth !== paper.options.width || calcHeight !== paper.options.height;
const originChange = tx !== currentTranslate.tx || ty !== currentTranslate.ty;
// Change the dimensions only if there is a size discrepency or an origin change
if (originChange) {
paper.translate(tx, ty);
}
if (dimensionChange) {
paper.setDimensions(calcWidth, calcHeight);
}
}
autosizePaper(): void {
let parent = $('#paper-container', this.element.nativeElement);
const parentWidth = parent.innerWidth();
const parentHeight = parent.innerHeight();
this.fitToContent(this.gridSize, this.gridSize, this.paperPadding, {
minWidth: parentWidth - Flo.SCROLLBAR_WIDTH,
minHeight: parentHeight - Flo.SCROLLBAR_WIDTH,
allowNewOrigin: 'same'
});
}
fitToPage(): void {
let parent = $('#paper-container', this.element.nativeElement);
let minScale = this.minZoom / 100;
let maxScale = 2;
const parentWidth = parent.innerWidth();
const parentHeight = parent.innerHeight();
this.paper.scaleContentToFit({
padding: this.paperPadding,
minScaleX: minScale,
minScaleY: minScale,
maxScaleX: maxScale,
maxScaleY: maxScale,
fittingBBox: {x: 0, y: 0, width: parentWidth - Flo.SCROLLBAR_WIDTH, height: parentHeight - Flo.SCROLLBAR_WIDTH}
});
/**
* Size the canvas appropriately and allow origin movement
*/
this.fitToContent(this.gridSize, this.gridSize, this.paperPadding, {
minWidth: parentWidth,
minHeight: parentHeight,
maxWidth: parentWidth,
maxHeight: parentHeight,
allowNewOrigin: 'any'
});
}
get zoomPercent(): number {
return Math.round(this.paper.scale().sx * 100);
}
set zoomPercent(percent: number) {
if (!isNaN(percent)) {
if (percent < this.minZoom) {
percent = this.minZoom;
} else if (percent >= this.maxZoom) {
percent = this.maxZoom;
} else {
if (percent <= 0) {
percent = 0.00001;
}
}
this.paper.scale(percent / 100, percent / 100);
}
}
get gridSize(): number {
return this._gridSize;
}
set gridSize(size: number) {
if (!isNaN(size) && size >= 1) {
this._gridSize = size;
if (this.paper) {
this.paper.setGridSize(size);
}
}
}
validateContent(): Promise<any> {
return new Promise<void>(resolve => {
if (this.editor && this.editor.validate) {
return this.editor
.validate(this.graph, this.dsl, this.editorContext)
.then(allMarkers => {
this.graph.getCells()
.forEach((cell: dia.Cell) => this.markElement(cell, allMarkers.has(cell.id) ? allMarkers.get(cell.id) : []));
this.validationMarkers.emit(allMarkers);
this.contentValidated.emit(true);
resolve();
});
} else {
resolve();
}
});
}
markElement(cell: dia.Cell, markers: Array<Flo.Marker>) {
cell.set('markers', markers);
// Old legacy code below consider removing
let errorMessages = markers.map(m => m.message);
let errorCell = cell.getEmbeddedCells().find((e: dia.Cell) => e.attr('./kind') === Constants.ERROR_DECORATION_KIND);
if (errorCell) {
if (errorMessages.length === 0) {
errorCell.remove();
} else {
// Without rewrite we merge this list with existing errors
errorCell.attr('messages', errorMessages, {rewrite: true});
}
} else if (errorMessages.length > 0) {
let error = Shapes.Factory.createDecoration({
renderer: this.renderer,
paper: this.paper,
parent: cell,
kind: Constants.ERROR_DECORATION_KIND,
messages: errorMessages
});
if (error) {
const view = this.paper.findViewByModel(error);
view.setInteractivity(false);
}
}
}
doLayout(): Promise<void> {
if (this.renderer && this.renderer.layout) {
return this.renderer.layout(this.paper);
}
}
@Input()
set dsl(dslText: string) {
if (this._dslText !== dslText) {
this._dslText = dslText;
this.textToGraphEventEmitter.emit();
}
}
get dsl(): string {
return this._dslText;
}
/**
* Ask the server to parse the supplied text into a JSON graph of nodes and links,
* then update the view based on that new information.
*/
updateGraphRepresentation(): Promise<any> {
Logger.debug(`Updating graph to represent '${this._dslText}'`);
if (this.metamodel && this.metamodel.textToGraph) {
return this.metamodel.textToGraph(this.editorContext, this._dslText).then(() => {
this.textToGraphConversionCompleted.next();
return this.validateContent()
});
} else {
this.textToGraphConversionCompleted.next();
return this.validateContent();
}
}
updateTextRepresentation(): Promise<any> {
if (this.metamodel && this.metamodel.graphToText) {
return this.metamodel.graphToText(this.editorContext).then(text => {
if (this._dslText !== text) {
this._dslText = text;
this.dslChange.emit(text);
}
this.graphToTextConversionCompleted.next();
return this.validateContent();
})
.catch(error => {
// Validation may reveal why the graph couldn't be
// converted so let it run
this.graphToTextConversionCompleted.next();
return this.validateContent();
});
} else {
this.graphToTextConversionCompleted.next();
return this.validateContent();
}
}
initMetamodel() {
this.metamodel.load().then(data => {
this.updateGraphRepresentation();
let textSyncSubscription = this.graphToTextEventEmitter.pipe(debounceTime(100)).subscribe(() => {
if (this._graphToTextSyncEnabled) {
this.updateTextRepresentation();
}
});
this._disposables.add(Disposable.create(() => textSyncSubscription.unsubscribe()));
// Setup content validated event emitter. Emit not validated when graph to text conversion required
let graphValidatedSubscription1 = this.graphToTextEventEmitter.subscribe(() => this.contentValidated.emit(false));
this._disposables.add(Disposable.create(() => graphValidatedSubscription1.unsubscribe));
// let validationSubscription = this.validationEventEmitter.pipe(debounceTime(100)).subscribe(() => this.validateGraph());
// this._disposables.add(Disposable.create(() => validationSubscription.unsubscribe()));
let graphSyncSubscription = this.textToGraphEventEmitter.pipe(debounceTime(300)).subscribe(() => this.updateGraphRepresentation());
this._disposables.add(Disposable.create(() => graphSyncSubscription.unsubscribe()));
// Setup content validated event emitter. Emit not validated when text to graph conversion required
let graphValidatedSubscription2 = this.textToGraphEventEmitter.subscribe(() => this.contentValidated.emit(false));
this._disposables.add(Disposable.create(() => graphValidatedSubscription2.unsubscribe));
if (this.editor && this.editor.setDefaultContent) {
this.editor.setDefaultContent(this.editorContext, data);
}
});
}
initGraph() {
this.graph = new joint.dia.Graph();
this.graph.set('type', Constants.CANVAS_CONTEXT);
this.graph.set('paperPadding', this.paperPadding);
}
handleNodeCreation(node: dia.Element) {
node.on('change:size', this._resizeHandler);
node.on('change:position', this._resizeHandler);
if (node.get('metadata')) {
node.on('change:attrs', (cell: dia.Element, attrs: any, changeData: any) => {
let propertyPath = changeData ? changeData.propertyPath : undefined;
if (propertyPath) {
let propAttr = propertyPath.substr(propertyPath.indexOf('/') + 1);
if (propAttr.indexOf('props') === 0 ||
(this.renderer && this.renderer.isSemanticProperty && this.renderer.isSemanticProperty(propAttr, node))) {
this.performGraphToTextSyncing();
}
if (this.renderer && this.renderer.refreshVisuals) {
this.renderer.refreshVisuals(node, propAttr, this.paper);
}
}
});
node.on('change:metadata', (cell: dia.Element, attrs: any, changeData: any) => {
let propertyPath = changeData ? changeData.propertyPath : undefined;
if (propertyPath && this.renderer && this.renderer.refreshVisuals) {
this.renderer.refreshVisuals(node, propertyPath, this.paper);
}
});
}
node.on('change:markers', () => {
if (this.renderer && this.renderer.markersChanged) {
this.renderer.markersChanged(node, this.paper);
}
});
}
/**
* Forwards a link event occurrence to any handlers in the editor service, if they are defined. Event examples
* are 'change:source', 'change:target'.
*/
handleLinkEvent(event: string, link: dia.Link) {
if (this.renderer && this.renderer.handleLinkEvent) {
this.renderer.handleLinkEvent(this.editorContext, event, link);
}
}
handleLinkCreation(link: dia.Link) {
link.on('change:source', (l: dia.Link) => {
this.autosizePaper();
let newSourceId = l.get('source').id;
let oldSourceId = l.previous('source').id;
if (newSourceId !== oldSourceId) {
this.performGraphToTextSyncing();
}
this.handleLinkEvent('change:source', l);
});
link.on('change:target', (l: dia.Link) => {
this.autosizePaper();
let newTargetId = l.get('target').id;
let oldTargetId = l.previous('target').id;
if (newTargetId !== oldTargetId) {
this.performGraphToTextSyncing();
}
this.handleLinkEvent('change:target', l);
});
link.on('change:vertices', this._resizeHandler);
link.on('change:attrs', (cell: dia.Link, attrs: any, changeData: any) => {
let propertyPath = changeData ? changeData.propertyPath : undefined;
if (propertyPath) {
let propAttr = propertyPath.substr(propertyPath.indexOf('/') + 1);
if (propAttr.indexOf('props') === 0 ||
(this.renderer && this.renderer.isSemanticProperty && this.renderer.isSemanticProperty(propAttr, link))) {
let sourceId = link.get('source').id;
let targetId = link.get('target').id;
this.performGraphToTextSyncing();
}
if (this.renderer && this.renderer.refreshVisuals) {
this.renderer.refreshVisuals(link, propAttr, this.paper);
}
}
});
link.on('change:metadata', (cell: dia.Element, attrs: any, changeData: any) => {
let propertyPath = changeData ? changeData.propertyPath : undefined;
if (propertyPath && this.renderer && this.renderer.refreshVisuals) {
this.renderer.refreshVisuals(link, propertyPath, this.paper);
}
});
this.paper.findViewByModel(link).on('link:options', () => this.handleLinkEvent('options', link));
if (this.readOnlyCanvas) {
link.attr('.link-tools/display', 'none');
}
this.handleLinkEvent('add', link);
}
initGraphListeners() {
this.graph.on('add', (element: dia.Cell) => {
if (element instanceof joint.dia.Link) {
this.handleLinkCreation(<dia.Link> element);
} else if (element instanceof joint.dia.Element) {
this.handleNodeCreation(<dia.Element> element);
}
if (element.get('type') === joint.shapes.flo.NODE_TYPE || element.get('type') === joint.shapes.flo.LINK_TYPE) {
this.performGraphToTextSyncing();
}
this.autosizePaper();
});
this.graph.on('remove', (element: dia.Cell) => {
if (element instanceof joint.dia.Link) {
this.handleLinkEvent('remove', <dia.Link> element);
}
if (this.selection && this.selection.model === element) {
this.selection = undefined;
}
if (element.isLink()) {
window.setTimeout(() => this.performGraphToTextSyncing(), 100);
} else if (element.get('type') === joint.shapes.flo.NODE_TYPE) {
this.performGraphToTextSyncing();
}
this.autosizePaper();
});
// Set if link is fan-routed. Should be called before routing call
this.graph.on('change:vertices', (link: dia.Link, changed: any, opt: any) => {
if (opt.fanRouted) {
link.set('fanRouted', true);
} else {
link.unset('fanRouted');
}
});
// adjust vertices when a cell is removed or its source/target was changed
this.graph.on('add remove change:source change:target change:vertices change:position', _.partial(Utils.fanRoute, this.graph));
this.graph.on('startDeletion', (cell: dia.Cell) => {
if (this.editor && this.editor.preDelete) {
if (this.editor.preDelete(this.editorContext, this.selection.model)) {
cell.remove();
}
} else {
cell.remove();
}
});
}
initPaperListeners() {
// https://stackoverflow.com/questions/20463533/how-to-add-an-onclick-event-to-a-joint-js-element
this.paper.on('cell:pointerup', (cellView: dia.CellView) => {
if (!this.readOnlyCanvas) {
this.selection = cellView;
}
}
);
this.paper.on('blank:pointerdown', () => {
this.selection = undefined;
});
this.paper.on('scale', this._resizeHandler);
this.paper.on('all', function() {
if (Utils.isCustomPaperEvent(arguments)) {
arguments[2].trigger.apply(arguments[2], [arguments[0], arguments[1], arguments[3], arguments[4]]);
}
});
this.paper.on('dragging-node-over-canvas', (dndEvent: Flo.DnDEvent) => {
let location = this.paper.snapToGrid({x: dndEvent.event.clientX, y: dndEvent.event.clientY});
switch (dndEvent.type) {
case Flo.DnDEventType.DRAG:
this.handleNodeDragging(dndEvent.view, this.getTargetViewFromEvent(dndEvent.event, location.x, location.y, [ dndEvent.view ]), location.x, location.y, Constants.CANVAS_CONTEXT);
break;
case Flo.DnDEventType.DROP:
this.handleNodeDropping();
break;
default:
break;
}
});
// JointJS now no longer grabs focus if working in a paper element - crude...
// $('#flow-view', this.element.nativeElement).on('mousedown', () => {
// $('#palette-filter-textfield', this.element.nativeElement).focus();
// });
}
initPaper(): void {
let options: dia.Paper.Options = {
el: $('#paper', this.element.nativeElement),
gridSize: this._gridSize,
drawGrid: true,
model: this.graph,
elementView: this.renderer && this.renderer.getNodeView ? this.renderer.getNodeView() : joint.shapes.flo.ElementView/*joint.dia.ElementView*/,
linkView: this.renderer && this.renderer.getLinkView ? this.renderer.getLinkView() : joint.shapes.flo.LinkView,
// Enable link snapping within 25px lookup radius
snapLinks: { radius: 25 },
defaultLink: /*this.renderer && this.renderer.createDefaultLink ? this.renderer.createDefaultLink: new joint.shapes.flo.Link*/
(cellView: dia.CellView, magnet: SVGElement) => {
if (this.renderer && this.renderer.createLink) {
let linkEnd: Flo.LinkEnd = {
id: cellView.model.id
};
if (magnet) {
linkEnd.selector = cellView.getSelector(magnet, undefined);
}
if (magnet.getAttribute('port')) {
linkEnd.port = magnet.getAttribute('port');
}
if (magnet.getAttribute('port') === 'input') {
return this.renderer.createLink(undefined, linkEnd);
} else {
return this.renderer.createLink(linkEnd, undefined);
}
} else {
return new joint.shapes.flo.Link();
}
},
// decide whether to create a link if the user clicks a magnet
validateMagnet: (cellView: dia.CellView, magnet: SVGElement) => {
if (this.readOnlyCanvas) {
return false;
} else {
if (this.editor && this.editor.validatePort) {
return this.editor.validatePort(this.editorContext, cellView, magnet);
} else {
return true;
}
}
},
interactive: (cellView: dia.CellView, event: string) => {
if (this.readOnlyCanvas) {
return false;
} else {
if (this.editor && this.editor.interactive) {
if (typeof this.editor.interactive === 'function') {
// Type for interactive is wrong in JointJS have to cast to <any>
return <any>this.editor.interactive(cellView, event);
} else {
return this.editor.interactive
}
}
return true
}
},
highlighting: this.editor && this.editor.highlighting ? this.editor.highlighting : {
'default': {
name: 'addClass',
options: {
className: 'highlighted'
}
}
},
markAvailable: true
};
if (this.renderer && this.renderer.getLinkAnchorPoint) {
options.linkConnectionPoint = this.renderer.getLinkAnchorPoint;
}
if (this.editor && this.editor.validateLink) {
const self = this;
options.validateConnection = (cellViewS: dia.CellView, magnetS: SVGElement, cellViewT: dia.CellView, magnetT: SVGElement, end: 'source' | 'target', linkView: dia.LinkView) =>
self!.editor!.validateLink(this.editorContext, cellViewS, magnetS, cellViewT, magnetT, end === 'source', linkView);
}
// The paper is what will represent the graph on the screen
this.paper = new joint.dia.Paper(options);
this._disposables.add(Disposable.create(() => this.paper.remove()));
this.paper.options.highlighterNamespace['addParentClass'] = {
/**
* @param {joint.dia.CellView} cellView
* @param {Element} magnetEl
* @param {object=} opt
*/
highlight(cellView: dia.CellView, magnetEl: SVGElement, opt: any) {
opt = opt || {};
const className = opt.className || this.className;
joint.V(magnetEl.parentElement).addClass(className);
},
/**
* @param {joint.dia.CellView} cellView
* @param {Element} magnetEl
* @param {object=} opt
*/
unhighlight(cellView: dia.CellView, magnetEl: SVGElement, opt: any) {
opt = opt || {};
const className = opt.className || this.className;
joint.V(magnetEl.parentElement).removeClass(className);
}
};
}
updatePaletteReadyState(ready: boolean) {
this.paletteReady.next(ready);
}
} | the_stack |
const Marketplace = artifacts.require('./Marketplace')
const { toBN } = web3.utils
import { expectRevert, BN } from '@openzeppelin/test-helpers'
import { convertTokensToWei } from '../utils/tokens'
contract('Marketplace', ([contractDeployer, creator, buyer, secondBuyer]) => {
let marketplace
before(async () => {
marketplace = await Marketplace.new({ from: contractDeployer })
await marketplace.createCollectible('metadata', 20, { from: creator })
})
describe('marketplace deployment', async () => {
it('Deploys the Marketplace SC successfully.', async () => {
console.log('Address is ', marketplace.address)
assert.notEqual(marketplace.address, '', 'Should not be empty')
assert.notEqual(marketplace.address, 0x0, 'Should not be the 0x0 address')
assert.notEqual(marketplace.address, null, 'Should not be null')
assert.notEqual(marketplace.address, undefined, 'Should not be undefined')
})
})
describe('List a NFT.', async () => {
it('The token id 0 has not been listed.', async () => {
const hasBeenListed = await marketplace.hasBeenListed(1)
assert.equal(hasBeenListed, false, 'The NFT with token id 1 has not been listed yet.')
})
it('The NFT with token id 1 cannot be listed by anyone who doesn\'t own it.', async () => {
await expectRevert(marketplace.listItem(1, convertTokensToWei('5'), { from: contractDeployer }), 'Only the owner of the token id can call this function.')
await expectRevert(marketplace.listItem(1, convertTokensToWei('5'), { from: buyer }), 'Only the owner of the token id can call this function.')
})
it('Transfer the NFT to the Marketplace SC.', async () => {
const result = await marketplace.listItem(1, convertTokensToWei('5'), { from: creator })
assert.equal(result.logs.length, 3, 'Should trigger three events.')
//event Approval
assert.equal(result.logs[0].event, 'Approval', 'Should be the \'Approval\' event.')
assert.equal(result.logs[0].args.owner, creator, 'Should be the creator address.')
assert.equal(result.logs[0].args.approved, 0x0, 'Should log the address(0) to approve in order to clear previous approvals.')
assert.equal(result.logs[0].args.tokenId, 1, 'Should log the token id which is 1.')
//event Transfer
assert.equal(result.logs[1].event, 'Transfer', 'Should be the \'Transfer\' event.')
assert.equal(result.logs[1].args.from, creator, 'Should be the creator address.')
assert.equal(result.logs[1].args.to, marketplace.address, 'Should log the recipient which is the marketplace.')
assert.equal(result.logs[1].args.tokenId, 1, 'Should log the token id which is 1.')
//event ItemListed
assert.equal(result.logs[2].event, 'ItemListed', 'Should be the \'ItemListed\' event.')
assert.equal(result.logs[2].args.tokenId, 1, 'Should be the token id 1.')
assert.equal(result.logs[2].args.price, convertTokensToWei('5'), 'Should log the price which is 5 AVAX.')
assert.equal(result.logs[2].args.seller, creator, 'Should log the creator as the seller.')
})
it('The listing has the correct data.', async () => {
const listing = await marketplace.getListing(1)
assert.equal(listing['0'], convertTokensToWei('5'), 'The price is 5 AVAX.')
assert.equal(listing['1'], creator, 'The one who listed it is the creator.')
})
it('The Marketplace SC is now the owner of the NFT and not the seller.', async () => {
const ownerOfNFT = await marketplace.ownerOf(1)
assert.equal(ownerOfNFT, marketplace.address, 'The owner should be the marketplace.')
assert.notEqual(ownerOfNFT, creator, 'The owner should not be the creator.')
})
//Actually this can be skipped, as the owner is technically the smart contract at this point
it('The NFT with token id 1 cannot be listed again.', async () => {
await expectRevert.unspecified(marketplace.listItem(1, convertTokensToWei('5'), { from: creator }))
})
it('The token id 1 can be claimed back by the creator if not sold.', async () => {
const claimableBySeller = await marketplace.claimableByAccount(1)
assert.equal(claimableBySeller, creator, 'The NFT with token id 1 can be claimed by the creator if not sold.')
})
it('The token id 1 has been listed.', async () => {
const hasBeenListed = await marketplace.hasBeenListed(1)
assert.equal(hasBeenListed, true, 'The NFT with token id 1 has been listed.')
})
})
describe('Cancel the listing.', async () => {
it('The listing cannot be cancelled by an address that does not have the right to claim it.', async () => {
await expectRevert(marketplace.cancelListing(1, { from: contractDeployer }), 'Only the address that has listed the token can cancel the listing.')
await expectRevert(marketplace.cancelListing(1, { from: buyer }), 'Only the address that has listed the token can cancel the listing.')
})
it('Transfer the NFT back to the owner.', async () => {
const result = await marketplace.cancelListing(1, { from: creator })
assert.equal(result.logs.length, 3, 'Should trigger three events.')
//event Approval
assert.equal(result.logs[0].event, 'Approval', 'Should be the \'Approval\' event.')
assert.equal(result.logs[0].args.owner, marketplace.address, 'Should be the marketplace address.')
assert.equal(result.logs[0].args.approved, 0x0, 'Should log the address(0) to approve in order to clear previous approvals.')
assert.equal(result.logs[0].args.tokenId, 1, 'Should log the token id which is 1.')
//event Transfer
assert.equal(result.logs[1].event, 'Transfer', 'Should be the \'Transfer\' event.')
assert.equal(result.logs[1].args.from, marketplace.address, 'Should be the marketplace address.')
assert.equal(result.logs[1].args.to, creator, 'Should log the recipient that is the creator.')
assert.equal(result.logs[1].args.tokenId, 1, 'Should log the token id which is 1.')
//event ListingCancelled
assert.equal(result.logs[2].event, 'ListingCancelled', 'Should be the \'ListingCancelled\' event.')
assert.equal(result.logs[2].args.tokenId, 1, 'Should be the token id 1.')
assert.equal(result.logs[2].args.price, convertTokensToWei('5'), 'Should log the price which is 5 AVAX.')
assert.equal(result.logs[2].args.seller, creator, 'Should log the creator as the one who cancels the listing.')
})
it('The seller is now the owner of the NFT and not the Marketplace SC.', async () => {
const ownerOfNFT = await marketplace.ownerOf(1)
assert.equal(ownerOfNFT, creator, 'The owner should be the creator.')
assert.notEqual(ownerOfNFT, marketplace.address, 'The owner should not be the marketplace.')
})
it('The claimableByAccount mapping should be cleared.', async () => {
const claimableBySeller = await marketplace.claimableByAccount(1)
assert.equal(claimableBySeller, 0x0, 'The NFT with token id 1 cannot be claimed by anyone after its no longer listed.')
})
it('The listing should not exist anymore.', async () => {
const listing = await marketplace.getListing(1)
assert.equal(listing['0'], 0, 'The price is reset to 0.')
assert.equal(listing['1'], 0x0, 'The address(0) should be the one which owns the listing.')
})
it('The token id 1 is not listed anymore.', async () => {
const hasBeenListed = await marketplace.hasBeenListed(1)
assert.equal(hasBeenListed, false, 'The NFT with token id 1 is not listed anymore.')
})
})
describe('Buy a NFT.', async () => {
//Make sure to list the item again
before(async () => {
await marketplace.listItem(1, convertTokensToWei('5'), { from: creator })
})
it('You cannot buy an item that is not listed or does not exist.', async () => {
await expectRevert(marketplace.buyItem(2, { from: buyer }), 'The token needs to be listed in order to be bought.')
})
it('You need to pay the correct price of 5 AVAX.', async () => {
await expectRevert(marketplace.buyItem(1, { from: buyer, value: convertTokensToWei('4') }), 'You need to pay the correct price.')
})
//Define the balances to check later whether they've increased or decreased by the correct amount
let balanceOfCreatorBeforePurchase
it('Buy the NFT.', async () => {
balanceOfCreatorBeforePurchase = await web3.eth.getBalance(creator)
const result = await marketplace.buyItem(1, { from: buyer, value: convertTokensToWei('5') })
assert.equal(result.logs.length, 3, 'Should trigger three events.')
//event Approval
assert.equal(result.logs[0].event, 'Approval', 'Should be the \'Approval\' event.')
assert.equal(result.logs[0].args.owner, marketplace.address, 'Should be the marketplace address.')
assert.equal(result.logs[0].args.approved, 0x0, 'Should log the address(0) to approve in order to clear previous approvals.')
assert.equal(result.logs[0].args.tokenId, 1, 'Should log the token id which is 1.')
//event Transfer
assert.equal(result.logs[1].event, 'Transfer', 'Should be the \'Transfer\' event.')
assert.equal(result.logs[1].args.from, marketplace.address, 'Should be the marketplace address.')
assert.equal(result.logs[1].args.to, buyer, 'Should log the recipient that is the buyer.')
assert.equal(result.logs[1].args.tokenId, 1, 'Should log the token id which is 1.')
//event ItemBought
assert.equal(result.logs[2].event, 'ItemBought', 'Should be the \'ItemBought\' event.')
assert.equal(result.logs[2].args.tokenId, 1, 'Should be the token id 1.')
assert.equal(result.logs[2].args.price, convertTokensToWei('5'), 'Should log the price which is 5 AVAX.')
assert.equal(result.logs[2].args.buyer, buyer, 'Should log the buyer address as the buyer.')
})
it('The buyer is now the owner of the NFT and not the Marketplace SC.', async () => {
const ownerOfNFT = await marketplace.ownerOf(1)
assert.equal(ownerOfNFT, buyer, 'The owner should be the buyer.')
assert.notEqual(ownerOfNFT, marketplace.address, 'The owner should not be the marketplace.')
})
it('The claimableByAccount mapping should be cleared.', async () => {
const claimableBySeller = await marketplace.claimableByAccount(1)
assert.equal(claimableBySeller, 0x0, 'The NFT with token id 1 cannot be claimed by anyone after its no longer listed.')
})
it('The listing should not exist anymore.', async () => {
const listing = await marketplace.getListing(1)
assert.equal(listing['0'], 0, 'The price is reset to 0.')
assert.equal(listing['1'], 0x0, 'The address(0) should be the one which owns the listing.')
})
it('The token id 1 is not listed anymore.', async () => {
const hasBeenListed = await marketplace.hasBeenListed(1)
assert.equal(hasBeenListed, false, 'The NFT with token id 1 should not be listed anymore.')
})
it('The item has the correct data.', async () => {
const item = await marketplace.getItem(1)
assert.notEqual(item['0'], creator, 'The owner should not be the creator.')
assert.equal(item['0'], buyer, 'The buyer is the owner now.')
assert.equal(item['1'], creator, 'The creator remains the creator address.')
assert.equal(item['2'], 20, 'The royalty is set to 20.')
})
it('The balances of creator and first buyer are correct.', async () => {
const balanceOfCreatorAfterPurchase = await web3.eth.getBalance(creator)
assert.equal(balanceOfCreatorAfterPurchase, toBN(balanceOfCreatorBeforePurchase).add(toBN(convertTokensToWei('5'))), 'The balance of the creator should be increased by 5 AVAX after the purchase.')
})
it('The balances of creator, first buyer who is now the seller and second buyer are correct.', async () => {
//List the item again, only this time by the new owner
await marketplace.listItem(1, convertTokensToWei('10'), { from: buyer })
const balanceOfBuyerBeforePurchase = await web3.eth.getBalance(buyer)
const balanceOfCreatorBeforePurchase = await web3.eth.getBalance(creator)
const balanceOfSecondBuyerBeforePurchase = await web3.eth.getBalance(secondBuyer)
await marketplace.buyItem(1, { from: secondBuyer, value: convertTokensToWei('10') })
const balanceOfSecondBuyerAfterPurchase = await web3.eth.getBalance(secondBuyer)
const isCorrectSecondBuyerBalanceDifference = toBN(balanceOfSecondBuyerAfterPurchase).add(toBN(convertTokensToWei('10'))).lt(toBN(balanceOfSecondBuyerBeforePurchase))
assert.equal(isCorrectSecondBuyerBalanceDifference, true, 'The balance of the second buyer should decrease by 10 AVAX plus gas paid.')
const balanceOfBuyerAfterPurchase = await web3.eth.getBalance(buyer)
const balanceOfCreatorAfterPurchase = await web3.eth.getBalance(creator)
assert.equal(balanceOfBuyerAfterPurchase, toBN(balanceOfBuyerBeforePurchase).add(toBN(convertTokensToWei('10')).mul(new BN('80')).div(new BN('100'))), 'The balance of the seller should increase by 80% of the sold amount.')
assert.equal(balanceOfCreatorAfterPurchase, toBN(balanceOfCreatorBeforePurchase).add(toBN(convertTokensToWei('10')).mul(new BN('20')).div(new BN('100'))), 'The balance of the creator should increase by 20% of the sold amount.')
})
})
}) | the_stack |
import * as urlLib from 'url';
// Node
import * as BBPromise from 'bluebird';
import PackageVersionCreateRequestApi = require('./packageVersionCreateRequestApi');
import { SfdxError, Messages } from '@salesforce/core';
Messages.importMessagesDirectory(__dirname);
import ux from 'cli-ux';
import Messages_old = require('../messages');
const messages = Messages_old();
const messagesPackaging = Messages.loadMessages('salesforce-alm', 'packaging');
const NOT_FOUND_MESSAGE = 'The requested resource does not exist';
const INVALID_TYPE_REGEX = /[\w]*(sObject type '[A-Za-z]*Package[2]?[A-Za-z]*' is not supported)[\w]*/im;
const ID_REGISTRY = [
{
prefix: '0Ho',
label: 'Package Id',
},
{
prefix: '05i',
label: 'Package Version Id',
},
{
prefix: '08c',
label: 'Package Version Create Request Id',
},
{
prefix: '04t',
label: 'Subscriber Package Version Id',
},
];
const LATEST_BUILD_NUMBER_TOKEN = 'LATEST';
const NEXT_BUILD_NUMBER_TOKEN = 'NEXT';
const RELEASED_BUILD_NUMBER_TOKEN = 'RELEASED';
const VERSION_NUMBER_SEP = '.';
const INSTALL_URL_BASE = 'https://login.salesforce.com/packaging/installPackage.apexp?p0=';
// https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_soslsoql.htm
const SOQL_WHERE_CLAUSE_MAX_LENGTH = 4000;
const POLL_INTERVAL_SECONDS = 30;
const DEFAULT_PACKAGE_DIR = {
path: '',
package: '',
versionName: 'ver 0.1',
versionNumber: '0.1.0.NEXT',
default: true,
};
export = {
BY_PREFIX: (function () {
const byIds: any = {};
ID_REGISTRY.forEach((id) => {
byIds[id.prefix] = id;
});
return byIds;
})(),
BY_LABEL: (function () {
const byLabels: any = {};
ID_REGISTRY.forEach((id) => {
byLabels[id.label.replace(/ /g, '_').toUpperCase()] = id;
});
return byLabels;
})(),
validateId(idObj, value) {
if (!this.validateIdNoThrow(idObj, value)) {
const msg = messages.getMessage(
'invalidIdOrAlias',
[
Array.isArray(idObj) ? idObj.map((e) => e.label).join(' or ') : idObj.label,
value,
Array.isArray(idObj) ? idObj.map((e) => e.prefix).join(' or ') : idObj.prefix,
],
'packaging'
);
throw new Error(msg);
}
},
validateIdNoThrow(idObj, value) {
if (!value || (value.length !== 15 && value.length !== 18)) {
return false;
}
return Array.isArray(idObj) ? idObj.some((e) => value.startsWith(e.prefix)) : value.startsWith(idObj.prefix);
},
validateVersionNumber(versionNumberString, supportedBuildNumberToken, supportedBuildNumberToken2) {
if (!versionNumberString) {
throw new Error(messages.getMessage('errorMissingVersionNumber', [], 'packaging'));
}
// split into array of [major, minor, patch, build]
const versionNumber = versionNumberString.split(VERSION_NUMBER_SEP);
if (versionNumber.length !== 4) {
throw new Error(messages.getMessage('errorInvalidVersionNumber', versionNumberString, 'packaging'));
}
// build number can be a number or valid token
if (
Number.isNaN(parseInt(versionNumber[3])) &&
versionNumber[3] !== supportedBuildNumberToken &&
versionNumber[3] !== supportedBuildNumberToken2
) {
if (supportedBuildNumberToken2) {
throw new Error(
messages.getMessage(
'errorInvalidBuildNumberForKeywords',
[versionNumberString, supportedBuildNumberToken, supportedBuildNumberToken2],
'packaging'
)
);
} else {
throw new Error(
messages.getMessage('errorInvalidBuildNumber', [versionNumberString, supportedBuildNumberToken], 'packaging')
);
}
}
if (Number.isNaN(parseInt(versionNumber[1]))) {
throw new Error(messages.getMessage('errorInvalidMajorMinorNumber', [versionNumberString, 'minor'], 'packaging'));
}
if (Number.isNaN(parseInt(versionNumber[0]))) {
throw new Error(messages.getMessage('errorInvalidMajorMinorNumber', [versionNumberString, 'major'], 'packaging'));
}
return versionNumber;
},
async validatePatchVersion(force, org, versionNumberString, packageId) {
const query = `SELECT ContainerOptions FROM Package2 WHERE id ='${packageId}'`;
const queryResult = await force.toolingQuery(org, query);
if (queryResult.records === null || queryResult.records.length === 0) {
throw SfdxError.create('salesforce-alm', 'packaging', 'errorInvalidPackageId', [packageId]);
}
// Enforce a patch version of zero (0) for Locked packages only
if (queryResult.records[0].ContainerOptions === 'Locked') {
// Break-up version string into [major, minor, patch, build] array
const versionNumber = versionNumberString.split(VERSION_NUMBER_SEP);
if (versionNumber.length !== 4) {
throw new Error(messages.getMessage('errorInvalidVersionNumber', versionNumberString, 'packaging'));
}
const patch = parseInt(versionNumber[2]);
if (Number.isNaN(patch) || patch !== 0) {
throw new Error(messages.getMessage('errorInvalidPatchNumber', versionNumberString, 'packaging'));
}
}
},
// check that the provided url has a valid format
validUrl(url) {
try {
// eslint-disable-next-line no-new
new urlLib.URL(url);
return true;
} catch (err) {
return false;
}
},
// determines if error is from malformed SubscriberPackageVersion query
// this is in place to allow cli to run against app version 214, where SPV queries
// do not require installation key
isErrorFromSPVQueryRestriction(err) {
return (
err.name === 'MALFORMED_QUERY' &&
err.message.includes('Implementation restriction: You can only perform queries of the form Id')
);
},
isErrorPackageNotAvailable(err) {
return err.name === 'UNKNOWN_EXCEPTION' || err.name === 'PACKAGE_UNAVAILABLE';
},
// overwrites error message under certain conditions
massageErrorMessage(err) {
if (err.name === 'INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST') {
err['message'] = messages.getMessage('invalidPackageTypeMessage', [], 'packaging');
}
if (
err.name === 'MALFORMED_ID' &&
(err.message.includes('Version ID') || err.message.includes('Version Definition ID'))
) {
err['message'] = messages.getMessage('malformedPackageVersionIdMessage', [], 'packaging');
}
if (err.name === 'MALFORMED_ID' && err.message.includes('Package2 ID')) {
err['message'] = messages.getMessage('malformedPackageIdMessage', [], 'packaging');
}
// remove references to Second Generation
if (err.message.includes('Second Generation ')) {
err['message'] = err.message.replace('Second Generation ', '');
}
return err;
},
// applies actions to common package errors
applyErrorAction(err) {
// append when actions already exist
const actions = [];
// include existing actions
if (err.action) {
actions.push(err.action);
}
// TODO:
// until next generation packaging is GA, wrap perm-based errors w/
// 'contact sfdc' action (REMOVE once GA'd)
if (
(err.name === 'INVALID_TYPE' && INVALID_TYPE_REGEX.test(err.message)) ||
(err.name === 'NOT_FOUND' && err.message === NOT_FOUND_MESSAGE)
) {
// contact sfdc customer service
actions.push(messages.getMessage('packageNotEnabledAction', [], 'packaging'));
}
if (err.name === 'INVALID_FIELD' && err.message.includes('Instance')) {
actions.push(messages.getMessage('packageInstanceNotEnabled', [], 'packaging'));
}
if (err.name === 'INVALID_FIELD' && err.message.includes('SourceOrg')) {
actions.push(messages.getMessage('packageSourceOrgNotEnabled', [], 'packaging'));
}
if (err.name === 'INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST') {
actions.push(messages.getMessage('invalidPackageTypeAction', [], 'packaging'));
}
if (
err.name === 'MALFORMED_ID' &&
err.message === messages.getMessage('malformedPackageIdMessage', [], 'packaging')
) {
actions.push(messages.getMessage('malformedPackageIdAction', [], 'packaging'));
}
if (
err.name === 'MALFORMED_ID' &&
err.message === messages.getMessage('malformedPackageVersionIdMessage', [], 'packaging')
) {
actions.push(messages.getMessage('malformedPackageVersionIdAction', [], 'packaging'));
}
if (
(err.message.includes(this.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID.label) && err.message.includes('is invalid')) ||
err.name === 'INVALID_ID_FIELD' ||
(err.name === 'INVALID_INPUT' && err.message.includes('Verify you entered the correct ID')) ||
err.name === 'MALFORMED_ID'
) {
actions.push(messages.getMessage('idNotFoundAction', [], 'packaging'));
}
if (actions.length > 0) {
err['action'] = actions.join('\n');
}
return err;
},
/**
* Given a subscriber package version ID (04t) or package version ID (05i), return the package version ID (05i)
*
* @param versionId The suscriber package version ID
* @param force For tooling query
* @param org For tooling query
*/
getPackageVersionId(versionId, force, org) {
// if it's already a 05i return it, otherwise query for it
if (!versionId || versionId.startsWith(this.BY_LABEL.PACKAGE_VERSION_ID.prefix)) {
return versionId;
}
const query = `SELECT Id FROM Package2Version WHERE SubscriberPackageVersionId = '${versionId}'`;
return force.toolingQuery(org, query).then((queryResult) => {
if (!queryResult || !queryResult.totalSize) {
throw new Error(
messages.getMessage(
'errorInvalidIdNoMatchingVersionId',
[this.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID.label, versionId, this.BY_LABEL.PACKAGE_VERSION_ID.label],
'packaging'
)
);
}
return queryResult.records[0].Id;
});
},
/**
* Given 0Ho the package type type (Managed, Unlocked, Locked(deprecated?))
*
* @param package2Id the 0Ho
* @param force For tooling query
* @param org For tooling query
* @throws Error with message when package2 cannot be found
*/
async getPackage2Type(package2Id: string, force: any, org: any): Promise<string> {
const query = `SELECT ContainerOptions FROM Package2 WHERE id ='${package2Id}'`;
const queryResult = await force.toolingQuery(org, query);
if (!queryResult || queryResult.records === null || queryResult.records.length === 0) {
throw SfdxError.create('salesforce-alm', 'packaging', 'errorInvalidPackageId', [package2Id]);
}
return queryResult.records[0].ContainerOptions;
},
/**
* Given 04t the package type type (Managed, Unlocked, Locked(deprecated?))
*
* @param package2VersionId the 04t
* @param force For tooling query
* @param org For tooling query
* @param installKey For tooling query, if an install key is applicable to the package version it must be passed in the queries
* @throws Error with message when package2 cannot be found
*/
async getPackage2TypeBy04t(package2VersionId: string, force: any, org: any, installKey: any): Promise<string> {
let query = `SELECT Package2ContainerOptions FROM SubscriberPackageVersion WHERE id ='${package2VersionId}'`;
if (installKey) {
const escapedInstallationKey = installKey.replace(/\\/g, '\\\\').replace(/\'/g, "\\'");
query += ` AND InstallationKey ='${escapedInstallationKey}'`;
}
const queryResult = await force.toolingQuery(org, query);
if (!queryResult || queryResult.records === null || queryResult.records.length === 0) {
throw SfdxError.create('salesforce-alm', 'packaging', 'errorInvalidPackageId', [package2VersionId]);
}
return queryResult.records[0].Package2ContainerOptions;
},
/**
* Given a package version ID (05i) or subscriber package version ID (04t), return the subscriber package version ID (04t)
*
* @param versionId The suscriber package version ID
* @param force For tooling query
* @param org For tooling query
*/
getSubscriberPackageVersionId(versionId, force, org) {
// if it's already a 04t return it, otherwise query for it
if (!versionId || versionId.startsWith(this.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID.prefix)) {
return versionId;
}
const query = `SELECT SubscriberPackageVersionId FROM Package2Version WHERE Id = '${versionId}'`;
return force.toolingQuery(org, query).then((queryResult) => {
if (!queryResult || !queryResult.totalSize) {
throw new Error(
messages.getMessage(
'errorInvalidIdNoMatchingVersionId',
[this.BY_LABEL.PACKAGE_VERSION_ID.label, versionId, this.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID.label],
'packaging'
)
);
}
return queryResult.records[0].SubscriberPackageVersionId;
});
},
/**
* Get the ContainerOptions for the specified Package2 (0Ho) IDs.
*
* @return Map of 0Ho id to container option api value
* @param poackage2Ids The list of package IDs
* @param force For tooling query
* @param org For tooling query
*/
// eslint-disable-next-line @typescript-eslint/require-await
async getContainerOptions(package2Ids, force, org) {
const results = new Map();
if (!package2Ids || package2Ids.length === 0) {
return results;
}
const query = 'SELECT Id, ContainerOptions FROM Package2 WHERE Id IN (%IDS%)';
return this.queryWithInConditionChunking(query, package2Ids, '%IDS%', force, org).then((records) => {
if (records && records.length > 0) {
records.forEach((record) => {
results.set(record.Id, record.ContainerOptions);
});
}
return results;
});
},
/**
* Return the Package2Version.HasMetadataRemoved field value for the given Id (05i)
*
* @param packageVersionId package version ID (05i)
* @param force For tooling query
* @param org For tooling query
*/
async getHasMetadataRemoved(packageVersionId, force, org) {
const query = `SELECT HasMetadataRemoved FROM Package2Version WHERE Id = '${packageVersionId}'`;
const queryResult = await force.toolingQuery(org, query);
if (!queryResult || queryResult.records === null || queryResult.records.length === 0) {
throw new Error(
messages.getMessage(
'errorInvalidIdNoMatchingVersionId',
[this.BY_LABEL.PACKAGE_VERSION_ID.label, packageVersionId, this.BY_LABEL.PACKAGE_VERSION_ID.label],
'packaging'
)
);
}
return queryResult.records[0].HasMetadataRemoved;
},
/**
* Given a list of subscriber package version IDs (04t), return the associated version strings (e.g., Major.Minor.Patch.Build)
*
* @return Map of subscriberPackageVersionId to versionString
* @param versionIds The list of suscriber package version IDs
* @param force For tooling query
* @param org For tooling query
*/
// eslint-disable-next-line @typescript-eslint/require-await
async getPackageVersionStrings(subscriberPackageVersionIds, force, org) {
const results = new Map();
if (!subscriberPackageVersionIds || subscriberPackageVersionIds.length === 0) {
return results;
}
const query =
'SELECT SubscriberPackageVersionId, MajorVersion, MinorVersion, PatchVersion, BuildNumber FROM Package2Version WHERE SubscriberPackageVersionId IN (%IDS%)';
return this.queryWithInConditionChunking(query, subscriberPackageVersionIds, '%IDS%', force, org).then(
(records) => {
if (records && records.length > 0) {
records.forEach((record) => {
const version = this.concatVersion(
record.MajorVersion,
record.MinorVersion,
record.PatchVersion,
record.BuildNumber
);
results.set(record.SubscriberPackageVersionId, version);
});
}
return results;
}
);
},
/**
* For queries with an IN condition, determine if the WHERE clause will exceed
* SOQL's 4000 character limit. Perform multiple queries as needed to stay below the limit.
*
* @return concatenated array of records returned from the resulting query(ies)
* @param query The full query to execute containing the replaceToken param in its IN clause
* @param items The IN clause items. A length-appropriate single-quoted comma-separated string chunk will be made from the items.
* @param replaceToken A placeholder in the query's IN condition that will be replaced with the chunked items
* @param force For tooling query
* @param org For tooling query
*/
async queryWithInConditionChunking(query, items, replaceToken, force, org) {
// eslint-disable-next-line @typescript-eslint/no-shadow
const SOQL_WHERE_CLAUSE_MAX_LENGTH = this.getSoqlWhereClauseMaxLength();
let records = [];
if (!query || !items || !replaceToken) {
return records;
}
const whereClause = query.substring(query.toLowerCase().indexOf('where'), query.length);
const inClauseItemsMaxLength = SOQL_WHERE_CLAUSE_MAX_LENGTH - whereClause.length - replaceToken.length;
let itemsQueried = 0;
while (itemsQueried < items.length) {
const chunkCount = this.getInClauseItemsCount(items, itemsQueried, inClauseItemsMaxLength);
const itemsStr = "'" + items.slice(itemsQueried, itemsQueried + chunkCount).join("','") + "'";
const queryChunk = query.replace(replaceToken, itemsStr);
const result = await this.toolingQuery(queryChunk, force, org);
if (result && result.length > 0) {
records = records.concat(result);
}
itemsQueried += chunkCount;
}
return records;
},
/**
* Returns the number of items that can be included in a quoted comma-separated string (e.g., "'item1','item2'") not exceeding maxLength
*/
getInClauseItemsCount(items, startIndex, maxLength) {
let resultLength = 0;
let includedCount = 0;
while (startIndex + includedCount < items.length) {
let itemLength = 0;
if (items[startIndex + includedCount]) {
itemLength = items[startIndex + includedCount].length + 3; // 3 = length of '',
if (resultLength + itemLength > maxLength) {
// the limit has been exceeded, return the current count
return includedCount;
}
}
includedCount++;
resultLength += itemLength;
}
return includedCount;
},
/**
* Execute a tooling query
*/
// eslint-disable-next-line @typescript-eslint/require-await
async toolingQuery(query, force, org) {
return force.toolingQuery(org, query).then((queryResult) => queryResult.records);
},
/**
* Return a version string in Major.Minor.Patch.Build format, using 0 for any emtpy part
*/
concatVersion(major, minor, patch, build) {
return [major ? major : '0', minor ? minor : '0', patch ? patch : '0', build ? build : '0'].join('.');
},
/**
* Given a package descriptor, return the ancestor ID.
*
* @param packageDescriptorJson JSON for packageDirectories element in sfdx-project.json
* @param force For tooling query
* @param org For tooling query
*/
getAncestorId(packageDescriptorJson, force, org) {
return Promise.resolve().then(async () => {
let ancestorId = '';
// ancestorID can be alias, 05i, or 04t;
// validate and convert to 05i, as needed
if (packageDescriptorJson.ancestorId) {
ancestorId = this.getPackageIdFromAlias(packageDescriptorJson.ancestorId, force);
this.validateId([this.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, this.BY_LABEL.PACKAGE_VERSION_ID], ancestorId);
ancestorId = await this.getPackageVersionId(ancestorId, force, org);
}
if (!packageDescriptorJson.ancestorVersion) {
return ancestorId;
} else {
const regNumbers = new RegExp('^[0-9]+$');
const versionNumber = packageDescriptorJson.ancestorVersion.split(VERSION_NUMBER_SEP);
if (
versionNumber.length < 3 ||
versionNumber.length > 4 ||
!versionNumber[0].match(regNumbers) ||
!versionNumber[1].match(regNumbers) ||
!versionNumber[2].match(regNumbers)
) {
throw new Error(
messages.getMessage('errorInvalidAncestorVersionFormat', packageDescriptorJson.ancestorVersion, 'packaging')
);
}
// If an id property is present, use it. Otherwise, look up the id from the package property.
const packageId = packageDescriptorJson.id
? packageDescriptorJson.id
: this.getPackageIdFromAlias(packageDescriptorJson.package, force);
const query =
'SELECT Id, IsReleased FROM Package2Version ' +
`WHERE Package2Id = '${packageId}' AND MajorVersion = ${versionNumber[0]} AND MinorVersion = ${versionNumber[1]} AND PatchVersion = ${versionNumber[2]}`;
let queriedAncestorId;
return force.toolingQuery(org, query).then((queryResult) => {
if (!queryResult || !queryResult.totalSize) {
throw new Error(
messages.getMessage(
'errorNoMatchingAncestor',
[packageDescriptorJson.ancestorVersion, packageId],
'packaging'
)
);
} else {
const releasedAncestor = queryResult.records.find((rec) => rec.IsReleased === true);
if (!releasedAncestor) {
throw new Error(
messages.getMessage('errorAncestorNotReleased', [packageDescriptorJson.ancestorVersion], 'packaging')
);
} else {
queriedAncestorId = releasedAncestor.Id;
}
}
// check for discrepancy between queried ancestorId and descriptor's ancestorId
if (
Object.prototype.hasOwnProperty.call(packageDescriptorJson, 'ancestorId') &&
ancestorId !== queriedAncestorId
) {
throw new Error(
messages.getMessage(
'errorAncestorIdVersionMismatch',
[packageDescriptorJson.ancestorVersion, packageDescriptorJson.ancestorId],
'packaging'
)
);
}
return queriedAncestorId;
});
}
});
},
getConfigPackageDirectories(context) {
return context.org.force.config.getConfigContent().packageDirectories;
},
getConfigPackageDirectory(packageDirs, lookupProperty, lookupValue) {
let packageDir;
if (packageDirs) {
packageDir = packageDirs.find((x) => x[lookupProperty] === lookupValue);
}
return packageDir;
},
/**
* Given a packageAlias, attempt to return the associated id from the config
*
* @param packageAlias string representing a package alias
* @param force for obtaining the project config
* @returns the associated id or the arg given.
*/
getPackageIdFromAlias(packageAlias, force) {
const configContent = force.config.getConfigContent();
const packageAliases = configContent.packageAliases;
// if there are no aliases defined, return
if (!packageAliases) {
return packageAlias;
}
// return alias if it exists, otherwise return what was passed in
return packageAliases[packageAlias] || packageAlias;
},
/**
* @param stringIn pascal or camel case string
* @returns space delimited and lower-cased (except for 1st char) string (e.g. in "AbcdEfghIj" => "Abcd efgh ij")
*/
convertCamelCaseStringToSentence(stringIn) {
function upperToSpaceLower(match, offset) {
return offset > 0 ? ' ' + match.toLowerCase() : '' + match;
}
return stringIn.replace(/[A-Z]/g, upperToSpaceLower);
},
/**
* Given a package id, attempt to return the associated aliases from the config
*
* @param packageid string representing a package id
* @param force for obtaining the project config
* @returns an array of alias for the given id.
*/
getPackageAliasesFromId(packageId, force) {
const configContent = force.config.getConfigContent();
const packageAliases = configContent.packageAliases;
// if there are no aliases defined, return undefined
if (!packageAliases) {
return [];
}
// otherwise check for a matching alias
const matchingAliases = Object.entries(packageAliases).filter((alias) => alias[1] === packageId);
return matchingAliases.map((alias) => alias[0]);
},
async findOrCreatePackage2(seedPackage: string, force, org) {
const query = `SELECT Id FROM Package2 WHERE ConvertedFromPackageId = '${seedPackage}'`;
const queryResult = await force.toolingQuery(org, query);
const records = queryResult.records;
if (records && records.length > 1) {
const ids = records.map((r) => r.Id);
throw new Error(messages.getMessage('errorMoreThanOnePackage2WithSeed', ids, 'package_convert'));
}
if (records && records.length === 1) {
// return the package2 object
return records[0].Id;
}
// Need to create a new Package2
const subQuery = `SELECT Name, Description, NamespacePrefix FROM SubscriberPackage WHERE Id = '${seedPackage}'`;
const subscriberResult = await force.toolingQuery(org, subQuery);
const subscriberRecords = subscriberResult.records;
if (!subscriberRecords || subscriberRecords.length <= 0) {
throw new Error(messages.getMessage('errorNoSubscriberPackageRecord', [seedPackage], 'package_convert'));
}
const request: any = {
Name: subscriberRecords[0].Name,
Description: subscriberRecords[0].Description,
NamespacePrefix: subscriberRecords[0].NamespacePrefix,
ContainerOptions: 'Managed',
ConvertedFromPackageId: seedPackage,
};
const createResult = await force.toolingCreate(org, 'Package2', request);
if (!createResult.success) {
throw new Error(createResult.errors);
}
return createResult.id;
},
_getPackageVersionCreateRequestApi(force, org) {
return new PackageVersionCreateRequestApi(force, org);
},
pollForStatusWithInterval(context, id, retries, packageId, logger, withProject, force, org, interval) {
const STATUS_ERROR = 'Error';
const STATUS_SUCCESS = 'Success';
const STATUS_UNKNOWN = 'Unknown';
const pvcrApi = this._getPackageVersionCreateRequestApi(force, org);
return pvcrApi.byId(id).then(async (results) => {
if (this._isStatusEqualTo(results, [STATUS_SUCCESS, STATUS_ERROR])) {
// complete
if (this._isStatusEqualTo(results, [STATUS_SUCCESS])) {
// success
// for Managed packages with removed metadata, output a warning
if (results[0].HasMetadataRemoved === true) {
ux.warn(messages.getMessage('hasMetadataRemovedWarning', [], 'package_version_create'));
}
// update sfdx-project.json
if (withProject && !process.env.SFDX_PROJECT_AUTOUPDATE_DISABLE_FOR_PACKAGE_VERSION_CREATE) {
const query = `SELECT MajorVersion, MinorVersion, PatchVersion, BuildNumber FROM Package2Version WHERE Id = '${results[0].Package2VersionId}'`;
const package2VersionVersionString = await force.toolingQuery(org, query).then((pkgQueryResult) => {
const record = pkgQueryResult.records[0];
return `${record.MajorVersion}.${record.MinorVersion}.${record.PatchVersion}-${record.BuildNumber}`;
});
const newConfig = await this._generatePackageAliasEntry(
context,
results[0].SubscriberPackageVersionId,
package2VersionVersionString,
context.flags.branch,
packageId
);
await this._writeProjectConfigToDisk(context, newConfig, logger);
}
return results[0];
} else {
let status = 'Unknown Error';
if (results && results.length > 0 && results[0].Error.length > 0) {
const errors = [];
// for multiple errors, display one per line prefixed with (x)
if (results[0].Error.length > 1) {
results[0].Error.forEach((error) => {
errors.push(`(${errors.length + 1}) ${error}`);
});
errors.unshift(messagesPackaging.getMessage('version_create.multipleErrors'));
}
status = errors.length !== 0 ? errors.join('\n') : results[0].Error;
}
throw new Error(status);
}
} else {
if (retries > 0) {
// poll/retry
let currentStatus = STATUS_UNKNOWN;
if (results && results.length > 0) {
currentStatus = results[0].Status;
}
logger.log(
`Request in progress. Sleeping ${interval} seconds. Will wait a total of ${
interval * retries
} more seconds before timing out. Current Status='${this.convertCamelCaseStringToSentence(currentStatus)}'`
);
return BBPromise.delay(interval * 1000).then(() =>
this.pollForStatusWithInterval(
context,
id,
retries - 1,
packageId,
logger,
withProject,
force,
org,
interval
)
);
} else {
// Timed out
}
}
return results;
});
},
pollForStatus(context, id, retries, packageId, logger, withProject, force, org) {
return this.pollForStatusWithInterval(
context,
id,
retries,
packageId,
logger,
withProject,
force,
org,
this.POLL_INTERVAL_SECONDS
);
},
/**
* Writes objects specified in the config to the sfdx-project.json file on disk.
*
* @param context
* @private
*/
_writeProjectConfigToDisk(context, config, logger) {
try {
// write it to sfdx-project.json
return context.org.force.config
.setWorkspaceConfigContent(context.org.force.config.getProjectPath(), config)
.then(() => {
logger.log(messages.getMessage('updatedSfdxProject', null, 'packaging'));
})
.catch((err) => {
logger.warnUser(
context,
messages.getMessage('errorSfdxProjectFileWrite', [JSON.stringify(config, null, 4), err], 'packaging')
);
});
} catch (err) {
logger.log(err.stack);
logger.warnUser(
context,
messages.getMessage('errorSfdxProjectFileWrite', [JSON.stringify(config, null, 4), err], 'packaging')
);
return Promise.reject(err);
}
},
/**
* Generate package alias json entry for this package version that can be written to sfdx-project.json
*
* @param context
* @param packageVersionId 04t id of the package to create the alias entry for
* @param packageVersionNumber that will be appended to the package name to form the alias
* @param packageId the 0Ho id
* @private
*/
async _generatePackageAliasEntry(context, packageVersionId, packageVersionNumber, branch, packageId) {
const configContent = context.org.force.config.getConfigContent();
const packageAliases = configContent.packageAliases || {};
const aliasForPackageId = this.getPackageAliasesFromId(packageId, context.org.force);
let packageName;
if (!aliasForPackageId || aliasForPackageId.length === 0) {
const query = `SELECT Name FROM Package2 WHERE Id = '${packageId}'`;
packageName = await context.org.force.toolingQuery(context.org, query).then((pkgQueryResult) => {
const record = pkgQueryResult.records[0];
return record.Name;
});
} else {
packageName = aliasForPackageId[0];
}
const packageAlias = branch
? `${packageName}@${packageVersionNumber}-${branch}`
: `${packageName}@${packageVersionNumber}`;
packageAliases[packageAlias] = packageVersionId;
return { packageAliases };
},
/**
* Return true if the queryResult.records[0].Status is equal to one of the values in statuses.
*
* @param results to examine
* @param statuses array of statuses to look for
* @returns {boolean} if one of the values in status is found.
*/
_isStatusEqualTo(results, statuses?) {
if (!results || results.length <= 0) {
return false;
}
const record = results[0];
for (let i = 0, len = statuses.length; i < len; i++) {
const status = statuses[i];
if (record.Status === status) {
return true;
}
}
return false;
},
// added for unit testing
getSoqlWhereClauseMaxLength() {
return this.SQL_WHERE_CLAUSE_MAX_LENGTH;
},
LATEST_BUILD_NUMBER_TOKEN,
NEXT_BUILD_NUMBER_TOKEN,
RELEASED_BUILD_NUMBER_TOKEN,
VERSION_NUMBER_SEP,
INSTALL_URL_BASE,
DEFAULT_PACKAGE_DIR,
SOQL_WHERE_CLAUSE_MAX_LENGTH,
POLL_INTERVAL_SECONDS,
}; | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import { deepStrictEqual as eq, notDeepStrictEqual as neq, ok } from 'assert';
import sinon = require('sinon');
import TweetWindow from '../../main/window';
import Ipc from '../../main/ipc';
import { appDir, reset } from './mock';
type Spy = sinon.SinonSpy;
const { ipcMain, dialog, shell, app } = require('electron') as any; // mocked
function findCall(spy: Spy, pred: (call: sinon.SinonSpyCall) => boolean): sinon.SinonSpyCall {
const calls = spy.getCalls();
const call = calls.find(pred);
ok(call, JSON.stringify(calls));
return call;
}
describe('TweetWindow', function () {
beforeEach(reset);
after(function () {
const config = path.join(appDir, 'config.json');
try {
fs.unlinkSync(config);
} catch (e) {
// ignore
}
});
it('initializes screen name at constructor', function () {
const dummy = {} as any;
for (const n of [undefined, 'foo', '@foo']) {
const w = new TweetWindow(n, dummy, dummy, dummy, dummy);
const expected = n === undefined ? undefined : 'foo';
eq(w.screenName, expected);
}
});
it('opens window for new tweet with no query', async function () {
const ipc = new Ipc();
const w = new TweetWindow('@foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const win = (w as any).win;
neq(win, null);
// Default properties
eq(win.opts.width, 600);
eq(win.opts.height, 600);
eq(win.opts.autoHideMenuBar, true);
const contents = win.webContents;
eq(contents.url, 'https://mobile.twitter.com/compose/tweet');
eq(contents.send.getCall(0).args, ['tweetapp:screen-name', 'foo']);
ok(contents.session.webRequest.onCompleted.calledOnce);
});
it('opens window multiple times', async function () {
const ipc = new Ipc();
const w = new TweetWindow('@foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const win = (w as any).win;
neq(win, null);
const contents = win.webContents;
for (let i = 0; i < 10; i++) {
const willOpen = w.openNewTweet();
contents.emit('dom-ready');
await willOpen;
}
const callArgs = contents.send
.getCalls()
.map((c: any) => c.args)
.filter((a: string[]) => a[0] === 'tweetapp:open');
for (const args of callArgs) {
eq(args[1], 'https://mobile.twitter.com/compose/tweet');
}
});
it('opens window for new tweet with hashtags', async function () {
const ipc = new Ipc();
const opts = {
hashtags: ['foo', 'bar'],
text: '',
};
const w = new TweetWindow('@foo', {}, ipc, opts, {} as any);
await w.openNewTweet();
const win = (w as any).win;
neq(win, null);
const contents = win.webContents;
eq(contents.url, 'https://mobile.twitter.com/compose/tweet?hashtags=foo%2Cbar');
});
it('opens window for new tweet with text', async function () {
const ipc = new Ipc();
const w = new TweetWindow('@foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet('this is test');
const win = (w as any).win;
neq(win, null);
const contents = win.webContents;
eq(contents.url, 'https://mobile.twitter.com/compose/tweet?text=this%20is%20test');
});
it('opens window for reply to previous tweet', async function () {
const ipc = new Ipc();
const w = new TweetWindow('@foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const win = (w as any).win;
neq(win, null);
const contents = win.webContents;
// Get IPC listener for 'tweetapp:prev-tweet-id'
let call = findCall(ipcMain.on, c => c.args[0] === 'tweetapp:prev-tweet-id');
const listener = call.args[1];
listener(null, '114514');
const opened = w.openReply();
contents.emit('dom-ready');
await opened;
ok(contents.send.called);
call = findCall(contents.send, c => c.args[0] === 'tweetapp:open');
const url = call.args[1];
eq(url, 'https://mobile.twitter.com/compose/tweet?in_reply_to=114514');
// Open tweet window again
await w.openNewTweet();
eq(contents.url, 'https://mobile.twitter.com/compose/tweet');
});
it('opens window for reply to previous tweet with text', async function () {
const ipc = new Ipc();
const w = new TweetWindow('@foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const win = (w as any).win;
neq(win, null);
const contents = win.webContents;
w.prevTweetId = '114514';
const opened = w.openReply('this is text');
contents.emit('dom-ready');
await opened;
ok(contents.send.called);
const call = findCall(contents.send, c => c.args[0] === 'tweetapp:open');
const url = call.args[1];
eq(url, 'https://mobile.twitter.com/compose/tweet?text=this%20is%20text&in_reply_to=114514');
});
it('shows dialog to require default_account config when no screen name is set and reply is requested', async function () {
const ipc = new Ipc();
const w = new TweetWindow(undefined, {}, ipc, { text: '' }, {} as any);
eq(w.screenName, undefined);
const willOpenAfterDialogClosed = w.openReply();
ok(dialog.showMessageBox.calledOnce);
const call = dialog.showMessageBox.lastCall;
const [opts] = call.args;
eq(opts.title, 'Config is required');
await willOpenAfterDialogClosed;
eq(shell.openPath.callCount, 1);
const file = shell.openPath.lastCall.args[0];
ok(file.endsWith('config.json'), file);
});
it('shows dialog to require default_account config and do nothing when clicking OK', async function () {
// index of buttons. emulate 'OK' button was pressed
dialog.showMessageBox = sinon.fake.returns(Promise.resolve({ response: 1 }));
const ipc = new Ipc();
const w = new TweetWindow(undefined, {}, ipc, { text: '' }, {} as any);
eq(w.screenName, undefined);
const willOpenAfterDialogClosed = w.openReply();
ok(dialog.showMessageBox.calledOnce);
const call = dialog.showMessageBox.lastCall;
const [opts] = call.args;
eq(opts.title, 'Config is required');
await willOpenAfterDialogClosed;
eq(shell.openPath.callCount, 0);
});
it('shows dialog to notify a new tweet must be posted before reply', async function () {
const ipc = new Ipc();
const w = new TweetWindow('foo', {}, ipc, { text: '' }, {} as any);
const willOpenAfterDialogClosed = w.openReply();
ok(dialog.showMessageBox.calledOnce);
const call = dialog.showMessageBox.lastCall;
const [opts] = call.args;
eq(opts.title, 'Cannot reply to previous tweet');
await willOpenAfterDialogClosed;
});
it('closes window and cleanup IPC receiver', async function () {
const ipc: any = new Ipc();
ipc.detach = sinon.fake();
ipc.forget = sinon.fake();
const w = new TweetWindow('@foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const contents = (w as any).win.webContents;
await w.close();
eq((w as any).win, null);
ok(ipc.detach.called);
ok(ipc.forget.called);
if (process.platform === 'darwin') {
ok(app.hide.called);
}
eq(ipc.detach.lastCall.args[0], contents);
const calls = ipc.forget.getCalls();
ok(calls.some((c: any) => c.args[0] === 'tweetapp:prev-tweet-id'));
ok(calls.some((c: any) => c.args[0] === 'tweetapp:online-status'));
await w.didClose;
await w.close();
});
it('prepare next tweet when action after tweet is tweet or reply', async function () {
for (const action of ['new tweet', 'reply previous'] as const) {
const config = {
after_tweet: action,
};
const ipc = new Ipc();
const w = new TweetWindow('foo', config, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const contents = (w as any).win.webContents;
const call = findCall(contents.send, c => c.args[0] === 'tweetapp:action-after-tweet');
ok(call);
eq(call.args[1], action);
ok(contents.session.webRequest.onCompleted.called);
const callback = contents.session.webRequest.onCompleted.lastCall.args[1];
callback({
url: 'https://mobile.twitter.com/i/api/graphql/hoge/CreateTweet',
statusCode: 200,
method: 'POST',
fromCache: false,
});
const ipcCall = findCall(contents.send, c => c.args[0] === 'tweetapp:sent-tweet');
ok(ipcCall);
eq(ipcCall.args[1], 'https://mobile.twitter.com/compose/tweet');
}
});
it('closes window when action after tweet is close', async function () {
const config = {
after_tweet: 'close',
} as const;
const ipc = new Ipc();
const w = new TweetWindow('foo', config, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const contents = (w as any).win.webContents;
const call = findCall(contents.send, c => c.args[0] === 'tweetapp:action-after-tweet');
ok(call);
eq(call.args[1], 'close');
ok(contents.session.webRequest.onCompleted.called);
const callback = contents.session.webRequest.onCompleted.lastCall.args[1];
callback({
url: 'https://mobile.twitter.com/i/api/graphql/hoge/CreateTweet',
statusCode: 200,
method: 'POST',
fromCache: false,
});
eq((w as any).win, null);
await w.didClose;
});
it('quits when action after tweet is quit', async function () {
const config = {
after_tweet: 'quit',
} as const;
const ipc = new Ipc();
const w = new TweetWindow('foo', config, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const contents = (w as any).win.webContents;
const call = findCall(contents.send, c => c.args[0] === 'tweetapp:action-after-tweet');
ok(call);
eq(call.args[1], 'quit');
ok(contents.session.webRequest.onCompleted.called);
const callback = contents.session.webRequest.onCompleted.lastCall.args[1];
callback({
url: 'https://mobile.twitter.com/i/api/graphql/hoge/CreateTweet',
statusCode: 200,
method: 'POST',
fromCache: false,
});
await w.wantToQuit;
});
it('does nothing when /i/api/graphql/hoge/CreateTweet API fails', async function () {
const ipc = new Ipc();
const w = new TweetWindow('foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const contents = (w as any).win.webContents;
ok(contents.session.webRequest.onCompleted.called);
const callback = contents.session.webRequest.onCompleted.lastCall.args[1];
callback({
url: 'https://mobile.twitter.com/i/api/graphql/hoge/CreateTweet',
statusCode: 400,
method: 'POST',
fromCache: false,
});
neq((w as any).win, null);
ok(contents.url);
});
it('updates options for second instance', async function () {
const config = {
after_tweet: 'quit',
} as const;
const opts = {
hashtags: ['foo', 'bar'],
text: '',
};
const ipc = new Ipc();
const w = new TweetWindow('foo', config, ipc, opts, {} as any);
w.updateOptions({
afterTweet: 'quit',
hashtags: ['aaa'],
text: '',
});
await w.openNewTweet();
const contents = (w as any).win.webContents;
// hashtags was updated
eq(contents.url, 'https://mobile.twitter.com/compose/tweet?hashtags=aaa');
// action after tweet was updated
const call = findCall(contents.send, c => c.args[0] === 'tweetapp:action-after-tweet');
ok(call);
eq(call.args[1], 'quit');
});
it('reflects window configuration to BrowserWindow options', async function () {
const config: Config = {
window: {
width: 400,
zoom: 0.7,
auto_hide_menu_bar: false,
visible_on_all_workspaces: true,
},
};
const w = new TweetWindow('foo', config, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const opts = (w as any).win.opts;
eq(opts.width, 400);
eq(opts.height, 600);
eq(opts.autoHideMenuBar, false);
eq(opts.webPreferences.zoomFactor, 0.7);
ok((w as any).win.setVisibleOnAllWorkspaces.lastCall.args[0]);
});
it('shows "Network unavailable" page on offline and reopens page again when it is back to online', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const call = findCall(ipcMain.on, c => c.args[0] === 'tweetapp:online-status');
ok(call);
const callback = call.args[1];
callback('tweetapp:online-status', 'offline');
let url = (w as any).win.webContents.url;
ok(url.endsWith('offline.html'), url);
callback('tweetapp:online-status', 'online');
url = (w as any).win.webContents.url;
eq(url, 'https://mobile.twitter.com/compose/tweet');
});
it('does nothing when online status does not change on tweetapp:online-status message', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const call = findCall(ipcMain.on, c => c.args[0] === 'tweetapp:online-status');
ok(call);
const callback = call.args[1];
let prevUrl = (w as any).win.webContents.url;
callback('tweetapp:online-status', 'online');
eq((w as any).win.webContents.url, prevUrl);
callback('tweetapp:online-status', 'offline');
prevUrl = (w as any).win.webContents.url;
callback('tweetapp:online-status', 'offline');
eq((w as any).win.webContents.url, prevUrl);
});
it('does nothing when no window is opened on online status change', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const call = findCall(ipcMain.on, c => c.args[0] === 'tweetapp:online-status');
ok(call);
const callback = call.args[1];
await w.close();
eq((w as any).win, null);
callback('tweetapp:online-status', 'offline');
eq((w as any).win, null);
});
it('shows dialog to require default_account config when no screen name is set and showing previous tweet is requested', async function () {
const ipc = new Ipc();
const w = new TweetWindow(undefined, {}, ipc, { text: '' }, {} as any);
eq(w.screenName, undefined);
const dialogClosed = w.openPreviousTweet();
ok(dialog.showMessageBox.calledOnce);
const call = dialog.showMessageBox.lastCall;
const [opts] = call.args;
eq(opts.title, 'Config is required');
ok(opts.message.includes('open previous tweet page'), opts.message);
await dialogClosed;
});
it('shows dialog to notify a new tweet must be posted before opening previous tweet', async function () {
const ipc = new Ipc();
const w = new TweetWindow('foo', {}, ipc, { text: '' }, {} as any);
const dialogClosed = w.openPreviousTweet();
ok(dialog.showMessageBox.calledOnce);
const call = dialog.showMessageBox.lastCall;
const [opts] = call.args;
eq(opts.title, 'Cannot open previous tweet page');
await dialogClosed;
});
it('opens previous tweet page if screen name and previous tweet ID is set', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const win = (w as any).win;
const contents = win.webContents;
win.isMinimized = sinon.fake.returns(true);
w.prevTweetId = '114514';
const opened = w.openPreviousTweet();
contents.emit('dom-ready');
await opened;
ok(contents.send.called);
const call = (contents.send as Spy)
.getCalls()
.reverse()
.find(c => c.args[0] === 'tweetapp:open');
ok(call);
eq(call.args, ['tweetapp:open', 'https://mobile.twitter.com/foo/status/114514']);
ok(win.restore.called);
});
it('opens "New Tweet" page again after deleting a tweet to prevent back to home timeline', async function () {
const ipc = new Ipc();
const w = new TweetWindow('foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const contents = (w as any).win.webContents;
ok(contents.session.webRequest.onCompleted.called);
const callback = contents.session.webRequest.onCompleted.lastCall.args[1];
callback({
url: 'https://api.twitter.com/1.1/statuses/destroy.json',
statusCode: 200,
method: 'OPTIONS',
fromCache: false,
});
const ipcCall = findCall(contents.send, c => c.args[0] === 'tweetapp:open');
ok(ipcCall);
eq(ipcCall.args[1], 'https://mobile.twitter.com/compose/tweet');
eq(w.prevTweetId, null);
});
it('prevents navigation when the URL is not mobile.twitter.com', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const wc = (w as any).win.webContents;
let e = {
preventDefault: sinon.fake(),
};
wc.emit('will-navigate', e, 'https://example.com');
ok(e.preventDefault.called);
e = {
preventDefault: sinon.fake(),
};
wc.emit('will-navigate', e, 'https://mobile.twitter.com/foo/status/114514');
ok(!e.preventDefault.called);
});
it('prevents creating a new window', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const wc = (w as any).win.webContents;
const e = {
preventDefault: sinon.fake(),
};
wc.emit('new-window', e, 'https://mobile.twitter.com/foo/status/114514');
ok(e.preventDefault.called);
});
it('injects CSS to prevent some links from displaying', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const wc = (w as any).win.webContents;
let insertCSS = sinon.fake();
wc.insertCSS = insertCSS;
wc.emit('did-finish-load');
ok(insertCSS.called);
let css = insertCSS.lastCall.args[0];
ok(css.includes('display: none !important;'), css);
ok(css.includes('[href="/"]'), css);
ok(css.includes('[aria-label="Back"]'), css);
ok(css.includes('[aria-label="戻る"]'), css);
(w as any).screenName = 'foo';
insertCSS = sinon.fake();
wc.insertCSS = insertCSS;
wc.emit('did-finish-load');
ok(insertCSS.called);
css = insertCSS.lastCall.args[0];
ok(css.includes('[href="/foo"]'), css);
});
it('detects login at onBeforeRequest hook', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const wc = (w as any).win.webContents;
const callback = wc.session.webRequest.onBeforeRequest.lastCall.args[1];
function loginIpcSent() {
const called = !!(wc.send as Spy).getCalls().find(c => c.args[0] === 'tweetapp:login');
wc.send = sinon.fake(); // Clear
return called;
}
// Do nothing when referrer is not /login URL
let cb = sinon.fake();
callback(
{
url: 'https://www.google-analytics.com/r/*',
referrer: 'https://mobile.twitter.com/compose/tweet',
},
cb,
);
ok(cb.called);
ok(!loginIpcSent());
// Detect referrer is /login URL
cb = sinon.fake();
callback(
{
url: 'https://www.google-analytics.com/r/*',
referrer: 'https://mobile.twitter.com/login',
},
cb,
);
ok(cb.called);
ok(loginIpcSent());
eq(wc.session.webRequest.onBeforeRequest.lastCall.args[0], null); // listener was removed
// Tweet is posted, it means it is already in login state
wc.session.webRequest.onBeforeRequest = sinon.fake();
cb = sinon.fake();
callback(
{
url: 'https://mobile.twitter.com/i/api/graphql/hoge/CreateTweet',
referrer: 'https://mobile.twitter.com/compose/tweet',
},
cb,
);
ok(cb.called);
ok(!loginIpcSent());
eq(wc.session.webRequest.onBeforeRequest.lastCall.args[0], null); // listener was removed
});
describe('Permission request handler', function () {
let webContents: any;
let handler: (...args: any[]) => any;
beforeEach(async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
webContents = (w as any).win.webContents;
webContents.url = 'https://mobile.twitter.com/compose/tweet';
handler = webContents.session.setPermissionRequestHandler.lastCall.args[0];
});
it('rejects some permissions without asking to user', function () {
for (const perm of ['fullscreen', 'notification']) {
const cb = sinon.fake();
handler(webContents, perm, cb, {});
ok(cb.called);
ok(!cb.lastCall.args[0]);
}
});
it('rejects any permission from outside mobile.twitter.com', function () {
webContents.url = 'https:/example.com'; // This changes return value of webContents.getURL()
const cb = sinon.fake();
handler(webContents, 'media', cb, {});
ok(cb.called);
ok(!cb.lastCall.args[0]);
});
it('rejects when user clicks "Reject" button of dialog', async function () {
for (const perm of ['media', 'geolocation']) {
// 1 means button at index 1 'Reject' was clicked
dialog.showMessageBox = sinon.fake.returns(Promise.resolve({ response: 1 }));
const p = new Promise(resolve => {
handler(webContents, perm, resolve, {});
});
ok(dialog.showMessageBox.called);
eq(dialog.showMessageBox.lastCall.args[0].title, 'Permission was requested');
const msg = dialog.showMessageBox.lastCall.args[0].message;
ok(msg.includes(perm), msg);
const accepted = (await p) as boolean;
ok(!accepted);
}
});
it('accepts when user clicks "Accept" button of dialog', async function () {
for (const perm of ['media', 'geolocation']) {
const p = new Promise(resolve => {
handler(webContents, perm, resolve, {});
});
ok(dialog.showMessageBox.called);
const accepted = (await p) as boolean;
ok(accepted);
}
});
});
it('rejects window title update', async function () {
const w = new TweetWindow('foo', {}, new Ipc(), { text: '' }, {} as any);
await w.openNewTweet();
const preventDefault = sinon.fake();
(w as any).win.emit('page-title-updated', { preventDefault });
ok(preventDefault.called);
});
it('unlinks tweet text', async function () {
const w = new TweetWindow('@foo', {}, new Ipc(), { text: '' }, {} as any);
// Do nothing when window is not open
w.unlinkSelection('');
await w.openNewTweet();
const webContents = (w as any).win.webContents;
// Nothing unlinked. Text is not changed
w.unlinkSelection('this is test');
ok(!webContents.insertText.called);
// Test unlinking things
w.unlinkSelection('foo! @name #tag');
ok(webContents.insertText.calledOnce);
const unlinked = webContents.insertText.lastCall.args[0];
eq(unlinked, 'foo! @\u200Bname #\u200Btag');
});
it('resets window when receiving tweetapp:reset-window message', async function () {
const ipc = new Ipc();
const w = new TweetWindow('foo', {}, ipc, { text: '' }, {} as any);
await w.openNewTweet();
const webContents = (w as any).win.webContents;
const call = findCall(ipcMain.on, c => c.args[0] === 'tweetapp:reset-window');
ok(call);
const onResetWindow = call.args[1];
const willReset = onResetWindow();
webContents.emit('dom-ready');
await willReset;
ok(w.isOpen());
// tweetapp:open is sent from main to renderer because tweetapp:reset-window forces to reopen
// the window
const sent = findCall(webContents.send, call => call.args[0] === 'tweetapp:open');
ok(sent);
const url = sent.args[1]; // Argument of 'tweetapp:open' message on calling open()
eq(url, 'https://mobile.twitter.com/compose/tweet');
});
}); | the_stack |
import chance from 'chance';
import { format } from '../../src/index';
import { en, fr } from '../../src/locale';
import truncateNumber from '../../src/core/utils/truncate-number';
import { NumerableLocale } from '../../src/locale/types/numerable-locale';
import { NumerableFormatter } from '../../src/core/types/numerable-formatter';
import { NumerableFormatNumberOptions } from '../../dist/formatter/types/format-number-options';
describe('numerable', () => {
const getOptionsWithDelimiters = (thousands: string, decimal: string) => {
return { locale: { ...en, delimiters: { thousands: thousands, decimal: decimal } } };
};
describe('formatNumber', () => {
it('should format to a number', () => {
const tests = [
[0, null, '0'],
[0, '0.00', '0.00'],
[null, null, ''],
[null, '0.00', ''],
[NaN, '0.0', ''],
[1.23,'0,0','1'],
[10000,'0,0.0000','10,000.0000'],
[10000.23,'0,0','10,000'],
[-10000,'0,0.0','-10,000.0'],
[10000.1234,'0.000','10000.123'],
[10000,'0[.]00','10000'],
[10000.1,'0[.]00','10000.10'],
[10000.123,'0[.]00','10000.12'],
[10000.456,'0[.]00','10000.46'],
[10000.001,'0[.]00','10000'],
[10000.45,'0[.]00#','10000.45'],
[10000.456,'0[.]00#','10000.456'],
[10000,'(0,0.0000)','10,000.0000'],
[-10000,'(0,0.0000)','(10,000.0000)'],
[-12300,'+0,0.0000','-12,300.0000'],
[1230,'+0,0','+1,230'],
[1230,'-0,0','1,230'],
[-1230,'-0,0','-1,230'],
[-1230.4,'0,0.0+','1,230.4-'],
[-1230.4,'0,0.0-','1,230.4-'],
[1230.4,'0,0.0-','1,230.4'],
[100.78, '0', '101'],
[100.28, '0', '100'],
[100, '0', '100'],
[1.932,'0.0','1.9'],
[1.9687,'0','2'],
[1.9687,'0.0','2.0'],
[-0.23,'#.00','-.23'],
[-0.23,'(#.00)','(.23)'],
[0.23,'0.00000','0.23000'],
[0.67,'0.0####','0.67'],
[3162.63,'0.0##############','3162.63'],
[1.99,'0.#','2'],
[1.0501,'0.00#','1.05'],
[1.005,'0.00','1.01'],
// leading zero
[0, '00.0', '00.0'],
[0.23, '000.##', '000.23'],
[4, '000', '004'],
[10, '00000', '00010'],
[1000, '000,0', '1,000'],
[1000, '00000,0', '01,000'],
[1000, '0000000,0', '0,001,000'],
// abbreviations
[2000000000,'0.0a','2.0B'],
[1230974,'0.0a','1.2M'],
[1460,'0a','1K'],
[-104000,'0 a','-104 K'],
[999950,'0.0a','1.0M'],
[999999999,'0a','1B'],
// forced abbreviations
[-5444333222111, '0,0 ak', '-5,444,333,222 K'],
[5444333222111, '0,0 am', '5,444,333 M'],
[-5444333222111, '0,0 ab', '-5,444 B'],
[-5444333222111, '0,0 at', '-5 T'],
[123456, '0.0# ak', '123.46 K'],
[150,'0.0 ak','0.2 K'],
// ====== New tests
// Fix abbreviation with space
[1000000000000000, '0.0 a', '1000.0 T'],
[10000000000000000, '0.0 a', '10000.0 T'],
[100000000000000000, '0.0 a', '100000.0 T'],
[1000000000000000000, '0.0 a', '1000000.0 T'],
// Same case as previous but without space
[1000000000000000, '0.0a', '1000.0T'],
[10000000000000000, '0.0a', '10000.0T'],
[100000000000000000, '0.0a', '100000.0T'],
[1000000000000000000, '0.0a', '1000000.0T'],
// No trailing space should be in the formatted string, if abbreviation is not applied.
[999, '0 a', '999'],
[10.23, '0.00 a', '10.23'],
[123.456, '0,0.000 a', '123.456'],
// Negative sign at the right and abbreviation
[-1230, '0,0.000- a', '1.230- K'],
[-2000, '0.0- a', '2.0- K'],
[-3400200, '0- a', '3- M'],
[-3400200, '0.##- a', '3.4- M'],
[-3400200, '0.X- a', '3.4002- M'],
] as const;
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern as any);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::rounding-bubbling-fix', () => {
/**
* - Corner case
* New thousands separator abbreviation after rounding (only with automatic abbreviation)
* value: 999950, pattern '0.0a'
* [k] 999.95 (5) [5 must be rounded to leave only one decimal]
* After rounding the 5, the resulting number is 1000, and therefore the number will have a new abbreviation,
* so a new abbreviation needs to be calculated.
* <i> The number that is rounded is the one after the pattern, that is the one that is going to be removed.
*/
it('should handle the "new thousands separator abbreviation after rounding" case', () => {
const tests: any[] = [
// Corner cases (positive)
[999.99, '0.0a', '1.0K'],
[999.999, '0.00a', '1.00K'],
[999.9999, '0.000a', '1.000K'],
[999950, '0.0a', '1.0M'],
[999999, '0.0a', '1.0M'],
[999999970, '0.0a', '1.0B'],
[999999999995, '0.0a', '1.0T'],
[999995, '0.00a', '1.00M'],
[999999995, '0.00a', '1.00B'],
[999999999995, '0.00a', '1.00T'],
[999999.5, '0.000a', '1.000M'],
[999999999.5, '0.000a', '1.000B'],
[999999999999.5, '0.000a', '1.000T'],
[999.999999999999999997, '0.00000000000000000a', '1.00000000000000000K'],
[999.999999999999999997, '0.00000000000000###a', '1.00000000000000K'],
// Corner cases (negative)
[-999.99, '0.0a', '-1.0K'],
[-999.999, '0.00a', '-1.00K'],
[-999.9999, '0.000a', '-1.000K'],
[-999960, '0.0a', '-1.0M'],
[-999999, '0.0a', '-1.0M'],
[-999999970, '0.0a', '-1.0B'],
[-999999999996, '0.0a', '-1.0T'],
[-999996, '0.00a', '-1.00M'],
[-999999996, '0.00a', '-1.00B'],
[-999999995.1, '0.00a', '-1.00B'],
[-999999995.06, '0.00a', '-1.00B'],
[-999999995.006, '0.00a', '-1.00B'],
[-999999995.0000000005, '0.00a', '-1.00B'],
[-999999999996, '0.00a', '-1.00T'],
[-999999.6, '0.000a', '-1.000M'],
[-999999999.5001, '0.000a', '-1.000B'],
[-999999999999.9, '0.000a', '-1.000T'],
// Safety cases
// With '0.0a'
[9999.99, '0.0a', '10.0K'],
[99999.99, '0.0a', '100.0K'],
[9999950, '0.0a', '10.0M'],
[99999960, '0.0a', '100.0M'],
[9999999980, '0.0a', '10.0B'],
[99999999990, '0.0a', '100.0B'],
[9999999999996, '0.0a', '10.0T'],
[99999999999997, '0.0a', '100.0T'],
[999999999999998, '0.0a', '1000.0T'],
[9999999999999998, '0.0a', '10000.0T'],
[99999999999999998, '0.0a', '100000.0T'],
[999999999999999998, '0.0a', '1000000.0T'],
[9999999999999999998, '0.0a', '10000000.0T'],
[99999999999999999998, '0.0a', '100000000.0T'],
[999999999999999999998, '0.0a', '1000000000.0T'],
[9999999999999999999998, '0.0a', '10000000000.0T'],
[99999999999999999999998, '0.0a', '100000000000.0T'],
[999999999999999999999998, '0.0a', '1000000000000.0T'],
// With 2 decimal places '0.00a'
[9999995, '0.00a', '10.00M'],
[99999995, '0.00a', '100.00M'],
[999999999999995, '0.00a', '1000.00T'],
// With 3 decimal places '0.000a'
[9999999.5, '0.000a', '10.000M'],
[99999999.5, '0.000a', '100.000M'],
[999999999999999.5, '0.000a', '1000.000T'],
// With 1 decimal place and forced scale '0.0ak'
[999.99, '0.0ak', '1.0K'],
[9999.99, '0.0ak', '10.0K'],
[99999.99, '0.0ak', '100.0K'],
[999999.99, '0.0ak', '1000.0K'],
// With 1 decimal place and forced scale '0.0am'
[999950, '0.0am', '1.0M'],
[999999, '0.0am', '1.0M'],
[9999950, '0.0am', '10.0M'],
[99999960, '0.0am', '100.0M'],
[999999970, '0.0am', '1000.0M'],
[9999999980, '0.0am', '10000.0M'],
[99999999990, '0.0am', '100000.0M'],
[999999999999, '0.0am', '1000000.0M'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::randomized-tests', () => {
it('should pass random tests for variable forced decimal places', () => {
const minDecimalPlaces = 1;
const maxDecimalPlaces = 12;
const maxInteger = 1000;
const maxDecimal = 1000000000;
[...Array(100)].forEach(() => {
const randomAmountOfDecimalPlaces = chance().natural({ min: minDecimalPlaces, max: maxDecimalPlaces });
const integerPart = chance().natural({ min: 0, max: maxInteger });
const decimalPart = chance().natural({ min: 0, max: maxDecimal });
const pattern = `0.${'0'.repeat(randomAmountOfDecimalPlaces)}`;
const value = +`${integerPart}.${decimalPart}`;
const result = format(value, pattern, { rounding: truncateNumber });
const expectedResult = `${integerPart}.${(decimalPart + '0000000000000').slice(0, randomAmountOfDecimalPlaces)}`;
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::locale-delimiters', () => {
it('should handle locale specific separators in format options', () => {
const tests: any[] = [
[[`,`, '.'], 1234.4, '0,0.0', '1,234.4'],
[[`.`, ','], 1234.4, '0,0.0', '1.234,4'],
[[`'`, ','], 1234.34, '0,0.0', '1\'234,3'],
[[`*`, '.'], 1299.34, '0,0.0', '1*299.3'],
[[`TEST`, '+'], 12345.34, '0,0.0', '12TEST345+3'],
[[` `, '_'], 12333.34, '0,0.0', '12 333_3'],
[[` `, '_'], 12333444.34, '0,0.0', '12 333 444_3'],
[[`<`, '>'], 12333567.34, '0,0.0', '12<333<567>3'],
[[` `, '--'], 12333567.3455, '0,0.0000', '12 333 567--3455'],
];
tests.forEach(([[thousands, decimals], value, pattern, expectedResult]) => {
const result = format(value, pattern, getOptionsWithDelimiters(thousands, decimals));
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should omit integer if omitInteger is enabled and the are no decimals, and decimal separator has more than one character', () => {
const tests: any[] = [
[[`,`, '__'], 1234, '0,0[.]00', '1,234'],
[[`,`, '___'], 1234, '0,0[.]00', '1,234'],
[[`,`, '--'], 1234567, '0,0[.]00', '1,234,567'],
[[`,`, '----'], 1234567, '0,0[.]00', '1,234,567'],
[[`,`, '--'], 1234567, '0,0[.]00', '1,234,567'],
[[`,`, '----'], 1234567, '0,0[.]00', '1,234,567'],
[[`,`, '----'], 1234567.999, '0,0[.]00', '1,234,568'],
[[`,`, '----'], 1234567.99, '0,0[.]0', '1,234,568'],
];
tests.forEach(([[thousands, decimals], value, pattern, expectedResult]) => {
const result = format(value, pattern, getOptionsWithDelimiters(thousands, decimals));
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::nullFormat-option', () => {
it('should return the specified nullFormat if value is null, undefined or NaN', () => {
const tests: any[] = [
['', null, '0,0.00', ''],
['', undefined, '0,0.00', ''],
['', NaN, '0,0.00', ''],
['N/A', null, '0,0.00', 'N/A'],
['N/A', undefined, '0,0.00', 'N/A'],
['N/A', NaN, '0,0.00', 'N/A'],
['-', null, '0,0.##', '-'],
];
tests.forEach(([nullFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { nullFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should return empty string if the typeof nullFormat is not an string', () => {
const tests: any[] = [
[null, null, '0,0.00', ''],
[undefined, null, '0,0.00', ''],
[NaN, undefined, '0,0.00', ''],
[0, null, '0,0.00', ''],
[Infinity, null, '0,0.00', ''],
[{}, null, '0,0.00', ''],
[[], null, '0,0.00', ''],
[true, null, '0,0.00', ''],
];
tests.forEach(([nullFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { nullFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should not apply nullFormat for NaN if nanFormat has been specified', () => {
const tests: any[] = [
['-', 'NaN', NaN, '0,0.00', 'NaN'],
['N/A', 'THIS-IS-NANFORMAT', NaN, '0,0.00', 'THIS-IS-NANFORMAT'],
[null, 'THIS-IS-NANFORMAT', NaN, '0,0.00', 'THIS-IS-NANFORMAT'],
];
tests.forEach(([nullFormat, nanFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { nullFormat, nanFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('format::signedZero-option', () => {
it('should append sign to 0 output if not specified in the options', () => {
const tests: [number, string, string][] = [
[0.0023, '0.00', '0.00'],
[-0.0023, '0.00', '-0.00'],
[-0.00023, '0.00', '-0.00'],
[-0.0000000000023, '0.00', '-0.00'],
[-0.0000000000023, '0.00##', '-0.00'],
[-0.0000000000023, '0', '-0'],
[-0.0000000000023, '0.0', '-0.0'],
[-0.0000000000023, '0.00000', '-0.00000'],
[-0.0000000000023, '0,0.00000', '-0.00000'],
[-0.0000000000023, '0,0.00000+', '0.00000-'],
[-0.0000000000023, '+0,0.00000', '-0.00000'],
[-0.0000000000023, '(0,0.00000)', '(0.00000)'],
[-100000, '0 am', '-0 M'],
[-10000, '0.0 am', '-0.0 M'],
[-100, '0 ak', '-0 K'],
[-10, '0.0 ak', '-0.0 K'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { signedZero: true });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
});
});
it('should NOT append sign to 0 output if not specified in the options', () => {
const tests: [number, string, string][] = [
[0.0023, '0.00', '0.00'],
[-0.0023, '0.00', '0.00'],
[-0.00023, '0.00', '0.00'],
[-0.0000000000023, '0.00', '0.00'],
[-0.0000000000023, '0.00##', '0.00'],
[-0.0000000000023, '0', '0'],
[-0.0000000000023, '0.0', '0.0'],
[-0.0000000000023, '0.00000', '0.00000'],
[-0.0000000000023, '0,0.00000', '0.00000'],
[-0.0000000000023, '0,0.00000+', '0.00000'],
[-0.0000000000023, '+0,0.00000', '0.00000'],
[-0.0000000000023, '(0,0.00000)', '0.00000'],
[-100000, '0 am', '0 M'],
[-10000, '0.0 am', '0.0 M'],
[-100, '0 ak', '0 K'],
[-10, '0.0 ak', '0.0 K'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { signedZero: false });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
});
});
});
describe('format::trim-option', () => {
it('should apply trim on the output string if specified in the options', () => {
const tests: [number, string, string][] = [
[NaN, ' 0,0.00', ''],
[0.15, ' 0,0.00 ', '0.15'],
[-0.15, ' 0.00 ', '-0.15'],
[123456789, ' 0.00 ', '123456789.00'],
[-123456789, ' 0.00 ', '-123456789.00'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { trim: true });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should NOT apply trim on the output string if specified in the options', () => {
const tests: [number, string, string][] = [
[NaN, ' 0,0.00', ''],
[0.15, ' 0,0.00 ', ' 0.15 '],
[-0.15, ' 0.00 ', ' -0.15 '],
[123456789, ' 0.00 ', ' 123456789.00 '],
[-123456789, ' 0.00 ', ' -123456789.00 '],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { trim: false });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('format::nanFormat-option', () => {
it('should return the specified nanFormat if value is NaN', () => {
const tests: any[] = [
['', NaN, '0,0.00', ''],
['N/A', NaN, '0,0.00', 'N/A'],
['-', NaN, '0,0.##', '-'],
['TEST', NaN, '0,0.##', 'TEST'],
];
tests.forEach(([nanFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { nanFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should return an empty string if the typeof nanFormat is not an string', () => {
const tests: any[] = [
[null, NaN, '0,0.00', ''],
[undefined, NaN, '0,0.00', ''],
[NaN, NaN, '0,0.00', ''],
[0, NaN, '0,0.00', ''],
[Infinity, NaN, '0,0.00', ''],
[{}, NaN, '0,0.00', ''],
[[], NaN, '0,0.00', ''],
[true, NaN, '0,0.00', ''],
];
tests.forEach(([nanFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { nanFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should not apply nanFormat over nullFormat if both has been specified, and the value is NaN', () => {
const tests: any[] = [
['-', 'NaN', NaN, '0,0.00', 'NaN'],
['N/A', 'THIS-IS-NANFORMAT', NaN, '0,0.00', 'THIS-IS-NANFORMAT'],
[null, 'THIS-IS-NANFORMAT', NaN, '0,0.00', 'THIS-IS-NANFORMAT'],
];
tests.forEach(([nullFormat, nanFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { nullFormat, nanFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('number-pattern', () => {
it('should apply the optional decimals (#) in the decimal places rule', () => {
const tests: any[] = [
// Alone
[1.5, '0.#', '1.5'],
[2.558, '0.#', '2.6'],
[-0.5, '0.#', '-0.5'],
[0.0000000000000000000000000001, '0.#', '0'],
[0.0000000000000000000000000001, '0.############################', '0.0000000000000000000000000001'],
[0.000000000000000000000000000000012345, '0.##################################', '0.0000000000000000000000000000000123'],
[0.000000000000000000000000000000012345, '0.#######################################', '0.000000000000000000000000000000012345'],
[-0.00000000000000000000000000000005432198, '0.####', '0'],
[-0.00000000000000000000000000000005432198, '0.###########################################', '-0.00000000000000000000000000000005432198'],
// With thousands separator in the pattern
[12345.67, '0,0.#', '12,345.7'],
[1.62, '0,0.#', '1.6'],
[-9876.23, '0,0.##', '-9,876.23'],
[-9876.23, '0,0.####', '-9,876.23'],
// With minimum decimals in the pattern
[12345, '0.0#', '12345.0'],
[98765, '0.000#', '98765.000'],
[98765.5, '0.000#', '98765.500'],
[-98765.58, '0.000#', '-98765.580'],
[98765.582, '0.000#', '98765.582'],
[-98765.5822, '0.000#', '-98765.5822'],
[98765.58222, '0.000##', '98765.58222'],
[-98765.58222, '0.000#####', '-98765.58222'],
[0.001, '0.0000#', '0.0010'],
[0.0000001, '0.0000#', '0.0000'],
[0.0000001, '0.0000###', '0.0000001'],
[-0.0000001, '0.0000#############', '-0.0000001'],
// With both thousands separator and minimum decimals
[1234.5, '0,0.0000#', '1,234.5000'],
[-1234.5, '0,0.0000#', '-1,234.5000'],
[-1234, '0,0.0000#####', '-1,234.0000'],
[123.5, '0,0.0000#', '123.5000'],
[-123.5, '0,0.0000##############', '-123.5000'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should apply the no-decimals-limit (X) in the decimal places rule', () => {
const tests: any[] = [
// Alone
[1.5, '0.X', '1.5'],
[2.558, '0.X', '2.558'],
[-0.5, '0.X', '-0.5'],
[0.0000000000000000000000000001, '0.X', '0.0000000000000000000000000001'],
[0.000000000000000000000000000000012345, '0.X', '0.000000000000000000000000000000012345'],
[-0.00000000000000000000000000000005432198, '0.X', '-0.00000000000000000000000000000005432198'],
// With thousands separator in the pattern
[12345.67, '0,0.X', '12,345.67'],
[1.67, '0,0.X', '1.67'],
[-9876.23, '0,0.X', '-9,876.23'],
// With minimum decimals in the pattern
[12345, '0.0X', '12345.0'],
[98765, '0.000X', '98765.000'],
[98765.5, '0.000X', '98765.500'],
[-98765.58, '0.000X', '-98765.580'],
[98765.582, '0.000X', '98765.582'],
[-98765.5822, '0.000X', '-98765.5822'],
[98765.58222, '0.000X', '98765.58222'],
[0.001, '0.0000X', '0.0010'],
[0.0000001, '0.0000X', '0.0000001'],
[-0.0000001, '0.0000X', '-0.0000001'],
// With both thousands separator and minimum decimals
[1234.5, '0,0.0000X', '1,234.5000'],
[-1234.5, '0,0.0000X', '-1,234.5000'],
[-1234, '0,0.0000X', '-1,234.0000'],
[123.5, '0,0.0000X', '123.5000'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should handle the force sign option in pattern (+)', () => {
const tests: any[] = [
[1, '+0,0.00', '+1.00'],
[1000, '+0,0.00', '+1,000.00'],
[0.1, '+0,0.00', '+0.10'],
[100, '+0,0.00', '+100.00'],
[100, '+ 0,0.00', '+ 100.00'],
[100, '+ 0,0.00', '+ 100.00'],
[100, '0,0.00+', '100.00+'],
[100, '0,0.00 +', '100.00 +'],
[100, '0,0.00 +', '100.00 +'],
// Negative numbers
[-1, '+0,0.00', '-1.00'],
[-1000, '+0,0.00', '-1,000.00'],
[-0.1, '+0,0.00', '-0.10'],
[-100, '+0,0.00', '-100.00'],
[-100, '+ 0,0.00', '- 100.00'],
[-100, '+ 0,0.00', '- 100.00'],
[-100, '0,0.00+', '100.00-'],
[-100, '0,0.00 +', '100.00 -'],
[-100, '0,0.00 +', '100.00 -'],
// Zero handling (no sign)
[0, '+0,0.00', '0.00'],
[-0, '+0,0.00', '0.00'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
});
});
});
describe('minimumIntegerDigits rule', () => {
it('should omit the integer for numbers between 1 and -1 if the pattern specifies that', () => {
const tests: any[] = [
[0, '#.00', '.00'],
[0.1, '#.00', '.10'],
[-0.1, '#.00', '-.10'],
[0, ' #.00', '.00'],
[0, ' #.00', '.00'],
[0.99, ' #.00', '.99'],
[-0.99, ' #.00', '-.99'],
[0.99, ' #.###', '.99'],
[-0.99, ' #.###', '-.99'],
[-0.23, '#.00', '-.23'],
[-0.23, '(#.00)', '(.23)'],
[-0.23, '( #.00)', '( .23)'],
[0.23, '+#.00', '+.23'],
[-0.23, '+#.00', '-.23'],
[0.23, '-#.00', '.23'],
[-0.23, '-#.00', '-.23'],
[0.23, '#.00-', '.23'],
[-0.23, '#.00-', '.23-'],
[0.23, '#.00+', '.23+'],
[-0.23, '#.00+', '.23-'],
[-0.23, '#.00 +', '.23 -'],
[0.23, '+ #.00', '+ .23'],
// Should apply only if value is between -1 and 1
[1.2, '#.00', '1.20'],
[-1.2, '#.00', '-1.20'],
[1000.2, '#.00', '1000.20'],
[-1000.2, '#.00', '-1000.20'],
[1000.2, '#.##', '1000.2'],
[1, '#.00', '1.00'],
[-1, '#.00', '-1.00'],
// Should also allow thousands separator
[1000, '#,#.00', '1,000.00'],
[-1000, '#,#.00', '-1,000.00'],
[0.12, '#,#.00', '.12'],
[-0.12, '#,#.00', '-.12'],
// What if number is 0? => '' (empty string)
[-0.12, '#.##', '-.12'],
[0, '#.##', ''],
[-0.12, '#', ''],
[-1.12, '#', '-1'],
[0, '#', ''],
[-0.12, '#,#.##', '-.12'],
[0, '#,#.##', ''],
[0, '#,0.##', ''],
];
tests.forEach(([number, pattern, expectedResult]) => {
const result = format(number, pattern);
expect([number, pattern, result]).toEqual([number, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::nonBreakingSpace-option', () => {
it('should replace spaces with non-breaking spaces if specified in the options', () => {
const tests: [number, string, string][] = [
[1000, '0.00 a', '1.00\u00A0K'],
[1000000, '0.00 a', '1.00\u00A0M'],
[1000000, '0.00 a', '1.00\u00A0\u00A0\u00A0\u00A0M'],
[1000000, 'a 0.00', 'M\u00A01.00'],
[1000000, 'a 0.00', 'M\u00A0\u00A0\u00A0\u00A01.00'],
[-1000, '0.00 a', '-1.00\u00A0K'],
[-1000000, '0.00 a', '-1.00\u00A0M'],
[-1000000, '0.00 a', '-1.00\u00A0\u00A0\u00A0\u00A0M'],
];
tests.forEach(([number, pattern, expectedResult]) => {
const result = format(number, pattern, { nonBreakingSpace: true });
expect([number, pattern, result]).toEqual([number, pattern, expectedResult]);
});
});
it('should NOT replace spaces with non-breaking spaces if specified in the options', () => {
const tests: [number, string, string][] = [
[1000, '0.00 a', '1.00 K'],
[1000000, '0.00 a', '1.00 M'],
[1000000, '0.00 a', '1.00 M'],
[1000000, 'a 0.00', 'M 1.00'],
[1000000, 'a 0.00', 'M 1.00'],
[-1000000, 'a 0.00', 'M -1.00'],
[-1000000, 'a 0.00', 'M -1.00'],
];
tests.forEach(([number, pattern, expectedResult]) => {
const result = format(number, pattern, { nonBreakingSpace: false });
expect([number, pattern, result]).toEqual([number, pattern, expectedResult]);
});
});
});
describe('formatNumber::zeroFormat-option', () => {
it('should return the specified zeroFormat if value is 0', () => {
const tests: any[] = [
['', 0, '0,0.00', ''],
['N/A', 0, '0,0.00', 'N/A'],
['-', 0, '0,0.##', '-'],
['TEST', 0, '0,0.##', 'TEST'],
];
tests.forEach(([zeroFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { zeroFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should return the normally formatted 0 if the typeof zeroFormat is not an string and the value is 0', () => {
const tests: any[] = [
[null, 0, '0,0.00', '0.00'],
[undefined, 0, '0,0.000##', '0.000'],
[NaN, 0, '0,0', '0'],
[0, 0, '0', '0'],
[Infinity, 0, '0,0.00000000', '0.00000000'],
[{}, 0, '0,0.00', '0.00'],
[[], 0, '0,0.00', '0.00'],
[true, 0, '0,0.00', '0.00'],
];
tests.forEach(([zeroFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { zeroFormat });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::_errorFormat', () => {
it('should return the hidden _errorFormat option if an error occurs during the format process', () => {
const brokenRoundingFunction = () => { throw new Error(); };
const tests: any[] = [
['', 123, '0,0.00', ''],
['N/A', 123, '0,0.00', 'N/A'],
['-', 123.23, '0,0.##', '-'],
['TEST', 3434.23, '0,0.##', 'TEST'],
];
tests.forEach(([_errorFormat, value, pattern, expectedResult]) => {
const result = format(value, pattern, { rounding: brokenRoundingFunction, _errorFormat } as any);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should return an empty string if an error occurs during the format process', () => {
const tests: any[] = [
[123, '0,0.00', ''],
[123, '0,0.00', ''],
[123.23, '0,0.##', ''],
[3434.23, '0,0.##', ''],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { rounding: () => { throw new Error(); } } as any);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::locale-option', () => {
it('should use the passed locale object for formatting the number', () => {
expect(format(12345.67, '0,0.000', { locale: fr })).toBe('12 345,670');
});
it('should fallback to "en" locale if the passed locale is not an object', () => {
expect(format(12345.67, '0,0.000', { locale: null as any })).toBe('12,345.670');
expect(format(12345.67, '0,0.000', { locale: '' as any })).toBe('12,345.670');
expect(format(12345.67, '0,0.000', { locale: 0 as any })).toBe('12,345.670');
expect(format(12345.67, '0,0.000', { locale: true as any })).toBe('12,345.670');
expect(format(12345.67, '0,0.000', { locale: NaN as any })).toBe('12,345.670');
});
});
describe('formatNumber::rounding', () => {
it('should apply rounding function aliases on format options', () => {
const tests: any[] = [
['truncate', 1234.158, '0,0.00', '1,234.15'],
['truncate', -1234.158, '0,0.00', '-1,234.15'],
['ceil', 1234.152, '0,0.00', '1,234.16'],
['ceil', -1234.158, '0,0.00', '-1,234.15'],
['floor', 1234.158, '0,0.00', '1,234.15'],
['floor', -1234.152, '0,0.00', '-1,234.16'],
['half-up', 1234.158, '0,0.00', '1,234.16'],
['half-up', 1234.155, '0,0.00', '1,234.16'],
['half-up', 1234.152, '0,0.00', '1,234.15'],
['half-up', -1234.158, '0,0.00', '-1,234.16'],
['half-up', -1234.155, '0,0.00', '-1,234.15'],
['half-up', -1234.152, '0,0.00', '-1,234.15'],
['half-away-from-zero', 1234.14, '0,0.0', '1,234.1'],
['half-away-from-zero', 1234.15, '0,0.0', '1,234.2'],
['half-away-from-zero', 1234.16, '0,0.0', '1,234.2'],
['half-away-from-zero', -1234.14, '0,0.0', '-1,234.1'],
['half-away-from-zero', -1234.15, '0,0.0', '-1,234.2'],
['half-away-from-zero', -1234.16, '0,0.0', '-1,234.2'],
];
tests.forEach(([roundingFunctionAlias, value, pattern, expectedResult]) => {
const result = format(value, pattern, { rounding: roundingFunctionAlias });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should apply rounding function found in format options', () => {
const tests: any[] = [
[truncateNumber, 1234.158, '0,0.00', '1,234.15'],
[Math.floor, 1234.158, '0,0.00', '1,234.15'],
[Math.ceil, 1234.152, '0,0.00', '1,234.16'],
[Math.round, 1234.152, '0,0.00', '1,234.15'],
[() => 10, 1234.152, '0,0.00', '0.10'],
];
tests.forEach(([roundingFunction, value, pattern, expectedResult]) => {
const result = format(value, pattern, { rounding: roundingFunction });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should fallback to Math.round if no valid rounding property is passed', () => {
const tests: any[] = [
// Apply Math.round as fallback
['', 1234.152, '0,0.00', '1,234.15'],
[null, 1234.152, '0,0.00', '1,234.15'],
[undefined, 1234.152, '0,0.00', '1,234.15'],
['unexisting-rounding-function-alias', 1234.152, '0,0.00', '1,234.15'], // Apply Math.round as fallback
];
tests.forEach(([roundingFunction, value, pattern, expectedResult]) => {
const result = format(value, pattern, { rounding: roundingFunction });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatNumber::overload', () => {
it('should handle 1 argument (value) and apply default pattern', () => {
expect(format(1234.56)).toBe(format(1234.56, '0,0.##########'));
});
it('should handle 2 arguments (value, pattern) and apply given pattern', () => {
expect(format(1234.56, '00000,0.0')).toBe('01,234.6');
});
it('should accept a number string (as JS number) as a "value" argument, and then apply apply given pattern', () => {
expect(format('1234.56', '00000,0.0')).toBe('01,234.6');
});
it('should handle 2 arguments (value, options) and apply default pattern with given options', () => {
const result = format(1234.56, getOptionsWithDelimiters('*', '_'));
const expectedResult = format(1234.56, '0,0.##########', getOptionsWithDelimiters('*', '_'));
expect(result).toBe(expectedResult);
});
it('should handle 3 arguments (value, pattern, options) and apply pattern and options', () => {
expect(format(1, '0000,0.00', getOptionsWithDelimiters('^', '"'))).toBe('0^001"00');
});
});
// The value type of the 'value' argument passed to formatNumber
describe('formatNumber::value-type-resolver', () => {
it('should return "∞" or "-∞" for `Infinity` value types', () => {
expect(format(Infinity, '0000,0.00')).toBe('∞');
expect(format(-Infinity, '0000,0.00')).toBe('-∞');
});
it('should return empty string if `null` or `undefined` is passed', () => {
expect(format(null, '0,0.00')).toBe('');
expect(format(undefined, '0,0.00')).toBe('');
expect(format(null, '0,0.00', { nullFormat: 'N/A' })).toBe('N/A');
expect(format(undefined, '0,0.00', { nullFormat: 'N/A' })).toBe('N/A');
});
it('should return empty string if `NaN` is passed', () => {
expect(format(NaN, '0,0.00')).toBe('');
expect(format(NaN, '0,0.00', { nanFormat: 'N/A' })).toBe('N/A');
expect(format(NaN, '0,0.00', { nullFormat: 'N/A' })).toBe('N/A');
expect(format(NaN, '0,0.00', { nanFormat: 'nan-format', nullFormat: 'N/A' })).toBe('nan-format');
expect(format('this-string-will-be-parsed-as-NaN', '0,0.00')).toBe('');
expect(format('', '0,0.00')).toBe('');
});
it('should apply parseFloat to the value if the provided value type is string', () => {
expect(format('123.45', '0000,0.00')).toBe('0,123.45');
expect(format('1,23.45', '0000,0.00')).toBe('0,001.00');
expect(format('12,3.45', '0000,0.00')).toBe('0,012.00');
expect(format('123.45 %', '0000,0.00')).toBe('0,123.45');
expect(format('1e+2', '0,0.00')).toBe('100.00');
expect(format('1e-2', '0,0.00')).toBe('0.01');
expect(format(' 1e-2', '0,0.00')).toBe('0.01');
expect(format(' 123', '0,0.00')).toBe('123.00');
expect(format('234testTESTtestTEST', '0,0.00')).toBe('234.00');
expect(format('', '0,0.00')).toBe('');
expect(format('no-valid-string', '0,0.00')).toBe('');
expect(format('this-should-be-same-as-passing-NaN', '0,0.00', { nanFormat: 'N/A' })).toBe('N/A');
expect(format('this-should-be-same-as-passing-NaN', '0,0.00', { nullFormat: 'N/A' })).toBe('N/A');
expect(format('this-should-be-same-as-passing-NaN', '0,0.00', { nanFormat: 'N-A-N', nullFormat: '-' })).toBe('N-A-N');
});
});
describe('pattern type resolver', () => {
const DEFAULT_PATTERN = '0,0.##########';
// no valid pattern means '', null or undefined
it('should format with DEFAULT_OPTIONS defaultPattern if no valid pattern is provided', () => {
expect(format(1234.56, '')).toBe(format(1234.56, DEFAULT_PATTERN));
expect(format(1234.56, undefined as any)).toBe(format(1234.56, DEFAULT_PATTERN));
expect(format(1234.56, null as any)).toBe(format(1234.56, DEFAULT_PATTERN));
});
it('should format with the provided defaultPattern in options if no valid pattern is provided in the arguments', () => {
expect(format(1234.503, null, { defaultPattern: '0.0' })).toBe('1234.5');
expect(format(1234.503, undefined, { defaultPattern: '0.0' })).toBe('1234.5');
expect(format(1234.503, '', { defaultPattern: '0.0' })).toBe('1234.5');
});
});
describe('formatting exponential numbers', () => {
it('should properly format small exponential numbers with fixed decimals', () => {
const tests: any[] = [
// Positive numbers
[0.000000012345, '0.00000000', '0.00000001'],
[0.000000012345, '0.000000000', '0.000000012'],
[0.000000012345, '0.0000000000', '0.0000000123'],
[0.000000012345, '0.00000000000', '0.00000001235'], // Rounding half-away-from-zero
[0.000000012345, '0.000000000000', '0.000000012345'],
[0.000000012345, '0.0000000000000', '0.0000000123450'],
[0.000000012345, '0.00000000000000', '0.00000001234500'],
[0.000000012345, '0.000000000000000', '0.000000012345000'],
[0.000000012345, '0.0000000000000000', '0.0000000123450000'],
[0.000000012345, '0.00000000000000000', '0.00000001234500000'],
// Negative numbers
[-0.000000012345, '0.00000000', '-0.00000001'],
[-0.000000012345, '0.000000000', '-0.000000012'],
[-0.000000012345, '0.0000000000', '-0.0000000123'],
[-0.000000012345, '0.00000000000', '-0.00000001235'], // Rounding half-away-from-zero
[-0.000000012345, '0.000000000000', '-0.000000012345'],
[-0.000000012345, '0.0000000000000', '-0.0000000123450'],
[-0.000000012345, '0.00000000000000', '-0.00000001234500'],
[-0.000000012345, '0.000000000000000', '-0.000000012345000'],
[-0.000000012345, '0.0000000000000000', '-0.0000000123450000'],
[-0.000000012345, '0.00000000000000000', '-0.00000001234500000'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should properly format small exponential numbers with optional decimals', () => {
const tests: any[] = [
// Positive numbers
[0.000000012345, '0.########', '0.00000001'],
[0.000000012345, '0.#########', '0.000000012'],
[0.000000012345, '0.##########', '0.0000000123'],
[0.000000012345, '0.###########', '0.00000001235'],
[0.000000012345, '0.############', '0.000000012345'],
[0.000000012345, '0.#############', '0.000000012345'],
[0.000000012345, '0.################', '0.000000012345'],
[0.000000012345, '0.0000000#', '0.00000001'],
[0.000000012345, '0.0000000##', '0.000000012'],
[0.000000012345, '0.000000##', '0.00000001'],
[0.000000012345, '0.000000####', '0.0000000123'],
[0.000000012345, '0.000000#####', '0.00000001235'],
[0.000000012345, '0.000000######', '0.000000012345'],
[0.000000012345, '0.000000#######', '0.000000012345'],
[0.000000012345, '0.000000###############', '0.000000012345'],
[0.000000012345, '0.000000#######################', '0.000000012345'],
// Negative numbers
[-0.000000012345, '0.########', '-0.00000001'],
[-0.000000012345, '0.#########', '-0.000000012'],
[-0.000000012345, '0.##########', '-0.0000000123'],
[-0.000000012345, '0.###########', '-0.00000001235'],
[-0.000000012345, '0.############', '-0.000000012345'],
[-0.000000012345, '0.#############', '-0.000000012345'],
[-0.000000012345, '0.################', '-0.000000012345'],
[-0.000000012345, '0.0000000#', '-0.00000001'],
[-0.000000012345, '0.0000000##', '-0.000000012'],
[-0.000000012345, '0.000000##', '-0.00000001'],
[-0.000000012345, '0.000000####', '-0.0000000123'],
[-0.000000012345, '0.000000#####', '-0.00000001235'], // Rounding half-away-from-zero
[-0.000000012345, '0.000000######', '-0.000000012345'],
[-0.000000012345, '0.000000#######', '-0.000000012345'],
[-0.000000012345, '0.000000###############', '-0.000000012345'],
[-0.000000012345, '0.000000#######################', '-0.000000012345'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should properly format big exponential numbers', () => {
const tests: any[] = [
// Positive numbers
[1234123412341230000000, '0,0', '1,234,123,412,341,230,000,000'],
[12341234123412300000000, '0,0', '12,341,234,123,412,300,000,000'],
[123412341234123000000000, '0,0', '123,412,341,234,123,000,000,000'],
[9934123412341230000000000, '0,0', '9,934,123,412,341,230,000,000,000'],
[99341234123412300000000000000, '0,0', '99,341,234,123,412,300,000,000,000,000'],
[993412341234123000000000000000000, '0,0', '993,412,341,234,123,000,000,000,000,000,000'],
[99341234123412300000000000000000000000000, '0,0', '99,341,234,123,412,300,000,000,000,000,000,000,000,000'],
[993412341234123000000000000000000000000000000000000000000, '0,0', '993,412,341,234,123,000,000,000,000,000,000,000,000,000,000,000,000,000,000'],
[553412341234123000000000000000000000000000000000000000000, '0,0', '553,412,341,234,123,000,000,000,000,000,000,000,000,000,000,000,000,000,000'],
[229912341234123000000000000000000000000000000000000000000, '0,0', '229,912,341,234,123,000,000,000,000,000,000,000,000,000,000,000,000,000,000'],
// Negative numbers
[-1234123412341230000000, '0,0', '-1,234,123,412,341,230,000,000'],
[-12341234123412300000000, '0,0', '-12,341,234,123,412,300,000,000'],
[-123412341234123000000000, '0,0', '-123,412,341,234,123,000,000,000'],
[-9934123412341230000000000, '0,0', '-9,934,123,412,341,230,000,000,000'],
[-99341234123412300000000000000, '0,0', '-99,341,234,123,412,300,000,000,000,000'],
[-993412341234123000000000000000000, '0,0', '-993,412,341,234,123,000,000,000,000,000,000'],
[-99341234123412300000000000000000000000000, '0,0', '-99,341,234,123,412,300,000,000,000,000,000,000,000,000'],
[-993412341234123000000000000000000000000000000000000000000, '0,0', '-993,412,341,234,123,000,000,000,000,000,000,000,000,000,000,000,000,000,000'],
[-553412341234123000000000000000000000000000000000000000000, '0,0', '-553,412,341,234,123,000,000,000,000,000,000,000,000,000,000,000,000,000,000'],
[-229912341234123000000000000000000000000000000000000000000, '0,0', '-229,912,341,234,123,000,000,000,000,000,000,000,000,000,000,000,000,000,000'],
// With both fixed and optional decimals
[1234123412341230000000, '0,0.00', '1,234,123,412,341,230,000,000.00'],
[12341234123412300000000, '0,0.000', '12,341,234,123,412,300,000,000.000'],
[123412341234123000000000, '0,0.0####', '123,412,341,234,123,000,000,000.0'],
[123412341234123000000000, '0,0.####', '123,412,341,234,123,000,000,000'],
[-1234123412341230000000, '0,0.00', '-1,234,123,412,341,230,000,000.00'],
[-12341234123412300000000, '0,0.000', '-12,341,234,123,412,300,000,000.000'],
[-123412341234123000000000, '0,0.0####', '-123,412,341,234,123,000,000,000.0'],
[-123412341234123000000000, '0,0.####', '-123,412,341,234,123,000,000,000'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should handle other features cases with exponential numbers', () => {
// Rounding
expect(format(0.000000012345, '0.00000000', { rounding: 'ceil' })).toBe('0.00000002');
expect(format(-0.000000012345, '0.00000000', { rounding: 'floor' })).toBe('-0.00000002');
// Abbreviation
expect(format(1234123412341230000000, '0.0a')).toBe('1234123412.3T');
expect(format(1234123412341230000000, '0,0.0a')).toBe('1,234,123,412.3T');
// Locales
expect(format(1234123412341230000000, '0,0.0a', { locale: fr })).toBe('1 234 123 412,3Bn');
expect(format(0.000000012345, '0.00000000', { locale: fr })).toBe('0,00000001');
// Percentage format
expect(format(0.00000000012345, '0.00000000%')).toBe('0.00000001%');
expect(format(123412341234123000000000, '0%')).toBe('12341234123412300000000000%');
expect(format(123412341234123000000000, '0,0%')).toBe('12,341,234,123,412,300,000,000,000%');
expect(format(123412341234123000000000, '0,0.00%')).toBe('12,341,234,123,412,300,000,000,000.00%');
});
});
describe('localization', () => {
it('should apply the defined digit grouping style', () => {
const getEnLocaleWithCustomDigitGroupingStyle = (digitGroupingStyle: number[]): NumerableLocale => ({ ...en, digitGroupingStyle });
const tests: any[] = [
[undefined, 123456789, '0,0', '123,456,789'],
[[], 123456789, '0,0', '123,456,789'],
[[4], 123456789, '0,0', '1,2345,6789'],
[[4,3], 123456789, '0,0', '12,345,6789'],
[[4,2], 123456789, '0,0', '1,23,45,6789'],
[[1], 123456789, '0,0', '1,2,3,4,5,6,7,8,9'],
[[7,1], 123456789, '0,0', '1,2,3456789'],
[[3,2], 123456789, '0,0', '12,34,56,789'],
[[3,2], 123456789, '0,0', '12,34,56,789'],
[[2], 123456789, '0,0', '1,23,45,67,89'],
[[3], 123456789, '0,0', '123,456,789'],
[[3,1,4], 123456789, '0,0', '1,2345,6,789'],
];
tests.forEach(([digitGroupingStyle, value, pattern, expectedResult]) => {
const result = format(value, pattern, { locale: getEnLocaleWithCustomDigitGroupingStyle(digitGroupingStyle) });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should apply the defined numeralSystem', () => {
const getEnLocaleWithCustomNumeralSystem = (numeralSystem: string[]): NumerableLocale => ({ ...en, numeralSystem });
const arabicNumeralSystem = [
'٠', // 0
'١', // 1
'٢', // 2
'٣', // 3
'٤', // 4
'٥', // 5
'٦', // 6
'٧', // 7
'٨', // 8
'٩', // 9
];
const tests: any[] = [
[undefined, 1234567890, '0', '1234567890'],
[arabicNumeralSystem, 1234567890, '0', '١٢٣٤٥٦٧٨٩٠'],
[arabicNumeralSystem, 9, '0', '٩'],
[arabicNumeralSystem, 10, '0', '١٠'],
['abcdefghij', 0, '0', 'a'],
['abcdefghij', 1, '0', 'b'],
['abcdefghij', 10, '0', 'ba'],
['abcdefghij', 1234567890, '0', 'bcdefghija'],
[['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 1234567890, '0', 'bcdefghija'],
// Invalid, not 10 characters (ignored)
['abc', 1234567890, '0', '1234567890'],
// Invalid, not 10 characters (ignored)
[['a', 'b'], 1234567890, '0', '1234567890'],
];
tests.forEach(([numeralSystem, value, pattern, expectedResult]) => {
const result = format(value, pattern, { locale: getEnLocaleWithCustomNumeralSystem(numeralSystem) });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should use the defined abbreviations', () => {
const tests: any[] = [
['|||Test', 1234, '0 a', '1 Test'],
['|||Test|||Test2', 1234, '0 a', '1 Test'],
['|||Test|||Test2', -1234567, '0 a', '-1 Test2'],
['||s||-', 1234567, '0 a', '123 -'],
['||||-||||"||||$', 120003000, '0.0 a', '1.2 "'],
['||||-||||"||||$', -1200030004000, '0.0 a', '-1.2 $'],
['|||T||L||Cr|||TCr||LCr', 1000, '0 a', '1 T'],
['|||T||L||Cr|||TCr||LCr', 100000, '0 a', '1 L'],
['|||T||L||Cr|||TCr||LCr', 10000000, '0 a', '1 Cr'],
['|||T||L||Cr|||TCr||LCr', -10000000000, '0 a', '-1 TCr'],
['|||T||L||Cr|||TCr||LCr', 1000000000000, '0 a', '1 LCr'],
['|||T||L||Cr|||TCr||LCr', 1000000000000000, '0 a', '1000 LCr'],
['|||K|||M|||B|||T', -1000, '0 a', '-1 K'],
['|||K|||M|||B|||T', 1000000, '0 a', '1 M'],
['|||K|||M|||B|||T', 1000000000, '0 a', '1 B'],
['|||K|||M|||B|||T', -1000000000000, '0 a', '-1 T'],
['|||K|||M|||B|||T', 1000000000000000, '0 a', '1000 T'],
['|s|-', 1, '0 a', '1'],
['|s|-', 10, '0 a', '1 s'],
['|s|-', -100, '0 a', '-1 -'],
['|s|-', 1000, '0 a', '10 -'],
// Should fallback to english if no abbreviations
[undefined, 1234, '0 a', '1 K'],
[null, -1234, '0 a', '-1 K'],
['', 1234, '0 a', '1 K'],
// No abbreviations defined
['|||||||||||', 1234, '0 a', '1234'],
];
tests.forEach(([abbreviations, value, pattern, expectedResult]) => {
const result = format(value, pattern, { locale: { ...en, abbreviations } });
expect([abbreviations, value, pattern, result]).toEqual([abbreviations, value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should properly apply the forced abbreviation unit', () => {
const enAbbreviations = '|||K|||M|||B|||T';
const enINAbbreviations = '|||T||L||Cr|||TCr||LCr';
const zhAbbreviations = '||||万||||亿||||万亿';
const tests: any[] = [
// Thousand
[enAbbreviations, 1234, '0.00 ak', '1.23 K'],
[enAbbreviations, 1, '0.00 ak', '0.00 K'],
[enAbbreviations, -1200300, '0.00 ak', '-1200.30 K'],
['|||T1|||T2', -1200300, '0.00 ak', '-1200.30 T1'],
// Million
[enAbbreviations, 1200300, '0.00 am', '1.20 M'],
[enAbbreviations, -987, '0.00 am', '0.00 M'],
[enAbbreviations, 1200300400, '0.00 am', '1200.30 M'],
// Billion
[enAbbreviations, 1500300400, '0.00 ab', '1.50 B'],
[enAbbreviations, -1500900300400, '0.00 ab', '-1500.90 B'],
[enAbbreviations, 10500300, '0.00 ab', '0.01 B'],
// Trillion
[enAbbreviations, 1500300400000, '0.00 at', '1.50 T'],
[enAbbreviations, 1500900300400000, '0.00 at', '1500.90 T'],
[enAbbreviations, -10500300000, '0.00 at', '-0.01 T'],
// Fallback into locale closest abbreviation (looking down) Not applying because it doesn't have abbreviation below 1K
[zhAbbreviations, 1500, '0.00 ak', '1500.00'],
[zhAbbreviations, 15000, '0.00 ak', '15000.00'],
[zhAbbreviations, 150000, '0.00 ak', '150000.00'],
// Fallback into locale closest abbreviation (looking down) Applying abbreviation at 10000 because is the closest one to 1M
[zhAbbreviations, 1500, '0.00 am', '0.15 万'],
[zhAbbreviations, 15000, '0.00 am', '1.50 万'],
[zhAbbreviations, 150000, '0.00 am', '15.00 万'],
// Fallback into locale closest abbreviation (looking down)
['|||||T1|||T2', 1400300, '0.00 am', '14.00 T1'],
// Match even while having different abbreviation patterns
[zhAbbreviations, 1500400300200, '0.00 at', '1.50 万亿'],
[enINAbbreviations, 1500400300200, '0.00 at', '1.50 LCr'],
];
tests.forEach(([abbreviations, value, pattern, expectedResult]) => {
const result = format(value, pattern, { locale: { ...en, abbreviations } });
expect([abbreviations, value, pattern, result]).toEqual([abbreviations, value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
it('should fallback to english delimiters if delimiters are not found or invalid', () => {
const tests: any[] = [
[[undefined, undefined], 1234.4, '0,0.0', '1,234.4'],
[[undefined, null], 1234.4, '0,0.0', '1,234.4'],
[[null, undefined], 1234.4, '0,0.0', '1,234.4'],
[[null, null], 1234.4, '0,0.0', '1,234.4'],
[[',', undefined], 1234.4, '0,0.0', '1,234.4'],
[[',', null], 1234.4, '0,0.0', '1,234.4'],
[[undefined, '.'], 1234.4, '0,0.0', '1,234.4'],
[[null, '.'], 1234.4, '0,0.0', '1,234.4'],
// '' is not valid for decimals
[[',', ''], 1234.4, '0,0.0', '1,234.4'],
// equal delimiters (not valid)
[[',', ','], 1234.4, '0,0.0', '1,234.4'],
[['.', '.'], 1234.4, '0,0.0', '1,234.4'],
];
tests.forEach(([[thousands, decimals], value, pattern, expectedResult]) => {
const result = format(value, pattern, getOptionsWithDelimiters(thousands, decimals));
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('.withOptions wrapper', () => {
it('should apply the given options in .withOptions()', () => {
expect(format.withOptions({ nullFormat: 'NULL' })(null, '0,0.0')).toBe('NULL');
expect(format.withOptions({ nanFormat: 'NAN REPLACER' })(NaN, '0,0.0')).toBe('NAN REPLACER');
expect(format.withOptions({ nullFormat: 'NULL', nanFormat: 'NAN REPLACER' })(NaN, '0,0.0')).toBe('NAN REPLACER');
expect(format.withOptions({ zeroFormat: 'MY ZERO FORMAT' })(0, '0,0.0')).toBe('MY ZERO FORMAT');
expect(format.withOptions({ defaultPattern: '0000' })(1)).toBe('0001');
expect(format.withOptions({ rounding: 'floor' })(2.9, '0')).toBe('2');
expect(format.withOptions({ locale: fr })(12345.67, '0,0.000')).toBe('12 345,670');
});
it('should merge the options from .withOptions with the options from the call', () => {
expect(format.withOptions({ nullFormat: 'NULLFROMWITHOPTIONS' })(null, '0,0.0', { zeroFormat: 'FROMCALL' })).toBe('NULLFROMWITHOPTIONS');
expect(format.withOptions({ nullFormat: 'NULLFROMWITHOPTIONS' })(0, '0,0.0', { zeroFormat: 'FROMCALL' })).toBe('FROMCALL');
});
it('should override the options from .withOptions with the options from the call', () => {
expect(format.withOptions({ nullFormat: 'NULL' })(null, '0,0.0', { nullFormat: 'FROMCALL' })).toBe('FROMCALL');
});
it('should resolve the locale function in case it is a function', () => {
const localeAsFunction = (): NumerableLocale => ({ ...en, delimiters: { thousands: ' ** ', decimal: ' && ' } });
expect(
format.withOptions({ locale: localeAsFunction })(12345.67, '0,0.000')
).toBe('12 ** 345 && 670');
});
});
describe('numeral.js compatibility', () => {
it('should provide compatibility with numeral optional decimals pattern format [0]', () => {
const tests: any[] = [
[10000.45,'0[.]00[0]','10000.45'],
[10000.456,'0[.]00[0]','10000.456'],
[0.67,'0.0[0000]','0.67'],
[3162.63,'0.0[00000000000000]','3162.63'],
[1.99,'0.[0]','2'],
[1.0501,'0.00[0]','1.05'],
[0.23, '000.[00]', '000.23'],
[123456, '0.0[0] ak', '123.46 K'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern);
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
describe('formatters', () => {
const getTestFormatter = (
formatMatcher: NumerableFormatter['regexps']['format'],
formatFunction: NumerableFormatter['format'],
): NumerableFormatter => ({
name: 'test-formatter',
regexps: {
format: formatMatcher,
unformat: /t/,
},
format: formatFunction,
unformat: undefined,
});
it('should format using the provided formatter', () => {
// Should receive the value
const formatter1 = getTestFormatter(/\*\*/, (value) => '' + value);
expect(format(1000, '0,0.000 **', { formatters: [formatter1] })).toBe('1000');
// Should receive the pattern
const formatter2 = getTestFormatter(/TEST/, (_value, pattern) => '' + pattern);
expect(format(1000, '0,0.000 TEST', { formatters: [formatter2] })).toBe('0,0.000 TEST');
// Should Call the matcher function
const formatter3 = getTestFormatter(pattern => pattern === '0,0.000 &*', (_value, pattern) => '' + pattern);
expect(format(1000, '0,0.000 &*', { formatters: [formatter3] })).toBe('0,0.000 &*');
// Should avoid the formatter if matcher function returns false
const avoidFormatSpy = jest.fn();
format(1000, '0,0.000 &*', { formatters: [getTestFormatter(() => false, avoidFormatSpy)] });
expect(avoidFormatSpy).toHaveBeenCalledTimes(0);
});
it('should call the formatters resolver if it is provided', () => {
// Using percentage sign (it should be by default catched by built-in percentage formatter, but not in this case)
const formatter = getTestFormatter(/%/, () => 'TEST_STRING');
expect(format(1000, '0,0.000 %', { formatters: builtInFormatters => [formatter, ...builtInFormatters] })).toBe('TEST_STRING');
// Not applying percentage
expect(format(1000, '0,0.000 %', { formatters: () => [] })).toBe('1,000.000 %');
});
it('should apply first the passed formatters (before the built-in ones)', () => {
// Using percentage sign (it should be by default catched by the passed formatter)
const formatter = getTestFormatter(/%/, () => 'TEST_STRING');
expect(format(0.01, '0,0.000 %', { formatters: [formatter] })).toBe('TEST_STRING');
});
});
describe('pattern-mask', () => {
it('should properly preserve spaces in pattern (except global trim)', () => {
const tests: any[] = [
[10000, '0[.]00# a', '10 K'],
[10000, '0.00# a', '10.00 K'],
[10000, '% 0.00 a', '% 1.00 M'],
[-10000, '% 0.00 a', '% -1.00 M'],
[10000, '% 0.00 a', '% 1.00 M'],
[10000, '% a 0.00', '% M 1.00'],
[-10000, '% a 0.00', '% M -1.00'],
[-10000, '% a 0.00', '% M -1.00'],
[10000, '% a 0.00', '% M 1.00'],
[-10000, '( 0,0.00 )', '( 10,000.00 )'],
[-10000, '( 0,0.00 )', '( 10,000.00 )'],
[10000, '0,0 +', '10,000 +'],
[10000, '0,0 +', '10,000 +'],
[10000, '+ 0,0', '+ 10,000'],
[10000, '+ 0,0', '+ 10,000'],
[10000, '- 0,0', '10,000'], // Global trim
[-10000, '- 0,0', '- 10,000'],
[-10000, '( 0,0)', '( 10,000)'],
[-10000, '(0,0 )', '(10,000 )'],
[-0.1, '- #.00', '- .10'],
[-0.1, '- #.00', '- .10'],
[-0.1, '#.00 -', '.10 -'],
[-0.1, '#.00 -', '.10 -'],
[-0.1, '( #.00 )', '( .10 )'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { trim: true });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
});
});
it('should include escaped text in defined position (and unescaped)', () => {
const tests: any[] = [
[10000, "0.00# a 'test1'", '10.00 K test1'],
[10000, "0,0.00 a 'test1' 'test2'", '10.00 K test1 test2'],
[10000, "'test3' 0,0.00 a 'test1' 'test2'", 'test3 10.00 K test1 test2'],
[10000, "'test3' % 0,0.00 a 'test1' 'test2'", 'test3 % 1.00 M test1 test2'],
[10000, "'TEST1' 0,0.00", 'TEST1 10,000.00'],
[10000, "'TEST1' 0,0.00", 'TEST1 10,000.00'],
[10000, "'TEST2' 'TEST1' 0,0.00", 'TEST2 TEST1 10,000.00'],
[10000, "% 'TEST2' 'TEST1' 0,0.00", '% TEST2 TEST1 1,000,000.00'],
[-10000, "('TEST2' 'TEST1' 0,0.00)", '(TEST2 TEST1 10,000.00)'],
[10000, "('TEST2' 'TEST1' 0,0.00)", 'TEST2 TEST1 10,000.00'],
[10000, "+ 'TEST1' 0,0.00", '+ TEST1 10,000.00'],
[10000, "+'TEST1' 0,0.00", '+TEST1 10,000.00'],
[10000, "'TEST1'+ 0,0.00", 'TEST1+ 10,000.00'],
[10000, "'TEST1'a 0,0.00", 'TEST1K 10.00'],
[10000, "a'TEST1' 0,0.00", 'KTEST1 10.00'],
[10000, "'TEST1 TEST2' 0,0.00", 'TEST1 TEST2 10,000.00'],
[10000, "0,0.00 'TEST1 TEST2'", '10,000.00 TEST1 TEST2'],
// Escaping forbidden tokens (a, o, %, +, ())
[10000, "0,0.00 '%'", '10,000.00 %'],
[10000, "0,0.00 'a'", '10,000.00 a'],
[10000, "0,0.00 'ak'", '10,000.00 ak'],
[10000, "0,0.00 'am'", '10,000.00 am'],
[10000, "0,0.00 'ab'", '10,000.00 ab'],
[10000, "0,0.00 'at'", '10,000.00 at'],
[10000, "0,0.00 'o'", '10,000.00 o'],
[10000, "'o' 0,0.00 'o'", 'o 10,000.00 o'],
[10000, "0,0.00 '+'", '10,000.00 +'],
[10000, "0,0.00 '-'", '10,000.00 -'],
[-10000, "0,0.00 '-'", '-10,000.00 -'],
[10000, "0,0.00 '()'", '10,000.00 ()'],
[10000, "0,0.00 '('", '10,000.00 ('],
[10000, "0,0.00 ')'", '10,000.00 )'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { trim: true });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
});
});
it('should include escaped text WITH ESCAPED SEMICOLONS in defined position (and unescaped)', () => {
const tests: any[] = [
[10000, "0.00 'a \\'b\\' c'", "10000.00 a 'b' c"],
[-10000, "0.00 'a \\'b\\' c'", "-10000.00 a 'b' c"],
[-10000, "0.00 'a \\'\\'\\'\\' c'", "-10000.00 a '''' c"],
[-10000, "0.00 '\\'\\'\\'\\''", "-10000.00 ''''"],
[-10000, "0.00 '\\''", "-10000.00 '"],
[-10000, "0.00 '\\'a\\''", "-10000.00 'a'"],
[-10000, "'\\'a\\''0.00", "'a'-10000.00"],
[-10000, "'\\'a\\'' 0.00", "'a' -10000.00"],
[-10000, "'te \\'a\\' te'0.00", "te 'a' te-10000.00"],
[-10000, "'te \\'a\\' te' 0.00", "te 'a' te -10000.00"],
// Escaping forbidden tokens (a, o, %, +, ())
[10000, "0.00 'o \\'a\\' o'", "10000.00 o 'a' o"],
[10000, "0.00 '() \\'a\\' +'", "10000.00 () 'a' +"],
[10000, "0.00 '- \\'a\\' %'", "10000.00 - 'a' %"],
[10000, "0.00 '- \\'%\\' %'", "10000.00 - '%' %"],
[10000, "0.00 '- \\'o\\' %'", "10000.00 - 'o' %"],
[10000, "0.00 '- \\'()\\' %'", "10000.00 - '()' %"],
[10000, "0.00 '- \\'+\\' %'", "10000.00 - '+' %"],
[10000, "0.00 '- \\'-\\' %'", "10000.00 - '-' %"],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { trim: true });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
});
});
it('should properly handle locale items that can potentially include single quotes', () => {
const getOptionsWithDelimiters = (thousands: string, decimal: string) => {
return { locale: { ...en, delimiters: { thousands: thousands, decimal: decimal } } } as NumerableFormatNumberOptions;
};
const getOptionsWithNumeralSystem = (numeralSystem: string[]) => {
return { locale: { ...en, numeralSystem } } as NumerableFormatNumberOptions;
};
const getOptionsWithAbbreviations = (abbreviations: string) => {
return { locale: { ...en, abbreviations } } as NumerableFormatNumberOptions;
};
const getOptionsWithOrdinal = (ordinal: () => string) => {
return { locale: { ...en, ordinal } } as NumerableFormatNumberOptions;
};
const tests: any[] = [
// Delimiters with single quotes
[getOptionsWithDelimiters("'", '.'), 10000, "0,0.00 'a'", "10'000.00 a"],
[getOptionsWithDelimiters(",", "'"), 10000, "0,0.00 'a'", "10,000'00 a"],
// Numeral system
[
getOptionsWithNumeralSystem(["o'", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']),
10000,
"0,0.00 'a'",
"ao',o'o'o'.o'o' a",
],
// Abbreviations
[getOptionsWithAbbreviations("|||k'|||m'|||'b|||'t"), 10000, '0,0 a', "10 k'"],
[getOptionsWithAbbreviations("|||k'|||m'|||'b|||'t"), 10000000, '0,0 a', "10 m'"],
[getOptionsWithAbbreviations("|||k'|||m'|||'b|||'t"), 10000000000, '0,0 a', "10 'b"],
[getOptionsWithAbbreviations("|||k'|||m'|||'b|||'t"), 10000000000000, '0,0 a', "10 't"],
// Ordinal
[getOptionsWithOrdinal(() => "'"), 10000, '0,0 o', "10,000 '"],
[getOptionsWithOrdinal(() => "n'"), 10000, '0,0 o', "10,000 n'"],
[getOptionsWithOrdinal(() => "'n"), 10000, '0,0 o', "10,000 'n"],
[getOptionsWithOrdinal(() => "'n"), 10000, "0,0o 'a'", "10,000'n a"],
];
tests.forEach(([options, value, pattern, expectedResult]) => {
const result = format(value, pattern, { ...options, trim: true });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
});
});
it('should remove the abbreviation space if there is no abbreviation unit resolved', () => {
const tests: any[] = [
[1, '0.00 a +', '1.00 +'],
[1, '+ a 0.00', '+ 1.00'],
[1, '0.00 a %', '100.00 %'],
[1, '0.00 a %', '100.00 %'],
[-1, '0.00 a %', '-100.00 %'],
[1, '% a 0.00', '% 100.00'],
[1, '% a 0.00', '% 100.00'],
[-1, '% a 0.00', '% -100.00'],
];
tests.forEach(([value, pattern, expectedResult]) => {
const result = format(value, pattern, { trim: true });
expect([value, pattern, result]).toEqual([value, pattern, expectedResult]);
expect(typeof result).toBe('string');
});
});
});
}); | the_stack |
import EditorUI = require("../EditorUI");
import ModalWindow = require("./ModalWindow");
import ResourceOps = require("resources/ResourceOps");
import ProjectTemplates = require("resources/ProjectTemplates");
export class ResourceDelete extends ModalWindow {
constructor(asset: ToolCore.Asset) {
super();
this.asset = asset;
this.init("Delete Resource", "AtomicEditor/editor/ui/resourcedelete.tb.txt");
var message = <Atomic.UIEditField>this.getWidget("message");
var text = "Are you sure you want to delete resource:\n\n";
text += asset.path;
text += "\n\nThis operation cannot be undone";
message.text = text;
this.resizeToFitContent();
this.center();
}
handleWidgetEvent(ev: Atomic.UIWidgetEvent) {
if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
var id = ev.target.id;
if (id == "delete") {
this.hide();
let eventData = {
path: this.asset.path
};
var db = ToolCore.getAssetDatabase();
db.deleteAsset(this.asset);
this.sendEvent(Editor.EditorDeleteResourceNotificationEventData(eventData));
return true;
}
if (id == "cancel") {
this.hide();
return true;
}
}
}
asset: ToolCore.Asset;
}
export class CreateFolder extends ModalWindow {
constructor(resourcePath: string) {
super();
this.resourcePath = resourcePath;
this.init("New Folder", "AtomicEditor/editor/ui/resourcenewfolder.tb.txt");
this.nameField = <Atomic.UIEditField>this.getWidget("folder_name");
}
handleWidgetEvent(ev: Atomic.UIWidgetEvent) {
if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
var id = ev.target.id;
if (id == "create") {
var resourcePath = Atomic.addTrailingSlash(this.resourcePath) + this.nameField.text;
if (ResourceOps.CreateNewFolder(resourcePath)) {
this.hide();
}
return true;
}
if (id == "cancel") {
this.hide();
return true;
}
}
}
resourcePath: string;
nameField: Atomic.UIEditField;
}
export class CreateComponent extends ModalWindow {
constructor(resourcePath: string) {
super();
this.resourcePath = resourcePath;
this.init("New Component", "AtomicEditor/editor/ui/resourcecreatecomponent.tb.txt");
this.nameField = <Atomic.UIEditField>this.getWidget("component_name");
this.templateField = <Atomic.UISelectDropdown>this.getWidget("template_list");
this.loadTemplatesList();
}
/**
*
* Gets the template definitions and loads it up
*/
loadTemplatesList() {
this.templates = ProjectTemplates.GetNewFileTemplateDefinitions("component");
this.templateFieldSource.clear();
this.templates.forEach( template => {
this.templateFieldSource.addItem(new Atomic.UISelectItem(template.name));
});
this.templateField.source = this.templateFieldSource;
this.templateField.value = 0;
}
handleWidgetEvent(ev: Atomic.UIWidgetEvent) {
if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
var id = ev.target.id;
if (id == "create") {
var componentName = this.nameField.text;
var outputFile = Atomic.addTrailingSlash(this.resourcePath) + componentName;
let selectedTemplate : Editor.Templates.FileTemplateDefinition = null;
this.templates.forEach(t => {
if (t.name == this.templateField.text) {
selectedTemplate = t;
}
});
if (selectedTemplate) {
// Check to see if we have a file extension. If we don't then use the one defined in the template
if (outputFile.indexOf(".") == -1) {
outputFile += selectedTemplate.ext;
}
if (ResourceOps.CreateNewComponent(outputFile, componentName, selectedTemplate)) {
this.hide();
this.sendEvent(Editor.EditorEditResourceEventData({ path: outputFile, lineNumber: 0 }));
}
return true;
} else {
return false;
}
}
if (id == "cancel") {
this.hide();
return true;
}
}
}
templates: Editor.Templates.FileTemplateDefinition[];
resourcePath: string;
nameField: Atomic.UIEditField;
templateField: Atomic.UISelectDropdown;
templateFieldSource: Atomic.UISelectItemSource = new Atomic.UISelectItemSource();
}
export class CreateScript extends ModalWindow {
constructor(resourcePath: string) {
super();
this.resourcePath = resourcePath;
this.init("New Script", "AtomicEditor/editor/ui/resourcecreatescript.tb.txt");
this.nameField = <Atomic.UIEditField>this.getWidget("script_name");
this.templateField = <Atomic.UISelectDropdown>this.getWidget("template_list");
this.loadTemplatesList();
}
/**
*
* Gets the template definitions and loads it up
*/
loadTemplatesList() {
this.templates = ProjectTemplates.GetNewFileTemplateDefinitions("script");
this.templateFieldSource.clear();
this.templates.forEach( template => {
this.templateFieldSource.addItem(new Atomic.UISelectItem(template.name));
});
this.templateField.source = this.templateFieldSource;
this.templateField.value = 0;
}
handleWidgetEvent(ev: Atomic.UIWidgetEvent) {
if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
var id = ev.target.id;
if (id == "create") {
var scriptName = this.nameField.text;
var outputFile = Atomic.addTrailingSlash(this.resourcePath) + scriptName;
let selectedTemplate : Editor.Templates.FileTemplateDefinition = null;
this.templates.forEach(t => {
if (t.name == this.templateField.text) {
selectedTemplate = t;
}
});
if (selectedTemplate) {
// Check to see if we have a file extension. If we don't then use the one defined in the template
if (outputFile.lastIndexOf(`.${selectedTemplate.ext}`) != outputFile.length - selectedTemplate.ext.length) {
outputFile += selectedTemplate.ext;
}
if (ResourceOps.CreateNewScript(outputFile, scriptName, selectedTemplate)) {
this.hide();
this.sendEvent(Editor.EditorEditResourceEventData({ path: outputFile, lineNumber: 0 }));
}
return true;
} else {
return false;
}
}
if (id == "cancel") {
this.hide();
return true;
}
}
}
templates: Editor.Templates.FileTemplateDefinition[];
resourcePath: string;
nameField: Atomic.UIEditField;
templateField: Atomic.UISelectDropdown;
templateFieldSource: Atomic.UISelectItemSource = new Atomic.UISelectItemSource();
}
export class CreateScene extends ModalWindow {
constructor(resourcePath: string) {
super();
this.resourcePath = resourcePath;
this.init("New Scene", "AtomicEditor/editor/ui/resourcecreateresource.tb.txt");
this.nameField = <Atomic.UIEditField>this.getWidget("component_name");
}
handleWidgetEvent(ev: Atomic.UIWidgetEvent) {
if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
var id = ev.target.id;
if (id == "create") {
var sceneName = this.nameField.text;
var outputFile = Atomic.addTrailingSlash(this.resourcePath) + sceneName;
if (outputFile.indexOf(".scene") == -1) outputFile += ".scene";
if (ResourceOps.CreateNewScene(outputFile, sceneName)) {
this.hide();
this.sendEvent(Editor.EditorEditResourceEventData({ path: outputFile, lineNumber: 0 }));
}
return true;
}
if (id == "cancel") {
this.hide();
return true;
}
}
}
resourcePath: string;
nameField: Atomic.UIEditField;
}
export class CreateMaterial extends ModalWindow {
constructor(resourcePath: string) {
super();
this.resourcePath = resourcePath;
this.init("New Material", "AtomicEditor/editor/ui/resourcecreateresource.tb.txt");
this.nameField = <Atomic.UIEditField>this.getWidget("component_name");
}
handleWidgetEvent(ev: Atomic.UIWidgetEvent) {
if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
var id = ev.target.id;
if (id == "create") {
var materialName = this.nameField.text;
var outputFile = Atomic.addTrailingSlash(this.resourcePath) + materialName;
if (outputFile.indexOf(".material") == -1) outputFile += ".material";
if (ResourceOps.CreateNewMaterial(outputFile, materialName)) {
this.hide();
this.sendEvent(Editor.EditorEditResourceEventData({ path: outputFile, lineNumber: 0 }));
}
return true;
}
if (id == "cancel") {
this.hide();
return true;
}
}
}
resourcePath: string;
nameField: Atomic.UIEditField;
}
export class RenameAsset extends ModalWindow {
constructor(asset: ToolCore.Asset) {
super();
this.asset = asset;
this.init("Rename Resource", "AtomicEditor/editor/ui/renameasset.tb.txt");
var currentName = <Atomic.UITextField>this.getWidget("current_name");
this.nameEdit = <Atomic.UIEditField>this.getWidget("new_name");
currentName.text = asset.name;
this.nameEdit.text = asset.name;
this.resizeToFitContent();
this.center();
this.nameEdit.setFocus();
}
handleWidgetEvent(ev: Atomic.UIWidgetEvent) {
if (ev.type == Atomic.UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
var id = ev.target.id;
if (id == "rename") {
this.hide();
if (this.asset.name != this.nameEdit.text) {
let oldPath = this.asset.path;
this.asset.rename(this.nameEdit.text);
let eventData: Editor.EditorRenameResourceNotificationEvent = {
path: oldPath,
newPath: this.asset.path,
newName: this.nameEdit.text,
asset: this.asset
};
this.sendEvent(Editor.EditorRenameResourceNotificationEventData(eventData));
}
return true;
}
if (id == "cancel") {
this.hide();
return true;
}
}
}
nameEdit: Atomic.UIEditField;
asset: ToolCore.Asset;
} | the_stack |
import assert from 'assert';
import * as util from 'util';
import { parseDate } from './utils/date_utils';
import List from './utils/list';
import { SyntaxType } from './syntax_api';
import {
MeasureEntity,
LocationEntity,
TimeEntity,
DateEntity,
GenericEntity,
AnyEntity,
EntityMap
} from './entities';
import { Temporal } from '@js-temporal/polyfill';
const EPSILON = 1e-8;
function entitiesEqual(type : string, one : AnyEntity, two : AnyEntity, timezone : string) : boolean {
if (one === two)
return true;
if (!one || !two)
return false;
if (type.startsWith('GENERIC_ENTITY_')) {
const eone = one as GenericEntity;
const etwo = two as GenericEntity;
if (!eone.value && !etwo.value)
return eone.display === etwo.display;
return (eone.value === etwo.value);
}
if (type.startsWith('MEASURE_') ||
type === 'DURATION') {
const eone = one as MeasureEntity;
const etwo = two as MeasureEntity;
return eone.value === etwo.value && eone.unit === etwo.unit;
}
switch (type) {
case 'CURRENCY': {
const eone = one as MeasureEntity;
const etwo = two as MeasureEntity;
return eone.value === etwo.value && eone.unit === etwo.unit;
}
case 'TIME': {
const eone = one as TimeEntity;
const etwo = two as TimeEntity;
return eone.hour === etwo.hour &&
eone.minute === etwo.minute &&
(eone.second || 0) === (etwo.second || 0);
}
case 'DATE':
if (!(one instanceof Date))
one = parseDate(one as DateEntity, timezone);
if (!(two instanceof Date))
two = parseDate(two as DateEntity, timezone);
return +one === +two;
case 'LOCATION': {
const eone = one as LocationEntity;
const etwo = two as LocationEntity;
if (isNaN(eone.latitude) && isNaN(etwo.latitude) && isNaN(eone.longitude) && isNaN(etwo.longitude))
return eone.display === etwo.display;
return Math.abs(eone.latitude - etwo.latitude) < EPSILON &&
Math.abs(eone.longitude - etwo.longitude) < EPSILON;
}
}
return false;
}
function entityToString(entityType : string, entity : AnyEntity) : string {
if ((entityType.startsWith('GENERIC_ENTITY_') || entityType === 'LOCATION')) {
const generic = entity as GenericEntity;
if (generic.display)
return generic.display;
if (generic.value)
return generic.value;
}
return String(entity);
}
/**
* Abstract class capable of allocating entity numbers when converting
* ThingTalk code to NN syntax (which uses numbered entities matching the input sentence).
*/
export abstract class AbstractEntityRetriever {
protected _syntaxType : SyntaxType.Tokenized|SyntaxType.LegacyNN;
protected _timezone : string;
constructor(options : {
timezone : string|undefined
}) {
this._timezone = options.timezone ?? Temporal.Now.timeZone().id;
this._syntaxType = SyntaxType.LegacyNN;
}
get timezone() {
return this._timezone;
}
setSyntaxType(syntaxType : SyntaxType.Tokenized|SyntaxType.LegacyNN) {
this._syntaxType = syntaxType;
}
/**
* Find the entity with the given `entityType` (USERNAME, HASHTAG, etc.) and value.
*
* @param entityType - the type of entity to retrieve
* @param value - the value to retrieve
* @param options - additional options
* @param options.ignoreNotFound - return `null` if the entity is not found, instead
* of throwing an exception.
* @return the list of tokens making up this entity.
*/
abstract findEntity(entityType : string, value : AnyEntity, options : { ignoreNotFound : true, includeEntityValue ?: boolean }) : List<string>|null;
abstract findEntity(entityType : string, value : AnyEntity, options ?: { ignoreNotFound ?: false, includeEntityValue ?: boolean }) : List<string>;
}
/**
* Entity retriever that looks for an entity in the tokenized entities, if any, and then
* falls back to string matching in the sentence.
*/
export class EntityRetriever extends AbstractEntityRetriever {
sentence : string[];
entities : EntityMap;
constructor(sentence : string|string[], entities : EntityMap, options : {
timezone : string|undefined
}) {
super(options);
if (typeof sentence === 'string')
sentence = sentence.split(' ');
this.sentence = sentence;
this.entities = {};
Object.assign(this.entities, entities);
}
protected _sentenceContains(tokens : string[]) : boolean {
for (let i = 0; i <= this.sentence.length-tokens.length; i++) {
let found = true;
for (let j = 0; j < tokens.length; j++) {
if (tokens[j] !== this.sentence[i+j]) {
found = false;
break;
}
}
if (found)
return true;
}
return false;
}
/**
* Match an entity from the sentence.
*
* This method should search for the entity string in the sentence, and return the value
* to predict in NN-syntax, or `undefined` if the entity is not mentioned.
* This method can be overridden to implement custom tokenization or normalization.
*
* @param {string} entityType - the entity type (USERNAME, HASHTAG, QUOTED_STRING, etc.)
* @param {string} entityString - the string to search
* @param {boolean} ignoreNotFound - ignore if the entity is not mentioned; subclasses can
* use this to hallucinate entities that are not mentioned, when `ignoreNotFound` is false
* @return the tokens to predict, or `undefined` if the entity is not mentioned in the sentence.
*/
protected _findEntityFromSentence(entityType : string, entityString : string, ignoreNotFound : boolean) : string[]|undefined {
const entityTokens = entityString.toLowerCase().split(' ');
const found = this._sentenceContains(entityTokens);
if (found)
return entityTokens;
else
return undefined;
}
/**
* Match a numeric entity from the sentence.
*
* This method should search for a mention of the number in the sentence, and return the value
* to predict in NN-syntax, or `undefined` if the entity is not mentioned.
* This method can be overridden to implement custom tokenization or normalization.
*
* @param {string} entityType - the numeric entity type (NUMBER, MEASURE, CURRENCY, etc.)
* @param {number} number - the number to search
* @param {boolean} ignoreNotFound - ignore if the number is not mentioned; subclasses can
* use this to hallucinate entities that are not mentioned, when `ignoreNotFound` is false
* @return the tokens to predict, or `undefined` if the entity is not mentioned in the sentence.
*/
protected _findNumberFromSentence(entityType : string, number : number, ignoreNotFound : boolean) : string[]|undefined {
// by default, we normalize using JS syntax for numbers: "." for decimal
// separator, and no thousand separator
const entityTokens = [String(number)];
const found = this._sentenceContains(entityTokens);
if (found)
return entityTokens;
else
return undefined;
}
private _findStringLikeEntity(entityType : string,
entity : AnyEntity,
entityString : string,
ignoreNotFound : boolean,
includeEntityValue : boolean) : List<string>|undefined {
if (entityType === 'DATE') {
const dateStr = (entity as Date).toISOString();
if (this._sentenceContains([dateStr]))
return List.concat('new', 'Date', '(', '"', dateStr, '"', ')');
}
if (entityType === 'NUMBER') {
const found = this._findNumberFromSentence(entityType, entity as number, ignoreNotFound);
if (found) // ignore the returned tokens, and always predict normalized English-like syntax
return List.singleton(String(entity));
}
if (entityType === 'CURRENCY' || entityType === 'DURATION' || entityType.startsWith('MEASURE_')) {
const measure = entity as MeasureEntity;
const found = this._findNumberFromSentence(entityType, measure.value, ignoreNotFound);
if (found) // ignore the returned tokens, and always predict normalized English-like syntax
return List.concat(String(measure.value), entityType === 'CURRENCY' ? ('$' + measure.unit) : measure.unit);
}
if (entityType === 'QUOTED_STRING' || entityType === 'HASHTAG' || entityType === 'USERNAME' ||
entityType === 'PATH_NAME' || entityType === 'URL' || entityType === 'PHONE_NUMBER' ||
entityType === 'EMAIL_ADDRESS' || entityType === 'LOCATION' || entityType.startsWith('GENERIC_ENTITY_')) {
const found = this._findEntityFromSentence(entityType, entityString, ignoreNotFound);
if (found) {
if (entityType === 'QUOTED_STRING')
return List.concat('"', ...found, '"');
else if (entityType === 'HASHTAG')
return List.concat('"', ...found, '"', '^^tt:hashtag');
else if (entityType === 'USERNAME')
return List.concat('"', ...found, '"', '^^tt:username');
else if (entityType === 'PATH_NAME')
return List.concat('"', ...found, '"', '^^tt:path_name');
else if (entityType === 'URL')
return List.concat('"', ...found, '"', '^^tt:url');
else if (entityType === 'PHONE_NUMBER')
return List.concat('"', ...found, '"', '^^tt:phone_number');
else if (entityType === 'EMAIL_ADDRESS')
return List.concat('"', ...found, '"', '^^tt:email_address');
if (this._syntaxType === SyntaxType.LegacyNN) {
if (entityType === 'LOCATION')
return List.concat('location:', '"', ...found, '"');
else
return List.concat('"', ...found, '"', '^^' + entityType.substring('GENERIC_ENTITY_'.length));
} else {
if (entityType === 'LOCATION') {
return List.concat('new', 'Location', '(', '"', ...found, '"', ')');
} else {
const genericEntity = entity as GenericEntity;
const entityId = includeEntityValue && genericEntity.value ? [ '"', ...genericEntity.value.split(' '), '"'] : ['null'];
return List.concat(...entityId, '^^' + entityType.substring('GENERIC_ENTITY_'.length), '(', '"', ...found, '"', ')');
}
}
}
}
// always predict (not copy) these entities if they are missing from the sentence
// (the neural model will learn the names of the devices
if (entityType === 'GENERIC_ENTITY_tt:device') {
const value = (entity as GenericEntity).value!;
if (this._syntaxType === SyntaxType.LegacyNN)
return List.singleton('device:' + value);
else
return List.singleton('@' + value);
}
if (entityType === 'GENERIC_ENTITY_tt:function') {
const value = (entity as GenericEntity).value!;
if (this._syntaxType === SyntaxType.LegacyNN) {
return List.singleton('@' + value);
} else {
const dot = value.lastIndexOf('.');
const kind = value.substring(0, dot);
const name = value.substring(dot+1, value.length);
return List.concat('@' + kind, '.', name);
}
}
return undefined;
}
private _findEntityInBag(entityType : string, value : AnyEntity, entities : EntityMap) : List<string>|undefined {
for (const what in entities) {
if (!what.startsWith(entityType + '_'))
continue;
if (entitiesEqual(entityType, entities[what], value, this._timezone))
return List.singleton(what);
}
return undefined;
}
findEntity(entityType : string, entity : AnyEntity, options : { ignoreNotFound : true, includeEntityValue ?: boolean }) : List<string>|null;
findEntity(entityType : string, entity : AnyEntity, options ?: { ignoreNotFound ?: false, includeEntityValue ?: boolean }) : List<string>;
findEntity(entityType : string, entity : AnyEntity, { ignoreNotFound = false, includeEntityValue = false } = {}) : List<string>|null {
const entityString = entityToString(entityType, entity);
// try in the sentence before we look in the bag of entities (which comes from the context)
// this is so that we predict
// " foo " ^^tt:whatever
// if the sentence contains "foo", regardless of whether GENERIC_ENTITY_tt:whatever_0 is "foo" or not
let found = this._findStringLikeEntity(entityType, entity, entityString, true, includeEntityValue);
if (found)
return found;
found = this._findEntityInBag(entityType, entity, this.entities);
if (found)
return found;
if (ignoreNotFound)
return null;
if (entityType.startsWith('GENERIC_ENTITY_') && this._syntaxType === SyntaxType.Tokenized) {
const genericEntity = entity as GenericEntity;
if (genericEntity.display) {
found = this._findEntityInBag('QUOTED_STRING', genericEntity.display, this.entities);
if (found) {
const entityId = includeEntityValue && genericEntity.value ? ['"', genericEntity.value, '"'] : ['null'];
return List.concat(...entityId, '^^' + entityType.substring('GENERIC_ENTITY_'.length), '(', found, ')');
}
}
}
found = this._findStringLikeEntity(entityType, entity, entityString, false, includeEntityValue);
if (found)
return found;
throw new Error(`Cannot find entity ${entityString} of type ${entityType}, have ${util.inspect(this.entities)}`);
}
}
export class SequentialEntityAllocator extends AbstractEntityRetriever {
offsets : { [key : string] : number };
entities : EntityMap;
explicitStrings : boolean;
constructor(entities : EntityMap, options : {
timezone : string|undefined,
explicitStrings ?: boolean
}) {
super(options);
this.offsets = {};
this.entities = entities;
this.explicitStrings = !!options.explicitStrings;
this.updateOffsets();
}
reset() {
this.offsets = {};
this.entities = {};
}
private updateOffsets() : void {
for (const entity in this.entities) {
const entityType = entity.slice(0, entity.lastIndexOf('_'));
const offset = entity.slice(entity.lastIndexOf('_') + 1);
assert(/^\d+$/.test(offset));
this.offsets[entityType] = Math.max((this.offsets[entityType] || -1), parseInt(offset) + 1);
}
}
findEntity(entityType : string, entity : AnyEntity, { ignoreNotFound = false, includeEntityValue = false } = {}) : List<string> {
if (this.explicitStrings &&
(entityType === 'QUOTED_STRING' || entityType === 'HASHTAG' || entityType === 'USERNAME' ||
entityType === 'LOCATION' || entityType.startsWith('GENERIC_ENTITY_'))) {
const entityString = entityToString(entityType, entity).split(' ');
if (entityType === 'QUOTED_STRING')
return List.concat('"', ...entityString, '"');
else if (entityType === 'HASHTAG')
return List.concat('"', ...entityString, '"', '^^tt:hashtag');
else if (entityType === 'USERNAME')
return List.concat('"', ...entityString, '"', '^^tt:username');
if (this._syntaxType === SyntaxType.LegacyNN) {
if (entityType === 'LOCATION')
return List.concat('location:', '"', ...entityString, '"');
else
return List.concat('"', ...entityString, '"', '^^' + entityType.substring('GENERIC_ENTITY_'.length));
} else {
if (entityType === 'LOCATION') {
return List.concat('new', 'Location', '(', '"', ...entityString, '"', ')');
} else {
const genericEntity = entity as GenericEntity;
const entityId = includeEntityValue && genericEntity.value ? ['"', genericEntity.value, '"'] : ['null'];
return List.concat(...entityId, '^^' + entityType.substring('GENERIC_ENTITY_'.length), '(', '"', ...entityString, '"', ')');
}
}
}
for (const what in this.entities) {
if (!what.startsWith(entityType + '_'))
continue;
if (entitiesEqual(entityType, this.entities[what], entity, this._timezone))
return List.singleton(what);
}
let num;
if (entityType in this.offsets) {
num = this.offsets[entityType];
this.offsets[entityType] += 1;
} else {
num = 0;
this.offsets[entityType] = 1;
}
const key = entityType + '_' + num;
this.entities[key] = entity;
return List.singleton(key);
}
} | the_stack |
declare class Podium {
/**
* Creates a new podium emitter.
*
* @param events - If present, the value is passed to podium.registerEvent().
*/
constructor(events?: Podium.Event | Podium.Event[]);
/**
* Register the specified events and their optional configuration. Events must be registered
* before they can be emitted or subscribed to. This is done to detect event name mispelling
* and invalid event activities.
*
* @param events - The event(s) to register.
*/
registerEvent(events: Podium.Event | Podium.Event[]): void;
/**
* Registers another emitter as an event source for the current emitter (any event update
* emitted by the source emitter is passed to any subscriber of the current emitter).
*
* Note that any events registered with a source emitter are automatically added to the current
* emitter. If the events are already registered, they are left as-is.
*
* @param podiums - A Podium object or an array of objects, each added as a source.
*/
registerPodium(podiums: Podium | Podium[]): void;
/**
* Emits an event update to all the subscribed listeners.
* @param criteria - The event update criteria.
* @param data - The value emitted to the subscribers.
*
* @returns Promise that resolves when all events has been processed. Any errors will cause an
* immediate rejection.
*/
emit(criteria: string | Podium.EmitCriteria, data?: any): Promise<void>;
/**
* Subscribe a handler to an event.
*
* @param criteria - The subscription criteria.
* @param listener - The handler method set to receive event updates. The function signature
* depends on the block, spread, and tags options.
* @param context - Optional object that binds to the listener handler.
*
* @returns A reference to the current emitter.
*/
on<TArgs extends any[] = unknown[], Tcontext extends object = this>(criteria: string | Podium.CriteriaObject, listener: Podium.Listener<Tcontext, TArgs>, context?: Tcontext): this;
on<TArgs extends any[] = any[], Tcontext extends object = this>(criteria: string | Podium.CriteriaObject, listener: Podium.Listener<Tcontext, TArgs>, context?: Tcontext): this;
/**
* Subscribe a handler to an event. Same as podium.on().
*
* @param criteria - The subscription criteria.
* @param listener - The handler method set to receive event updates. The function signature
* depends on the block, spread, and tags options.
* @param context - Optional object that binds to the listener handler.
*
* @returns A reference to the current emitter.
*/
addListener<TArgs extends any[] = unknown[], Tcontext extends object = this>(criteria: string | Podium.CriteriaObject, listener: Podium.Listener<Tcontext, TArgs>, context?: Tcontext): this;
addListener<TArgs extends any[] = any[], Tcontext extends object = this>(criteria: string | Podium.CriteriaObject, listener: Podium.Listener<Tcontext, TArgs>, context?: Tcontext): this;
/**
* Same as podium.on() with the count option set to 1.
*
* Can also be called without an listener to wait for a single event.
*
* @param criteria - The subscription criteria.
* @param listener - The handler method set to receive event updates. The function signature
* depends on the block, spread, and tags options.
* @param context - Optional object that binds to the listener handler.
*
* @returns A reference to the current emitter.
*/
once<TArgs extends any[] = unknown[], Tcontext extends object = this>(criteria: string | Omit<Podium.CriteriaObject, 'count'>, listener: Podium.Listener<Tcontext, TArgs>, context?: Tcontext): this;
once<TArgs extends any[] = any[], Tcontext extends object = this>(criteria: string | Omit<Podium.CriteriaObject, 'count'>, listener: Podium.Listener<Tcontext, TArgs>, context?: Tcontext): this;
/**
* Wait for a single event. The count option is fixed to 1.
*
* @param criteria - The subscription criteria.
*
* @returns Promise with array of emitted parameters.
*/
once<TArgs extends any[] = unknown[], Tcontext extends void = void>(criteria: string | Omit<Podium.CriteriaObject, 'count'>): Promise<TArgs>;
once<TArgs extends any[] = any[], Tcontext extends void = void>(criteria: string | Omit<Podium.CriteriaObject, 'count'>): Promise<TArgs>;
/**
* Removes all listeners subscribed to a given event name matching the provided listener method.
*
* @param name - The event name string.
* @param listener - The function reference provided when subscribed.
*
* @returns A reference to the current emitter.
*/
removeListener(name: string, listener: Podium.Listener): this;
/**
* Removes all listeners subscribed to a given event name.
*
* @param name - The event name string.
*
* @returns A reference to the current emitter.
*/
removeAllListeners(name: string): this;
/**
* Returns whether an event has any listeners subscribed.
*
* @param name the event name string.
*
* @returns true if the event name has any listeners, otherwise false.
*/
hasListeners(name: string): boolean;
}
declare namespace Podium {
export interface EmitCriteria {
/**
* Event name.
*/
readonly name: string;
/**
* Channel name.
*/
readonly channel?: string;
/**
* The tags to apply.
*/
readonly tags?: string | string[] | { [tag: string]: boolean };
}
export interface EventOptions {
/**
* Event name.
*/
readonly name: string;
/**
* A string or array of strings specifying the event channels available.
*
* Defaults to no channel restrictions - Event updates can specify a channel or not.
*/
readonly channels?: string | string[];
/**
* Set to make podium.emit() clone the data object passed to it, before it is passed to the
* listeners (unless an override specified by each listener).
*
* Defaults to false - Data is passed as-is.
*/
readonly clone?: boolean;
/**
* Set to require the data object passed to podium.emit() to be an array, and make the
* listener method called with each array element passed as a separate argument (unless an
* override specified by each listener).
*
* This should only be used when the emitted data structure is known and predictable.
*
* Defaults to false - Data is emitted as a single argument regardless of its type.
*/
readonly spread?: boolean;
/**
* Set to make any tags in the critieria object passed to podium.emit() map to an object
* (where each tag string is the key and the value is true) which is appended to the emitted
* arguments list at the end.
*
* A configuration override can be set by each listener.
*
* Defaults to false.
*/
readonly tags?: boolean;
/**
* Set to allow the same event name to be registered multiple times, ignoring all but the
* first.
*
* Note that if the registration config is changed between registrations, only the first
* configuration is used.
*
* Defaults to false - A duplicate registration will throw an error.
*/
readonly shared?: boolean;
}
type Event = string | EventOptions | Podium;
type Listener<TContext extends object = any, TArgs extends any[] = any[]> =
(this: TContext, ...args: TArgs) => void | Promise<void>;
interface CriteriaFilterOptionsObject {
/**
* A tag string or array of tag strings.
*/
readonly tags?: string | string[];
/**
* Require all tags to be present for the event update to match the subscription.
*
* Default false - Require at least one matching tag.
*/
readonly all?: boolean;
}
export interface CriteriaObject {
/**
* Event name.
*/
readonly name: string;
/**
* The event channels to subscribe to.
*
* If the event registration specified a list of allowed channels, the channels array must
* match the allowed channels. If channels are specified, event updates without any channel
* designation will not be included in the subscription.
*
* Defaults to no channels filter.
*/
readonly channels?: string | string[];
/**
* Set to clone the data object passed to podium.emit() before it is passed to the listener
* method.
*
* Defaults to the event registration option (which defaults to false).
*/
readonly clone?: boolean;
/**
* A positive non-zero integer indicating the number of times the listener can be called
* after which the subscription is automatically removed.
*
* Does nothing when calling once(), where it will use the value 1.
*
* Defaults to no limit.
*/
readonly count?: number;
/**
* The event tags (if present) to subscribe to.
*/
readonly filter?: string | string[] | CriteriaFilterOptionsObject;
/**
* Override the value of spread from the event registraiont when the listener is called.
*
* This should only be used when the emitted data structure is known and predictable.
*
* Defaults to the event registration option (which defaults to false).
*/
readonly spread?: boolean;
/**
* Override the value of tags from the event registraiont when the listener is called.
*
* Defaults to the event registration option (which defaults to false).
*/
readonly tags?: boolean;
}
}
export = Podium; | the_stack |
//TODO: restore "ATATiterator" to "@@iterator"
/*@ qualif HasP (x: string, y: A): hasProperty(x, y) */
/*@ qualif EnumP(x: string, y: A): enumProp(x, y) */
module com {
module cognitect {
module transducers {
/*@ predicate Inst(X, Key, Type) = (hasProperty(Key, X) <=> extends_interface(X, Type)) */
/*@ predicate InstIterator(V) = Inst(V,"next","Iterator") */
/*@ predicate InstIterable(V) = Inst(V,"ATATiterator","Iterable") */
/*@ predicate IsIter(V) = extends_interface(V,"Iterator") || extends_interface(V,"Iterable") */
/*@ type ObjectK = { v: EmptyObject<Immutable> | InstIterator(v) && InstIterable(v) } */
/*@ type ObjIter = { v: ObjectK | IsIter(v) } */
/*@ type ObjNoIter = { v: ObjectK | not IsIter(v) } */
/*@ type MTransformer<T, U, V> = Transformer<Mutable, T, U, V> */
declare type MTransformer<T, U, V> = Transformer<Mutable, T, U, V>;
/*@ type MTransducer<A,B,C,T,U,V> = (MTransformer<A,B,C>)=>MTransformer<T,U,V> */
/*@ type MQQ<T> = QQ<Mutable,T> */
declare type MQQ<T> = QQ<Mutable,T>;
interface Pair<M extends ReadOnly, A, B> { x: A; y: B; }
declare type Entry<M extends ReadOnly> = Pair<M, string, any>;
/*@ type MMap<T> = (Mutable){[s:string]:T} */
declare type MMap<T> = {[s:string]:T};
interface Goog<M extends ReadOnly> {
/*@ typeOf <M, T> (x:Array<M,T>) : {string | v = "array"} */
/*@ typeOf (x:top) : {string | v != "array"} */
typeOf(x:any):string;
}
declare let goog:Goog<Immutable>;
interface IterResult<M extends ReadOnly> {
done:boolean;
value:any;
}
class EmptyObject<M extends ReadOnly> {
constructor() { }
}
interface Iterator<M extends ReadOnly> extends EmptyObject<M> {
next():IterResult<M>;
}
interface Iterable<M extends ReadOnly> extends EmptyObject<M> {
ATATiterator():Iterator<M>;
}
interface TruncatedTransformer<M extends ReadOnly, IN, INTER> {
init:()=>INTER;
/*@ step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step:(result:INTER, input:IN)=>MQQ<INTER>;
}
interface Transformer<M extends ReadOnly, IN, INTER, OUT> extends TruncatedTransformer<M, IN, INTER> {
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result:(result:MQQ<INTER>)=>OUT;
}
// "use strict";
// goog.provide("com.cognitect.transducers");
// =============================================================================
// Build target config
/** @define {boolean} */
/*@ readonly */
let TRANSDUCERS_DEV = true;
/** @define {boolean} */
/*@ readonly */
let TRANSDUCERS_NODE_TARGET = false;
/** @define {boolean} */
/*@ readonly */
let TRANSDUCERS_BROWSER_TARGET = false;
/** @define {boolean} */
/*@ readonly */
let TRANSDUCERS_BROWSER_AMD_TARGET = false;
// goog.scope(function() {
// /**
// * @class transducers
// */
// let transducers = com.cognitect.transducers;
// =============================================================================
// Utilities
/*@ isString :: (x:top) => {boolean | (Prop v) <=> (ttag(x) = "string")} */
function isString(x:any) {
return typeof x === "string";
}
//TODO
// if(typeof Array.isArray != "undefined") {
// transducers.isArray = function(x) {
// return Array.isArray(x);
// }
// } else {
/*@ isArray :: <M, T> (x:Array<M,T>) => {boolean | Prop v} */
/*@ isArray :: (x:top) => {boolean | not (Prop v)} */
function isArray(x:any) {
return goog.typeOf(x) === "array";
}
// }
function isObject(x:any) {
return goog.typeOf(x) === "object";
}
/*@ isIterable :: <T> (x:ObjectK) => {boolean | Prop(v) <=> IsIter(x)} */
function isIterable(x:any) {
assume(false);
return ("ATATiterator" in x) || ("next" in x);
}
// NOTICE: this seems inherently not typesafe and thus impossible to support
// transducers.slice = function(arrayLike, start, n) {
// if(n == null) {
// return Array.prototype.slice.call(arrayLike, start);
// } else {
// return Array.prototype.slice.call(arrayLike, start, n);
// }
// };
/**
* Take a predicate function and return its complement.
* @method transducers.complement
* @param {function} a predicate function
* @return {function} the complement predicate function
* @example
* let isEven = function(n) { return n % 2 == 0; };
* let isOdd = transducers.complement(isEven);
*/
//TODO: this now only supports unary functions
/*@ complement :: <T> ((T)=>top) => (T) => {boolean | 0 < 1} */
function complement(f) {
/*@ readonly */
let ff = f;
return function(y)
/*@ <anonymous> (T) => {boolean | 0 < 1} */
{ return !ff(y) };
}
class Wrap<M extends ReadOnly, IN, OUT> implements Transformer<M, IN, OUT, OUT> {
/*@ stepFn : (OUT, IN)=>MQQ<OUT> */
public stepFn: (result:OUT, input:IN)=>MQQ<OUT>;
/*@ new (stepFn:(result:OUT, input:IN)=>MQQ<OUT>) : {Wrap<M, IN, OUT> | 0 < 1} */
constructor(stepFn:(result:OUT, input:IN)=>MQQ<OUT>) {
this.stepFn = stepFn;
}
init():OUT {
throw new Error("init not implemented");
}
/*@ result (result:MQQ<OUT>) : {OUT | 0 < 1} */
result(result:MQQ<OUT>):OUT {
return result.value; //TODO: to maintain the original generality this should actually just be 'result' and the return value is then QQ<OUT>
}
/*@ step (result:OUT, input:IN) : {MQQ<OUT> | 0 < 1} */
step(result:OUT, input:IN):MQQ<OUT> {
return this.stepFn(result, input);
}
}
/**
* Take a two-arity reducing function where the first argument is the
* accumluation and the second argument is the next input and convert
* it into a transducer transformer object.
* @method transducers.wrap
* @param {function} stepFn a two-arity reducing function
* @return {transducers.Wrap} a transducer transformer object
* @example
* let t = transducers;
* let arrayPush = t.wrap(function(arr, x) { arr.push(x); return arr; });
*/
/*@ wrap :: <IN, OUT, M> (stepFn: (result:OUT, input:IN)=>OUT) => {Wrap<M, IN, OUT> | 0 < 1} */
/*@ wrap :: <IN, T, OUT> (stepFn: MTransformer<IN, T, OUT>) => {MTransformer<IN, T, OUT> | 0 < 1} */
function wrap<IN, OUT>(stepFn:any) {
if(typeof stepFn === "function") {
return generalWrap(addQQ0(stepFn));
} else {
return stepFn;
}
}
/*@ addQQ0 :: <M, T, U> (stepFn:(T,U)=>T) => (T,U) => {QQ<M,T> | 0 < 1} */
function addQQ0<T, U>(stepFn:(T,U)=>T):(T,U)=>MQQ<T> {
/*@ readonly */
let ff = stepFn;
return function(t:T, u:U)
/*@ <anonymous> (T,U)=>{QQ<M,T> | 0 < 1} */
{ return new QQ(ff(t,u), 0) };
}
/*@ generalWrap :: <IN, OUT, M> (stepFn: (result:OUT, input:IN)=>MQQ<OUT>) => {Wrap<M, IN, OUT> | 0 < 1} */
/*@ generalWrap :: <IN, T, OUT> (stepFn: MTransformer<IN, T, OUT>) => {MTransformer<IN, T, OUT> | 0 < 1} */
function generalWrap(stepFn:any) {
if(typeof stepFn === "function") {
return new Wrap(stepFn);
} else {
return stepFn;
}
}
// =============================================================================
// Main
class QQ<M extends ReadOnly, T> {
/*@ __transducers_reduced__ : number */
public __transducers_reduced__:number;
public value:T;
/*@ new (value:T, reducedCount:number) : {QQ<M, T> | 0 < 1} */
constructor(value:T, reducedCount:number) {
this.__transducers_reduced__ = reducedCount;
this.value = value;
}
}
/**
* Return a reduced value. Reduced values short circuit transduce.
* @method transducers.reduced
* @param {Object} x any JavaScript value
* @return {transducers.Reduced} a reduced value
* @example
* let reduced = transducers.reduced(1);
*/
// TODO
// /*@ reduced :: <T, M> (T) => {QQ<M, T> | 0 < 1} */
// function reduced<T>(x:T) {
// return new QQ(x, true);
// }
/**
* Check if a value is reduced.
* @method transducers.isReduced
* @param {Object} x any JavaScript value
* @return {Boolean} true if the value is an instance of transducers.Reduced
* false otherwise
* @example
* let t = transducers;
* t.isReduced(1); // false
* t.isReduced(t.reduced(1)); // true
*/
/*@ isReduced :: <T> (x:QQ<ReadOnly, T>) => {boolean | 0 < 1} */
function isReduced<T>(x:QQ<ReadOnly, T>) {
return (x.__transducers_reduced__ > 0); //TODO:(x instanceof Reduced || (x && x.__transducers_reduced__);
}
// NOTICE: ensureReduced and unreduced removed as irrelevant to the new formulation of Reduced as QQ
//TODO
// /*@ deref :: <T, M> (QQ<M, T>) => {T | 0 < 1} */
// function deref<T>(x:QQ<T>):T {
// return x.value;
// }
/**
* Identity function.
* @method transducers.identiy
* @param {Object} x any JavaScript value
* @return {Object} a JavaScript value
* @example
* transducers.identity(1); // 1
*/
/*@ identity :: <T> (x:T) => {T | v = x} */
function identity<T>(x:T):T {
return x;
}
/**
* Function composition. Take N function and return their composition.
* @method transducers.comp
* @param {Function} varArgs N functions
* @result {Function} a function that represent the composition of the arguments.
* @example
* let t = transducers;
* let inc = function(n) { return n + 1 };
* let double = function(n) { return n * 2 };
* let incDouble = t.comp(double, inc);
* incDouble(3); // 8
*/
//TODO
/*@ comp :: <S, T, U> (f:(T)=>U, g:(S)=>T) => (S) => {U | 0 < 1} */
/* PORT TODO: comp :: <T> (f:(T)=>T, g:{IArray<(T)=>T> | (len g) > 0}) => (T) => {T | 0 < 1} */
function comp(f:Function, g:any) {
if (typeof g === "function") {
return binaryComp(f,g);
} else {
return reduce(binaryComp, f, g);
}
}
/*@ binaryComp :: <S, T, U> (f:(T)=>U, g:(S)=>T) => (S) => {U | 0 < 1} */
function binaryComp(f, g) {
/*@ readonly */
let ff = f;
/*@ readonly */
let gg = g;
return function(s)
/*@ <anonymous> (S)=>{U | 0 < 1} */
{ return ff(gg(s)) }
}
class Map<M extends ReadOnly, IN, INTER, OUT, T> implements Transformer<M, IN, INTER, OUT> {
public f: (z:IN) => T;
/*@ xf : MTransformer<T, INTER, OUT> */
public xf: MTransformer<T, INTER, OUT>;
/*@ new (f:(IN) => T, xf:MTransformer<T, INTER, OUT>) : {Map<M, IN, INTER, OUT, T> | 0 < 1} */
constructor(f:(z:IN) => T, xf:MTransformer<T, INTER, OUT>) {
this.f = f;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
return this.xf.step(result, this.f(input));
}
}
/**
* Mapping transducer constructor
* @method transducers.map
* @param {Function} f the mapping operation
* @return {transducers.Map} returns a mapping transducer
* @example
* let t = transducers;
* let inc = function(n) { return n+1; };
* let xf = t.map(inc);
* t.into([], xf, [1,2,3]); // [2,3,4]
*/
/*@ map :: <IN, INTER, OUT, T, M> (f: (IN)=>T) => (xf: MTransformer<T, INTER, OUT>) => {Map<M, IN, INTER, OUT, T> | 0 < 1} */
function map<M extends ReadOnly, IN, INTER, OUT, T>(f: (IN)=>T): (xf: MTransformer<T, INTER, OUT>) => Map<M, IN, INTER, OUT, T> {
/*@ readonly */
let ff = f;
if(TRANSDUCERS_DEV && (f === null)) {
throw new Error("At least one argument must be supplied to map");
} else {
return function(xf)
/*@ <anonymous> <M> (xf: MTransformer<T, INTER, OUT>) => {Map<M, IN, INTER, OUT, T> | 0 < 1} */
{ return new Map(ff, xf); };
}
}
class Filter<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
public pred: (z:IN) => boolean;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (pred:(IN) => boolean, xf:MTransformer<IN, INTER, OUT>) : {Filter<M, IN, INTER, OUT> | 0 < 1} */
constructor(pred: (z:IN) => boolean, xf: MTransformer<IN, INTER, OUT>) {
this.pred = pred;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
if(this.pred(input)) {
return this.xf.step(result, input);
} else {
return new QQ(result, 0);
}
}
}
/**
* Filtering transducer constructor
* @method transducers.filter
* @param {Function} pred a predicate function
* @return {transducers.Filter} returns a filtering transducer
* @example
* let t = transducers;
* let isEven = function(n) { return n % 2 == 0; };
* let xf = t.filter(isEven);
* t.into([], xf, [0,1,2,3,4]); // [0,2,4];
*/
/*@ filter :: <IN, INTER, OUT, M> (pred: (IN)=>boolean) => (xf: MTransformer<IN, INTER, OUT>) => {Filter<Unique, IN, INTER, OUT> | 0 < 1} */
function filter<IN, INTER, OUT>(pred: (IN)=>boolean): (xf: MTransformer<IN, INTER, OUT>) => Filter<Unique, IN, INTER, OUT> {
/*@ readonly */
let ff = pred;
if(TRANSDUCERS_DEV && (typeof pred !== "function")) {
throw new Error("filter must be given a function");
} else {
return function(xf)
/*@ <anonymous> <M> (MTransformer<IN, INTER, OUT>) => {Filter<M, IN, INTER, OUT> | 0 < 1} */
{ return new Filter(ff, xf) };
}
}
/**
* Similar to filter except the predicate is used to
* eliminate values.
* @method transducers.remove
* @param {Function} pred a predicate function
* @return {transducers.Filter} returns a removing transducer
* @example
* let t = transducers;
* let isEven = function(n) { return n % 2 == 0; };
* let xf = t.remove(isEven);
* t.into([], xf, [0,1,2,3,4]); // [1,3];
*/
/*@ remove :: <IN, INTER, OUT, M> (pred: (IN)=>boolean) => (xf: MTransformer<IN, INTER, OUT>) => {Filter<M, IN, INTER, OUT> | 0 < 1} */
function remove<M extends ReadOnly, IN, INTER, OUT>(pred: (IN)=>boolean): (xf: MTransformer<IN, INTER, OUT>) => Filter<M, IN, INTER, OUT> {
if(TRANSDUCERS_DEV && (typeof pred !== "function")) {
throw new Error("remove must be given a function");
} else {
return filter<IN, INTER, OUT>(complement(pred));
}
}
class Take<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
/*@ n : number */
public n: number;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (n:number, xf:MTransformer<IN, INTER, OUT>) : {Take<M, IN, INTER, OUT> | 0 < 1} */
constructor(n:number, xf:MTransformer<IN, INTER, OUT>) {
this.n = n;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ @Mutable step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
let retval;
if(this.n > 0) {
retval = this.xf.step(result, input);
} else {
retval = new QQ(result, 1); //TODO: modified semantics here...
}
this.n--;
return retval;
}
}
/**
* A take transducer constructor. Will take n values before
* returning a reduced result.
* @method transducers.take
* @param {Number} n the number of inputs to receive.
* @return {transducers.Take} a take transducer
* @example
* let t = transducers;
* let xf = t.take(3);
* t.into([], xf, [0,1,2,3,4,5]); // [0,1,2];
*/
/*@ take :: <IN, INTER, OUT, M> (n:number) => (xf: MTransformer<IN, INTER, OUT>) => {Take<M, IN, INTER, OUT> | 0 < 1} */
function take<M extends ReadOnly, IN, INTER, OUT>(n:number): (xf: MTransformer<IN, INTER, OUT>) => Take<M, IN, INTER, OUT> {
/*@ readonly */
let nn = n;
if(TRANSDUCERS_DEV && (typeof n !== "number")) {
throw new Error("take must be given an integer");
} else {
return function(xf)
/*@ <anonymous> <M> (MTransformer<IN, INTER, OUT>) => {Take<M, IN, INTER, OUT> | 0 < 1} */
{ return new Take(nn, xf) };
}
}
class TakeWhile<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
public pred: (z:IN) => boolean;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (pred:(z:IN) => boolean, xf:MTransformer<IN, INTER, OUT>) : {TakeWhile<M, IN, INTER, OUT> | 0 < 1} */
constructor(pred: (z:IN) => boolean, xf: MTransformer<IN, INTER, OUT>) {
this.pred = pred;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
if(this.pred(input)) {
return this.xf.step(result, input);
} else {
return new QQ(result, 1);
}
}
}
/**
* Like the take transducer except takes as long as the pred
* return true for inputs.
* @method transducers.takeWhile
* @param {Function} pred a predicate function
* @return {transducers.TakeWhile} a takeWhile transducer
* @example
* let t = transducers;
* let xf = t.takeWhile(function(n) { return n < 3; });
* t.into([], xf, [0,1,2,3,4,5]); // [0,1,2];
*/
/*@ takeWhile :: <IN, INTER, OUT, M> (pred: (IN)=>boolean) => (xf: MTransformer<IN, INTER, OUT>) => {TakeWhile<M, IN, INTER, OUT> | 0 < 1} */
function takeWhile<M extends ReadOnly, IN, INTER, OUT>(pred: (IN)=>boolean): (xf: MTransformer<IN, INTER, OUT>) => TakeWhile<M, IN, INTER, OUT> {
/*@ readonly */
let ff = pred;
if(TRANSDUCERS_DEV && (typeof pred !== "function")) {
throw new Error("takeWhile must given a function");
} else {
return function(xf)
/*@ <anonymous> <M> (MTransformer<IN, INTER, OUT>) => {TakeWhile<M, IN, INTER, OUT> | 0 < 1} */
{ return new TakeWhile(ff, xf) };
}
}
class TakeNth<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
/*@ i : number */
public i: number;
public n: number;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (n:number, xf:MTransformer<IN, INTER, OUT>) : {TakeNth<M, IN, INTER, OUT> | 0 < 1} */
constructor(n:number, xf:MTransformer<IN, INTER, OUT>) {
this.i = -1;
this.n = n;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ @Mutable step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
this.i++;
if (true) {//PORT TODO ((this.i % this.n) === 0) {
return this.xf.step(result, input);
} else {
return new QQ(result, 0);
}
}
}
/**
* A transducer that takes every Nth input
* @method transducers.takeNth
* @param {Number} n an integer
* @return {transducers.TakeNth} a takeNth transducer
* @example
* let t = transducers;
* let xf = t.takeNth(3);
* t.into([], xf, [0,1,2,3,4,5]); // [2,5];
*/
/*@ takeNth :: <IN, INTER, OUT, M> (n:number) => (xf: MTransformer<IN, INTER, OUT>) => {TakeNth<Unique, IN, INTER, OUT> | 0 < 1} */
function takeNth<IN, INTER, OUT>(n:number): (xf: MTransformer<IN, INTER, OUT>) => TakeNth<Unique, IN, INTER, OUT> {
/*@ readonly */
let nn = n;
if(TRANSDUCERS_DEV && (typeof n !== "number")) {
throw new Error("takeNth must be given a number");
} else {
return function(xf)
/*@ <anonymous> <M> (MTransformer<IN, INTER, OUT>) => {TakeNth<M, IN, INTER, OUT> | 0 < 1} */
{ return new TakeNth(nn, xf) };
}
}
// no maps in JS, perhaps define only if transit or
// Map available? - David
class Drop<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
/*@ n : number */
public n: number;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (n:number, xf:MTransformer<IN, INTER, OUT>) : {Drop<M, IN, INTER, OUT> | 0 < 1} */
constructor(n:number, xf:MTransformer<IN, INTER, OUT>) {
this.n = n;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ @Mutable step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
if(this.n > 0) {
this.n--;
return new QQ(result, 0);
} else {
return this.xf.step(result, input);
}
}
}
/**
* A dropping transducer constructor
* @method transducers.drop
* @param {Number} n an integer, the number of inputs to drop.
* @return {transducers.Drop} a dropping transducer
* @example
* let t = transducers;
* let xf = t.drop(3);
* t.into([], xf, [0,1,2,3,4,5]); // [3,4,5];
*/
/*@ drop :: <IN, INTER, OUT> (n:number) => (xf: MTransformer<IN, INTER, OUT>) => {Drop<Unique, IN, INTER, OUT> | 0 < 1} */
function drop<IN, INTER, OUT>(n:number): (xf: MTransformer<IN, INTER, OUT>) => Drop<Unique, IN, INTER, OUT> {
/*@ readonly */
let nn = n;
if(TRANSDUCERS_DEV && (typeof n !== "number")) {
throw new Error("drop must be given an integer");
} else {
return function(xf)
/*@ <anonymous> (MTransformer<IN, INTER, OUT>) => {Drop<Unique, IN, INTER, OUT> | 0 < 1} */
{ return new Drop(nn, xf) };
}
}
class DropWhile<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
/*@ drop : boolean */
public drop: boolean;
public pred: (z:IN) => boolean;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (pred:(z:IN) => boolean, xf:MTransformer<IN, INTER, OUT>) : {DropWhile<M, IN, INTER, OUT> | 0 < 1} */
constructor(pred: (z:IN) => boolean, xf: MTransformer<IN, INTER, OUT>) {
this.drop = true;
this.pred = pred;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ @Mutable step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
if(this.drop && this.pred(input)) {
return new QQ(result, 0);
} else {
if(this.drop) this.drop = false;
return this.xf.step(result, input);
}
}
}
/**
* A dropping transducer that drop inputs as long as
* pred is true.
* @method transducers.dropWhile
* @param {Function} pred a predicate function
* @return {transducers.DropWhile} a dropWhile transducer
* @example
* let t = transducers;
* let xf = t.dropWhile(function(n) { return n < 3; });
* t.into([], xf, [0,1,2,3,4,5]); // [3,4,5];
*/
/*@ dropWhile :: <IN, INTER, OUT, M> (pred: (IN)=>boolean) => (xf: MTransformer<IN, INTER, OUT>) => {DropWhile<Unique, IN, INTER, OUT> | 0 < 1} */
function dropWhile<IN, INTER, OUT>(pred: (IN)=>boolean): (xf: MTransformer<IN, INTER, OUT>) => DropWhile<Unique, IN, INTER, OUT> {
/*@ readonly */
let ff = pred;
if(TRANSDUCERS_DEV && (typeof pred !== "function")) {
throw new Error("dropWhile must be given a function");
} else {
return function(xf)
/*@ <anonymous> (MTransformer<IN, INTER, OUT>) => {DropWhile<Unique, IN, INTER, OUT> | 0 < 1} */
{ return new DropWhile(ff, xf) };
}
}
/*@ readonly */
let NONE = {};
class PartitionBy<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
public f: (z:IN) => any;
/*@ xf : MTransformer<MArray<IN>, INTER, OUT> */
public xf: MTransformer<MArray<IN>, INTER, OUT>;
/*@ a : MArray<IN> */
public a: MArray<IN>;
/*@ pval : top */
public pval: any;
/*@ new (f:(IN) => top, xf:MTransformer<MArray<IN>, INTER, OUT>) : {PartitionBy<M, IN, INTER, OUT> | 0 < 1} */
constructor(f: (z:IN) => any, xf: MTransformer<MArray<IN>, INTER, OUT>) {
this.f = f;
this.xf = xf;
this.a = [];
this.pval = NONE;
}
init():INTER {
return this.xf.init();
}
/*@ @Mutable result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
if(this.a.length > 0) {
result = this.xf.step(result.value, this.a);
result.__transducers_reduced__ = 0;
this.a = [];
}
return this.xf.result(result);
}
/*@ @Mutable step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
let pval = this.pval;
let val = this.f(input);
this.pval = val;
// NOTE: we should probably allow someone to define
// equality? - David
if((pval === NONE) ||
(pval === val)) {
this.a.push(input);
return new QQ(result, 0);
} else {
let ret = this.xf.step(result, this.a);
this.a = [];
if(!isReduced(ret)) {
this.a.push(input);
}
return ret;
}
}
}
/**
* A partitioning transducer. Collects inputs into
* arrays as long as predicate remains true for contiguous
* inputs.
* @method transducers.partitionBy
* @param {Function} f a partition function. When the result
* for an input changes from the previous result will create
* a partition.
* @return {transducers.PartitionBy} a partitionBy transducer
* @example
* let t = transducers;
* let xf = t.partitionBy(function(x) { return typeof x == "string"; });
* t.into([], xf, [0,1,"foo","bar",2,3,"bar","baz"]); // [[0,1],["foo","bar"],[2,3],["bar","baz"]];
*/
/*@ partitionBy :: <IN, INTER, OUT, M> (f: (IN)=>top) => (xf: MTransformer<MArray<IN>, INTER, OUT>) => {PartitionBy<Unique, IN, INTER, OUT> | 0 < 1} */
function partitionBy<IN, INTER, OUT>(f: (IN)=>any): (xf: MTransformer<MArray<IN>, INTER, OUT>) => PartitionBy<Unique, IN, INTER, OUT> {
/*@ readonly */
let ff = f;
if(TRANSDUCERS_DEV && (typeof f !== "function")) {
throw new Error("partitionBy must be given an function");
} else {
return function(xf)
/*@ <anonymous> (MTransformer<MArray<IN>, INTER, OUT>) => {PartitionBy<Unique, IN, INTER, OUT> | 0 < 1} */
{ return new PartitionBy(ff, xf) };
}
}
class PartitionAll<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
public n: number;
/*@ xf : MTransformer<MArray<IN>, INTER, OUT> */
public xf: MTransformer<MArray<IN>, INTER, OUT>;
/*@ a : MArray<IN> */
public a: MArray<IN>;
/*@ new (n:number, xf:MTransformer<MArray<IN>, INTER, OUT>) : {PartitionAll<M, IN, INTER, OUT> | 0 < 1} */
constructor(n:number, xf:MTransformer<MArray<IN>, INTER, OUT>) {
this.n = n;
this.xf = xf;
this.a = [];
}
init():INTER {
return this.xf.init();
}
/*@ @Mutable result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
if(this.a.length > 0) {
result = this.xf.step(result.value, this.a);
result.__transducers_reduced__ = 0;
this.a = [];
}
return this.xf.result(result);
}
/*@ @Mutable step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
this.a.push(input);
if(this.n === this.a.length) {
let a = this.a;
this.a = [];
return this.xf.step(result, a);
} else {
return new QQ(result, 0);
}
}
}
/**
* A partitioning transducer. Collects inputs into
* arrays of size N.
* @method transducers.partitionAll
* @param {Number} n an integer
* @return {transducers.PartitionAll} a partitionAll transducer
* @example
* let t = transducers;
* let xf = t.partitionAll(3);
* t.into([], xf, [0,1,2,3,4,5]); // [[0,1,2],[3,4,5]]
*/
/*@ partitionAll :: <IN, INTER, OUT, M> (n:number) => (xf: MTransformer<MArray<IN>, INTER, OUT>) => {PartitionAll<Unique, IN, INTER, OUT> | 0 < 1} */
function partitionAll<IN, INTER, OUT>(n:number): (xf: MTransformer<MArray<IN>, INTER, OUT>) => PartitionAll<Unique, IN, INTER, OUT> {
/*@ readonly */
let nn = n;
if(TRANSDUCERS_DEV && (typeof n !== "number")) {
throw new Error("partitionAll must be given a number");
} else {
return function(xf)
/*@ <anonymous> (MTransformer<MArray<IN>, INTER, OUT>) => {PartitionAll<Unique, IN, INTER, OUT> | 0 < 1} */
{ return new PartitionAll(nn, xf) };
}
}
class Keep<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
public f: (z:IN) => any;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (f:(IN) => top, xf:MTransformer<IN, INTER, OUT>) : {Keep<M, IN, INTER, OUT> | 0 < 1} */
constructor(f: (z:IN) => any, xf: MTransformer<IN, INTER, OUT>) {
this.f = f;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
let v = this.f(input);
if(v === null) {
return new QQ(result, 0);
} else {
return this.xf.step(result, input);
}
}
}
/**
* A keeping transducer. Keep inputs as long as the provided
* function does not return null or undefined.
* @method transducers.keep
* @param {Function} f a function
* @return {transducers.Keep} a keep transducer
* @example
* let t = transducers;
* let xf = t.keep(function(x) { if(typeof x == "string") return "cool"; });
* t.into([], xf, [0,1,"foo",3,4,"bar"]); // ["foo","bar"]
*/
/*@ keep :: <IN, INTER, OUT, M> (f: (IN)=>top) => (xf: MTransformer<IN, INTER, OUT>) => {Keep<Unique, IN, INTER, OUT> | 0 < 1} */
function keep<IN, INTER, OUT>(f: (IN)=>any): (xf: MTransformer<IN, INTER, OUT>) => Keep<Unique, IN, INTER, OUT> {
/*@ readonly */
let ff = f;
if(TRANSDUCERS_DEV && (typeof f !== "function")) {
throw new Error("keep must be given a function");
} else {
return function(xf)
/*@ <anonymous> (MTransformer<IN, INTER, OUT>) => {Keep<Unique, IN, INTER, OUT> | 0 < 1} */
{ return new Keep(ff, xf) };
}
}
class KeepIndexed<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
/*@ i : number */
public i: number;
public f: (idx:number, z:IN) => any;
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ new (f:(idx:number, z:IN) => top, xf:MTransformer<IN, INTER, OUT>) : {KeepIndexed<M, IN, INTER, OUT> | 0 < 1} */
constructor(f: (idx:number, z:IN) => any, xf: MTransformer<IN, INTER, OUT>) {
this.i = -1;
this.f = f;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ @Mutable step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
this.i++;
let v:any = this.f(this.i, input);
if(v === null) {
return new QQ(result, 0);
} else {
return this.xf.step(result, input);
}
}
}
/**
* Like keep but the provided function will be passed the
* index as the first argument.
* @method transducers.keepIndexed
* @param {Function} f a function
* @return {transducers.KeepIndexed} a keepIndexed transducer
* @example
* let t = transducers;
* let xf = t.keepIndexed(function(i, x) { if(typeof x == "string") return "cool"; });
* t.into([], xf, [0,1,"foo",3,4,"bar"]); // ["foo","bar"]
*/
/*@ keepIndexed :: <IN, INTER, OUT, M> (f: (idx:number, z:IN)=>top) => (xf: MTransformer<IN, INTER, OUT>) => {KeepIndexed<Unique, IN, INTER, OUT> | 0 < 1} */
function keepIndexed<IN, INTER, OUT>(f: (idx:number, z:IN)=>any): (xf: MTransformer<IN, INTER, OUT>) => KeepIndexed<Unique, IN, INTER, OUT> {
/*@ readonly */
let ff = f;
if(TRANSDUCERS_DEV && (typeof f !== "function")) {
throw new Error("keepIndexed must be given a function");
} else {
return function(xf)
/*@ <anonymous> (MTransformer<IN, INTER, OUT>) => {KeepIndexed<Unique, IN, INTER, OUT> | 0 < 1} */
{ return new KeepIndexed(ff, xf) };
}
}
// randomSample
// iteration
/**
* Given a transformer returns a transformer which preserves
* reduced by wrapping one more time. See cat.
* @method transducers.preservingReduced
* @param {transformer} xf a transformer
* @return {transformer} a transformer which preserves reduced
*/
/*@ preservingReduced :: <IN, INTER, OUT> (xf: MTransformer<IN, INTER, OUT>) => {MTransformer<IN, INTER, MQQ<INTER>> | 0 < 1} */
function preservingReduced<IN, INTER, OUT>(xf: MTransformer<IN, INTER, OUT>) {
return new PreservingReduced(xf);
}
class PreservingReduced<M extends ReadOnly, IN, INTER> implements Transformer<M, IN, INTER, MQQ<INTER>> {
/*@ xf : TruncatedTransformer<Mutable, IN, INTER> */
public xf: TruncatedTransformer<Mutable, IN, INTER>;
/*@ new (xf:TruncatedTransformer<Mutable, IN, INTER>) : {PreservingReduced<M, IN, INTER> | 0 < 1} */
constructor(xf: TruncatedTransformer<Mutable, IN, INTER>) {
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {MQQ<INTER> | 0 < 1} */
result(result:MQQ<INTER>):MQQ<INTER> {
return result;
}
/*@ step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IN):MQQ<INTER> {
let ret = this.xf.step(result, input);
if(isReduced(ret)) ret.__transducers_reduced__++;
return ret;
}
}
/**
* Given a transformer return a concatenating transformer
* @method transducers.cat
* @param {transformer} xf a transformer
* @return {transformer} a concatenating transformer
*/
/*@ cat :: <IN, INTER, OUT> (xf: MTransformer<IN, INTER, OUT>) => {MTransformer<IArray<IN>, INTER, OUT> | 0 < 1} */
function cat<IN, INTER, OUT>(xf: MTransformer<IN, INTER, OUT>) {
return new Cat(xf);
}
class Cat<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IArray<IN>, INTER, OUT> {
/*@ xf : MTransformer<IN, INTER, OUT> */
public xf: MTransformer<IN, INTER, OUT>;
/*@ rxf : MTransformer<IN, INTER, MQQ<INTER>> */
public rxf: MTransformer<IN, INTER, MQQ<INTER>>;
/*@ new (xf:MTransformer<IN, INTER, OUT>) : {Cat<M, IN, INTER, OUT> | 0 < 1} */
constructor(xf: MTransformer<IN, INTER, OUT>) {
this.xf = xf;
this.rxf = preservingReduced(xf);
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.xf.result(result);
}
/*@ step (result:INTER, input:IArray<IN>) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, input:IArray<IN>):MQQ<INTER> {
return reduce(this.rxf, result, input);
}
}
/**
* A mapping concatenating transformer
* @method transducers.mapcat
* @param {Function} f the mapping function
* @return {Transducer} a mapping concatenating transducer
* @example
* let t = transducers;
* let reverse = function(arr) { let arr = Array.prototype.slice.call(arr, 0); arr.reverse(); return arr; }
* let xf = t.mapcat(reverse);
* t.into([], xf, [[3,2,1],[6,5,4]]); // [1,2,3,4,5,6]
*/
/*@ mapcat :: <IN, INTER, OUT, S, M> (f: (z:S)=>IArray<IN>) => (xf: MTransformer<IN, INTER, OUT>) => {Map<M, S, INTER, OUT, IArray<IN>> | 0 < 1} */
function mapcat<IN, INTER, OUT, S>(f: (z:S)=>IN[]) {
/*@ readonly */
let ff = f;
return function(xf: MTransformer<IN, INTER, OUT>)
/*@ <anonymous> <M> (xf: MTransformer<IN, INTER, OUT>) => {Map<M, S, INTER, OUT, IArray<IN>> | 0 < 1} */
{
return map(ff)(cat(xf))
}
}
function slen(x:string):number { return _pos(); }
/*@ stringReduce :: <INTER, OUT> (xf:MTransformer<string, INTER, OUT>, init:INTER, str:string) => {OUT | 0 < 1} */
function stringReduce<INTER, OUT>(xf:MTransformer<string, INTER, OUT>, init:INTER, str:string) {
let acc = init;
/*@ wrappedAcc :: MQQ<INTER> */
let wrappedAcc = new QQ(acc, 0);
let shouldBreak = false;
for(let i = 0; i < slen(str); i++) { //PORT TODO: was str.length
wrappedAcc = xf.step(acc, str.charAt(i));
if (isReduced(wrappedAcc)) {
wrappedAcc.__transducers_reduced__--;
shouldBreak = true;
} else {
acc = wrappedAcc.value;
}
}
return xf.result(wrappedAcc);
}
/*@ arrayReduce :: <IN, INTER, OUT> (xf:MTransformer<IN, INTER, OUT>, init:INTER, array:IArray<IN>) => {OUT | 0 < 1} */
function arrayReduce<IN, INTER, OUT>(xf:MTransformer<IN, INTER, OUT>, init:INTER, array:IN[]) {
let acc = init;
/*@ wrappedAcc :: MQQ<INTER> */
let wrappedAcc = new QQ(acc, 0);
let shouldBreak = false;
for(let i = 0; i < array.length && !shouldBreak; i++) {
wrappedAcc = xf.step(acc, array[i]);
if (isReduced(wrappedAcc)) {
wrappedAcc.__transducers_reduced__--;
shouldBreak = true;
} else {
acc = wrappedAcc.value;
}
}
return xf.result(wrappedAcc);
}
/*@ objectReduce :: <M, INTER, OUT> (xf:MTransformer<Entry<M>, INTER, OUT>, init:INTER, ob:EmptyObject<Immutable>) => {OUT | 0 < 1} */
function objectReduce<INTER, OUT>(xf:MTransformer<{}, INTER, OUT>, init:INTER, ob:{[key:string]:any}) {
let acc = init;
/*@ wrappedAcc :: MQQ<INTER> */
let wrappedAcc = new QQ(acc, 0);
let shouldBreak = false;
for(let p in ob) {
if(!shouldBreak && ob.hasOwnProperty(p)) {
wrappedAcc = xf.step(acc, {x:p, y:ob[p]}); //ORIG: [p, obj[p]]);
if (isReduced(wrappedAcc)) {
wrappedAcc.__transducers_reduced__--;
shouldBreak = true;
} else {
acc = wrappedAcc.value;
}
}
}
return xf.result(wrappedAcc);
}
/*@ iterableReduce :: <INTER, OUT> (xf:MTransformer<top, INTER, OUT>, init:INTER, iter:ObjIter) => {OUT | 0 < 1} */
function iterableReduce(xf, init, iter) {
let xiter;
if("ATATiterator" in iter) {
xiter = (<Iterable<ReadOnly>>iter).ATATiterator();
} else {
xiter = <Iterator<ReadOnly>>iter;
}
let acc = init;
/*@ wrappedAcc :: MQQ<INTER> */
let wrappedAcc = new QQ(acc, 0);
let shouldBreak = false;
let step = xiter.next();
while(!shouldBreak) {
wrappedAcc = xf.step(acc, step.value);
if(isReduced(wrappedAcc)) {
wrappedAcc.__transducers_reduced__--;
shouldBreak = true;
} else {
step = xiter.next();
shouldBreak = step.done;
acc = wrappedAcc.value;
}
}
return xf.result(wrappedAcc);
}
/**
* Given a transducer, an intial value and a
* collection - returns the reduction.
* @method transducers.reduce
* @param {Transducer|Function} xf a transducer or two-arity function
* @param {Object} init any JavaScript value
* @param {String|Array|Object|Iterable} coll any iterable JavaScript value
* @return {Object} a iterable JavaScript value: string, array
* iterable, or object.
*/
// TODO: removed the if(coll) check but it wasn't sound anyway - e.g. it would reject coll==""
/*@ reduce :: <IN, INTER, OUT > (xf: MTransformer<IN, INTER, OUT>, init:INTER, coll:IArray<IN>) => {OUT | 0 < 1} */
/*@ reduce :: < INTER, OUT > (xf: MTransformer<string, INTER, OUT>, init:INTER, coll:string) => {OUT | 0 < 1} */
/*@ reduce :: < INTER, OUT, M> (xf: MTransformer<Entry<M>, INTER, OUT>, init:INTER, coll:ObjNoIter) => {OUT | 0 < 1} */
/*@ reduce :: < INTER, OUT > (xf: MTransformer<top, INTER, OUT>, init:INTER, coll:ObjIter) => {OUT | 0 < 1} */
/*@ reduce :: <IN, OUT > (stepFn: (result:OUT, input:IN)=>OUT, init:OUT, coll:IArray<IN>) => {OUT | 0 < 1} */
/*@ reduce :: < OUT > (stepFn: (result:OUT, input:string)=>OUT, init:OUT, coll:string) => {OUT | 0 < 1} */
/*@ reduce :: < OUT, M> (stepFn: (result:OUT, input:Entry<M>)=>OUT, init:OUT, coll:ObjNoIter) => {OUT | 0 < 1} */
/*@ reduce :: < OUT > (stepFn: (result:OUT, input:top)=>OUT, init:OUT, coll:ObjIter) => {OUT | 0 < 1} */
function reduce(xf:any, init:any, coll:any):any {
xf = typeof xf === "function" ? wrap(xf) : xf;
if(isString(coll)) {
return stringReduce(xf, init, coll);
} else if(isArray(coll)) {
return arrayReduce(xf, init, coll);
} else if(isIterable(coll)) {
return iterableReduce(xf, init, coll);
} else if(isObject(coll)) {
return objectReduce(xf, init, coll);
} else {
throw new Error("Cannot reduce instance of ");// + coll.constructor.name); //TODO
}
}
/**
* Given a transducer, a builder function, an initial value
* and a iterable collection - returns the reduction.
* collection - returns the reduction.
* @method transducers.transduce
* @param {Transducer} xf a transducer
* @param {Transducer|Function} f a transducer or two-arity function
* @param {Object} init any JavaScript value
* @param {String|Array|Object|Iterable} coll any iterable JavaScript value
* @return {Object} a JavaScript value.
* @example
* let t = transducers;
* let inc = function(n) { return n+1; };
* let isEven = function(n) { return n % 2 == 0; };
* let apush = function(arr,x) { arr.push(x); return arr; };
* let xf = t.comp(t.map(inc),t.filter(isEven));
* t.transduce(xf, apush, [], [1,2,3,4]); // [2,4]
*/
/*@ transduce :: <A,B,C,X,Y,Z > (xf: MTransducer<A, B, C, X, Y, Z>, f: MTransformer<A, B, C>, init:Y, coll:IArray<X>) => {Z | 0 < 1} */
/*@ transduce :: <A,B,C, Y,Z > (xf: MTransducer<A, B, C, string, Y, Z>, f: MTransformer<A, B, C>, init:Y, coll:string) => {Z | 0 < 1} */
/*@ transduce :: <A,B,C, Y,Z,M> (xf: MTransducer<A, B, C, Entry<M>, Y, Z>, f: MTransformer<A, B, C>, init:Y, coll:ObjNoIter) => {Z | 0 < 1} */
/*@ transduce :: <A,B,C, Y,Z > (xf: MTransducer<A, B, C, top, Y, Z>, f: MTransformer<A, B, C>, init:Y, coll:ObjIter) => {Z | 0 < 1} */
/*@ transduce :: <A, C,X,Y,Z > (xf: MTransducer<A, C, C, X, Y, Z>, f: (result:C, input:A)=>C, init:Y, coll:IArray<X>) => {Z | 0 < 1} */
/*@ transduce :: <A, C, Y,Z > (xf: MTransducer<A, C, C, string, Y, Z>, f: (result:C, input:A)=>C, init:Y, coll:string) => {Z | 0 < 1} */
/*@ transduce :: <A, C, Y,Z,M> (xf: MTransducer<A, C, C, Entry<M>, Y, Z>, f: (result:C, input:A)=>C, init:Y, coll:ObjNoIter) => {Z | 0 < 1} */
/*@ transduce :: <A, C, Y,Z > (xf: MTransducer<A, C, C, top, Y, Z>, f: (result:C, input:A)=>C, init:Y, coll:ObjIter) => {Z | 0 < 1} */
function transduce(xf:any, f:any, init:any, coll:any) {
f = typeof f === "function" ? wrap(f) : f;
xf = xf(f);
return reduce(xf, init, coll);
}
// TODO: should be (string, string + number + boolean) => string
/*@ stringAppend :: (string, string) => {string | 0 < 1} */
function stringAppend(s, x) {
return s + x;
}
/*@ arrayPush :: <T> (arr:MArray<T>, x:T) => {MArray<T> | 0 < 1} */
function arrayPush<T>(arr:T[], x:T) {
arr.push(x);
return arr;
}
/*@ addEntry :: <M extends ReadOnly, T> (ob: MMap<T>, entry: Pair<M,string,T>) => { MMap<T> | 0 < 1 } */
function addEntry(ob, entry) {
ob[entry.x] = entry.y; //ORIG: ob[entry[0]] = entry[1];
return ob;
}
/**
* Reduce a value into the given empty value using a transducer.
* @method transducers.into
* @param {String|Array|Object} empty a JavaScript collection
* @param {Transducer} xf a transducer
* @param {Iterable} coll any iterable JavaScript value: array, string,
* object, or iterable.
* @return {Object} a JavaScript value.
* @example
* let t = transducers;
* let inc = function(n) { return n+1; };
* let isEven = function(n) { return n % 2 == 0; };
* let apush = function(arr,x) { arr.push(x); return arr; };
* let xf = t.comp(t.map(inc),t.filter(isEven));
* t.into([], xf, [1,2,3,4]); // [2,4]
*/
//TODO: when empty is a string, xf should actually be (MTransformer<string + number + boolean, string, string>) =>...
/*@ into :: < Z > (empty: string, xf: MTransducer<string, string, string, string, string, Z>, coll: string) => {Z | 0 < 1} */
/*@ into :: < X,Z > (empty: string, xf: MTransducer<string, string, string, X, string, Z>, coll: IArray<X>) => {Z | 0 < 1} */
/*@ into :: < Z, M> (empty: string, xf: MTransducer<string, string, string, Entry<M>, string, Z>, coll: ObjNoIter) => {Z | 0 < 1} */
/*@ into :: < Z > (empty: string, xf: MTransducer<string, string, string, top, string, Z>, coll: ObjIter) => {Z | 0 < 1} */
/*@ into :: <T, Z > (empty: MArray<T>, xf: MTransducer<T, MArray<T>, MArray<T>, string, MArray<T>, Z>, coll: string) => {Z | 0 < 1} */
/*@ into :: <T,X,Z > (empty: MArray<T>, xf: MTransducer<T, MArray<T>, MArray<T>, X, MArray<T>, Z>, coll: IArray<X>) => {Z | 0 < 1} */
/*@ into :: <T, Z, M> (empty: MArray<T>, xf: MTransducer<T, MArray<T>, MArray<T>, Entry<M>, MArray<T>, Z>, coll: ObjNoIter) => {Z | 0 < 1} */
/*@ into :: <T, Z > (empty: MArray<T>, xf: MTransducer<T, MArray<T>, MArray<T>, top, MArray<T>, Z>, coll: ObjIter) => {Z | 0 < 1} */
/*@ into :: <T, Z,N > (empty: MMap<T>, xf: MTransducer<Pair<N,string,T>, MMap<T>, MMap<T>, string, MMap<T>, Z>, coll: string) => {Z | 0 < 1} */
/*@ into :: <T,X,Z,N > (empty: MMap<T>, xf: MTransducer<Pair<N,string,T>, MMap<T>, MMap<T>, X, MMap<T>, Z>, coll: IArray<X>) => {Z | 0 < 1} */
/*@ into :: <T, Z,N,M> (empty: MMap<T>, xf: MTransducer<Pair<N,string,T>, MMap<T>, MMap<T>, Entry<M>, MMap<T>, Z>, coll: ObjNoIter) => {Z | 0 < 1} */
/*@ into :: <T, Z,N > (empty: MMap<T>, xf: MTransducer<Pair<N,string,T>, MMap<T>, MMap<T>, top, MMap<T>, Z>, coll: ObjIter) => {Z | 0 < 1} */
function into(empty, xf, coll) {
if(isString(empty)) {
return transduce(xf, stringAppend, empty, coll);
} else if(isArray(empty)) {
return transduce(xf, arrayPush, empty, coll);
} else if(isObject(empty)) {
return transduce(xf, addEntry, empty, coll);
}
else throw new Error("illegal 'empty' arg to into()");
}
class Completing<M extends ReadOnly, IN, INTER, OUT> implements Transformer<M, IN, INTER, OUT> {
/*@ cf : (z:MQQ<INTER>) => OUT */
public cf: (z:MQQ<INTER>) => OUT;
/*@ xf : TruncatedTransformer<Mutable, IN, INTER> */
public xf: TruncatedTransformer<Mutable, IN, INTER>;
/*@ new (cf:(z:MQQ<INTER>) => OUT, xf:TruncatedTransformer<Mutable, IN, INTER>) : {Completing<M, IN, INTER, OUT> | 0 < 1} */
constructor(cf: (z:MQQ<INTER>) => OUT, xf: TruncatedTransformer<Mutable, IN, INTER>) {
this.cf = cf;
this.xf = xf;
}
init():INTER {
return this.xf.init();
}
/*@ result (result:MQQ<INTER>) : {OUT | 0 < 1} */
result(result:MQQ<INTER>):OUT {
return this.cf(result);
}
/*@ step (result:INTER, input:IN) : {MQQ<INTER> | 0 < 1} */
step(result:INTER, step:IN):MQQ<INTER> {
return this.xf.step(result, step);
}
}
/**
* A completing transducer constructor. Useful to provide cleanup
* logic at the end of a reduction/transduction.
* @method transducers.completing
* @param {Transducer} xf a transducer
* @param {Function} cf a function to apply at the end of the reduction/transduction
* @return {Transducer} a transducer
*/
// TODO: the MTransformers in this signature could be TruncatedTransformers instead...
/*@ completing :: <IN, INTER, OUT, M, T> (xf: MTransformer<IN, INTER, T>, cf: (MQQ<INTER>) => OUT) => {Completing<M, IN, INTER, OUT > | 0 < 1} */
/*@ completing :: <IN, INTER, OUT, M> (xf: (result:INTER, input:IN)=>INTER, cf: (MQQ<INTER>) => OUT) => {Completing<M, IN, INTER, OUT > | 0 < 1} */
/*@ completing :: <IN, INTER, OUT, M, T> (xf: MTransformer<IN, INTER, T>) => {Completing<M, IN, INTER, MQQ<INTER>> | 0 < 1} */
/*@ completing :: <IN, INTER, OUT, M> (xf: (result:INTER, input:IN)=>INTER) => {Completing<M, IN, INTER, MQQ<INTER>> | 0 < 1} */
function completing<IN, INTER, OUT>(xf: any, cf?: (z:MQQ<INTER>) => OUT):any {
let wxf:TruncatedTransformer<Mutable, IN, INTER> = typeof xf === "function" ? wrap(xf) : xf;
if(TRANSDUCERS_DEV && (wxf !== null) && !isObject(wxf)) {
throw new Error("completing must be given a transducer as first argument");
} else {
if (cf) return new Completing(cf, wxf);
return new Completing(identity, wxf);
}
}
/**
* Convert a transducer transformer object into a function so
* that it can be used with existing reduce implementation i.e. native,
* Underscore, lodash
* @method transducers.toFn
* @param {Transducer} xf a transducer
* @param {Function} builder a function which take the accumulator and the
* the next input and return a new accumulator value.
* @return {Function} a two-arity function compatible with existing reduce
* implementations
* @example
* let t = transducers;
* let arr = [0,1,2,3,4,5],
* let apush = function(arr, x) { arr.push(x); return arr; },
* let xf = t.comp(t.map(inc),t.filter(isEven));
* arr.reduce(t.toFn(xf, apush), []); // [2,4,6]
*/
/*@ toFn :: <A, B, C, X, Y, T> (xf: MTransducer<A, B, C, X, Y, T>, builder: MTransformer<A, B, C>) => (result:Y, input:X) => {MQQ<Y> | 0 < 1} */
/*@ toFn :: <A, C, X, Y, T> (xf: MTransducer<A, C, C, X, Y, T>, builder: (result:C, input:A)=>C) => (result:Y, input:X) => {MQQ<Y> | 0 < 1} */
function toFn<IN, INTER, OUT>(xf, builder) {
if(typeof builder === "function") {
return xf(wrap(builder)).step;//TODO: see below
}
let rxf = xf(builder);
return rxf.step//TODO: .bind(rxf);
}
// =============================================================================
// Utilities
// BC: helper function added for `first` below
function _f(result:any, input:any): MQQ<any>
{ return new QQ(input, 1); }
/**
* A transformer which simply returns the first input.
* @method transducers.first
* @return {Transducer} a transducer transformer
*/
let first:Wrap<Mutable, any, any> = generalWrap(_f);
// =============================================================================
// Exporting
// NOTICE: this section was removed as irrelevant to the JS->RS port
}}} // end of module com.cognitect.transducers | the_stack |
import { Ranges } from "ranges-push";
import { rApply } from "ranges-apply";
import { version as v } from "../package.json";
const version: string = v;
import { Ranges as RangesType } from "../../../scripts/common";
const BACKSLASH = `\u005C`;
interface Opts {
padStart: number;
overrideRowNum: null | number;
returnRangesOnly: boolean;
triggerKeywords: string[];
extractedLogContentsWereGiven: boolean;
}
const defaults: Opts = {
padStart: 3,
overrideRowNum: null,
returnRangesOnly: false,
triggerKeywords: ["console.log"],
extractedLogContentsWereGiven: false,
};
function fixRowNums(
str: string,
originalOpts?: Partial<Opts>
): string | RangesType {
console.log(
`030 ${`\u001b[${33}m${`originalOpts`}\u001b[${39}m`} = ${JSON.stringify(
originalOpts,
null,
4
)}`
);
if (typeof str !== "string" || !str.length) {
return str;
}
function isDigit(something: any): boolean {
return /[0-9]/.test(something);
}
function isAZ(something: any): boolean {
return /[A-Za-z]/.test(something);
}
function isObj(something: any): boolean {
return (
something && typeof something === "object" && !Array.isArray(something)
);
}
const opts: Opts = { ...defaults, ...originalOpts };
if (
!opts.padStart ||
typeof opts.padStart !== "number" ||
(typeof opts.padStart === "number" && opts.padStart < 0)
) {
opts.padStart = 0;
}
const finalIndexesToDelete = new Ranges();
let i;
const len = str.length;
let quotes: { start: number; type: string } | null = null;
let consoleStartsAt = null;
let bracketOpensAt = null;
let currentRow = 1;
let wasLetterDetected: undefined | boolean = false;
let digitStartsAt = null;
if (opts.padStart && len > 45000) {
opts.padStart = 4;
}
console.log(
`077 ${`\u001b[${33}m${`str`}\u001b[${39}m`}:\n${JSON.stringify(
str,
null,
0
)}\n${`\u001b[${35}m${`FINAL`}\u001b[${39}m`} opts: ${JSON.stringify(
opts,
null,
4
)}`
);
for (i = 0; i < len; i++) {
console.log(
`\u001b[${36}m${`--------------------------------`}\u001b[${39}m ${`\u001b[${33}m${`str[${i}]`}\u001b[${39}m`} = ${
str[i].trim() ? str[i] : JSON.stringify(str[i], null, 0)
}`
);
// count lines:
if (
opts.overrideRowNum === null &&
(str[i] === "\n" || (str[i] === "\r" && str[i + 1] !== "\n"))
) {
currentRow += 1;
console.log(
`102 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} currentRow = ${currentRow}`
);
}
// catch closing quotes console.log( ' -----> ' <------)
if (
!opts.extractedLogContentsWereGiven &&
quotes !== null &&
quotes.start < i &&
quotes.type === str[i]
) {
console.log(
`114 \u001b[${31}m${`CLOSING QUOTE DETECTED - WIPE`}\u001b[${39}m`
);
quotes = null;
consoleStartsAt = null;
bracketOpensAt = null;
digitStartsAt = null;
wasLetterDetected = false;
}
// catch opening quotes console.log( -----> ' <------ ')
if (
quotes === null &&
(opts.extractedLogContentsWereGiven ||
(consoleStartsAt &&
consoleStartsAt < i &&
bracketOpensAt &&
bracketOpensAt < i)) &&
str[i].trim()
) {
console.log("133 within opening quotes trap clauses");
if (str[i] === '"' || str[i] === "'" || str[i] === "`") {
console.log(`136 clause #1 - quotes`);
quotes = {
start: i,
type: str[i],
};
wasLetterDetected = false;
console.log(
`143 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`wasLetterDetected`}\u001b[${39}m`} = ${JSON.stringify(
wasLetterDetected,
null,
4
)}`
);
console.log(
`150 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`quotes`}\u001b[${39}m`} = ${JSON.stringify(
quotes,
null,
4
)}`
);
} else if (opts.extractedLogContentsWereGiven && digitStartsAt === null) {
if (isDigit(str[i])) {
console.log(`158 clause #2`);
digitStartsAt = i;
console.log(
`161 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`digitStartsAt`}\u001b[${39}m`} = ${digitStartsAt}`
);
} else {
console.log(`164 ${`\u001b[${31}m${`BREAK`}\u001b[${39}m`}`);
break;
}
} else if (
str[i].trim() &&
str[i] !== "/" &&
!opts.extractedLogContentsWereGiven
) {
console.log(`172 clause #3`);
// wipe
console.log(
`175 \u001b[${31}m${`A QUOTE EXPECTED HERE SO WIPE`}\u001b[${39}m`
);
consoleStartsAt = null;
bracketOpensAt = null;
digitStartsAt = null;
}
}
// catch the first digit within console.log:
if (
quotes &&
Number.isInteger(quotes.start) &&
quotes.start < i &&
!wasLetterDetected &&
digitStartsAt === null &&
isDigit(str[i])
) {
digitStartsAt = i;
console.log(
`194 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`digitStartsAt`}\u001b[${39}m`} = ${digitStartsAt}`
);
}
// catch the ending of the digits within console.log:
if (
Number.isInteger(digitStartsAt) &&
(!isDigit(str[i]) || !str[i + 1]) &&
(i > (digitStartsAt as number) || !str[i + 1])
) {
// replace the digits:
console.log(
`206 ${`\u001b[${32}m${`THING ABOUT TO BE PUSHED:`}\u001b[${39}m`}`
);
console.log(
`209 ${`\u001b[${33}m${`opts.padStart`}\u001b[${39}m`} = ${JSON.stringify(
opts.padStart,
null,
4
)}`
);
console.log(
`216 ${`\u001b[${33}m${`padStart(${currentRow} (${typeof currentRow}), ${
opts.padStart
} (${typeof opts.padStart}), "0")`}\u001b[${39}m`} = ${JSON.stringify(
String(currentRow).padStart(opts.padStart, "0"),
null,
4
)}`
);
console.log(
`225 ${`\u001b[${33}m${`currentRow`}\u001b[${39}m`} = ${JSON.stringify(
currentRow,
null,
4
)}`
);
console.log(
`232 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify(
[
digitStartsAt,
!isDigit(str[i]) ? i : i + 1,
opts.padStart
? String(
opts.overrideRowNum !== null
? opts.overrideRowNum
: currentRow
).padStart(opts.padStart, "0")
: `${
opts.overrideRowNum !== null
? opts.overrideRowNum
: currentRow
}`,
],
null,
0
)}`
);
console.log(
`253 ${`\u001b[${35}m${`███████████████████████████████████████`}\u001b[${39}m`}`
);
if (!opts.padStart) {
console.log(`256 `);
if (opts.overrideRowNum != null) {
console.log(`258 ██ case 1`);
} else {
console.log(`260 ██ case 2`);
}
}
// PS. finalIndexesToDelete is a Ranges class so we can push
// two/three arguments and it will understand it's (range) array...
finalIndexesToDelete.push(
digitStartsAt as number,
!isDigit(str[i]) ? i : i + 1,
opts.padStart
? String(
opts.overrideRowNum != null ? opts.overrideRowNum : currentRow
).padStart(opts.padStart, "0")
: `${opts.overrideRowNum != null ? opts.overrideRowNum : currentRow}`
);
console.log(
`276 NOW ${`\u001b[${33}m${`finalIndexesToDelete`}\u001b[${39}m`} = ${JSON.stringify(
finalIndexesToDelete.current(),
null,
4
)}`
);
// then, reset:
digitStartsAt = null;
console.log(
`285 ${`\u001b[${33}m${`digitStartsAt`}\u001b[${39}m`} = null`
);
// set wasLetterDetected as a decoy to prevent further digit lumps from being edited:
wasLetterDetected = true;
console.log(
`290 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`wasLetterDetected`}\u001b[${39}m`} = true`
);
}
// catch first letter within console.log:
if (
quotes &&
Number.isInteger(quotes.start) &&
quotes.start < i &&
!wasLetterDetected &&
isAZ(str[i]) &&
!(str[i] === "n" && str[i - 1] === BACKSLASH)
) {
// Skip one of more of either patterns:
// \u001b[${33}m
// ${`
// `\u001b[33m \u001b[39m`
// \u001B[4m \u001B[0m
// \u001B[4m \u001B[0m
// check for pattern \u001B[ + optional ${ + any amount of digits + optional } + m
/* istanbul ignore if */
if (
/* istanbul ignore next */
str[i - 1] === BACKSLASH &&
str[i] === "u" &&
str[i + 1] === "0" &&
str[i + 2] === "0" &&
str[i + 3] === "1" &&
(str[i + 4] === "b" || str[i + 5] === "B") &&
str[i + 5] === "["
) {
console.log(`325 \u001b[${35}m${`MATCHED`}\u001b[${39}m`);
// at this moment, we have stuck here:
//
// console.log(`\u001b[${33}m${`291 zzz`}\u001b[${39}m`)
// ^
// here, at this bracket
// now, the ANSI colour digit code might be wrapped with ${} and also,
// it can be of an indeterminate width: normally there is either one or
// two digits.
// We need to find where digits start.
// There are two possibilities: either here, or after string literal ${}
// wrapper:
// base assumption, we're here:
// console.log(`\u001b[33m 123 zzz \u001b[${39}m`)
// ^
// here
let startMarchingForwFrom;
if (isDigit(str[i + 6])) {
startMarchingForwFrom = i + 6;
console.log(
`350 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`startMarchingForwFrom`}\u001b[${39}m`} = ${startMarchingForwFrom}`
);
} else if (
str[i + 6] === "$" &&
str[i + 7] === "{" &&
isDigit(str[i + 8])
) {
startMarchingForwFrom = i + 8;
console.log(
`359 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`startMarchingForwFrom`}\u001b[${39}m`} = ${startMarchingForwFrom}`
);
}
console.log(
`364 FINAL ${`\u001b[${33}m${`startMarchingForwFrom`}\u001b[${39}m`} = ${startMarchingForwFrom}`
);
// find out where does this (possibly a sequence) of number(s) end:
let numbersSequenceEndsAt;
if (startMarchingForwFrom as number) {
console.log(
`371 \u001b[${36}m${`startMarchingForwFrom`}\u001b[${39}m was set so marching forward`
);
for (let y = startMarchingForwFrom as number; y < len; y++) {
console.log(`\u001b[${36}m${`str[${y}] = ${str[y]}`}\u001b[${39}m`);
if (!isDigit(str[y])) {
numbersSequenceEndsAt = y;
console.log(`\u001b[${36}m${`not digit, so break`}\u001b[${39}m`);
break;
}
}
console.log(`381 \u001b[${36}m${`stop marching`}\u001b[${39}m`);
}
// answer: at "numbersSequenceEndsAt".
console.log(
`386 \u001b[${32}m${`str[${numbersSequenceEndsAt}] = ${
str[numbersSequenceEndsAt as number]
}`}\u001b[${39}m`
);
// We're at the next character where digits end. That is:
// console.log(`\u001b[33m 123 zzz \u001b[${39}m`)
// ^
// here, OR
// console.log(`\u001b[${33}m 123 zzz \u001b[${39}m`)
// ^
// here
let ansiSequencesLetterMAt;
if (
numbersSequenceEndsAt !== undefined &&
str[numbersSequenceEndsAt] === "m"
) {
// if number follows "m", this is it:
ansiSequencesLetterMAt = numbersSequenceEndsAt;
} else if (
numbersSequenceEndsAt !== undefined &&
str[numbersSequenceEndsAt] === "}" &&
str[numbersSequenceEndsAt + 1] === "m"
) {
ansiSequencesLetterMAt = numbersSequenceEndsAt + 1;
}
console.log(
`418 ${`\u001b[${33}m${`ansiSequencesLetterMAt`}\u001b[${39}m`} = ${ansiSequencesLetterMAt};`
);
/* istanbul ignore else */
if (!ansiSequencesLetterMAt) {
// if ANSI closing "m" hasn't been detected yet, bail:
wasLetterDetected = true;
continue;
}
/* istanbul ignore else */
if (
str[ansiSequencesLetterMAt + 1] === "$" &&
str[ansiSequencesLetterMAt + 2] === "{" &&
str[ansiSequencesLetterMAt + 3] === "`"
) {
i = ansiSequencesLetterMAt + 3;
console.log(
`436 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`i`}\u001b[${39}m`} = ${i}`
);
continue;
}
}
wasLetterDetected = true;
console.log(
`444 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`wasLetterDetected`}\u001b[${39}m`} = true`
);
}
// catch the opening bracket of console.log ---->(<----- )
if (
!bracketOpensAt &&
str[i].trim() &&
consoleStartsAt &&
consoleStartsAt <= i
) {
if (str[i] === "(") {
bracketOpensAt = i;
console.log(
`458 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`bracketOpensAt`}\u001b[${39}m`} = ${JSON.stringify(
bracketOpensAt,
null,
4
)}`
);
} else {
// wipe
console.log(`466 \u001b[${31}m${`WIPE`}\u001b[${39}m`);
consoleStartsAt = null;
digitStartsAt = null;
}
}
// catch the trigger keywords
if (
isObj(opts) &&
opts.triggerKeywords &&
Array.isArray(opts.triggerKeywords)
) {
// check does any of the trigger keywords match
let caughtKeyword;
for (let y = 0, len2 = opts.triggerKeywords.length; y < len2; y++) {
/* istanbul ignore else */
if (str.startsWith(opts.triggerKeywords[y], i)) {
caughtKeyword = opts.triggerKeywords[y];
break;
}
}
// if any of trigger keywords starts here
/* istanbul ignore else */
if (caughtKeyword) {
consoleStartsAt = i + caughtKeyword.length;
console.log(
`494 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`consoleStartsAt`}\u001b[${39}m`} = ${consoleStartsAt}`
);
// offset the index so we don't traverse twice what was traversed already:
i = i + caughtKeyword.length - 1;
console.log(
`499 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`i`}\u001b[${39}m`} = ${i}`
);
continue;
}
}
console.log(`\u001b[${90}m${`--------------------------`}\u001b[${39}m`);
console.log(`\u001b[${90}m${`currentRow = ${currentRow}`}\u001b[${39}m`);
console.log(
`\u001b[${90}m${`digitStartsAt = ${digitStartsAt}`}\u001b[${39}m`
);
console.log(
`\u001b[${90}m${`bracketOpensAt = ${bracketOpensAt}`}\u001b[${39}m`
);
console.log(
`\u001b[${90}m${`consoleStartsAt = ${consoleStartsAt}`}\u001b[${39}m`
);
console.log(
`\u001b[${90}m${`quotes = ${JSON.stringify(quotes, null, 0)}${
quotes ? `\nwasLetterDetected = ${wasLetterDetected}` : ""
}`}\u001b[${39}m`
);
}
console.log(
`524 ${`\u001b[${33}m${`finalIndexesToDelete.current()`}\u001b[${39}m`} = ${JSON.stringify(
finalIndexesToDelete.current(),
null,
4
)}`
);
// wipe
quotes = null;
consoleStartsAt = null;
bracketOpensAt = null;
currentRow = 1;
wasLetterDetected = undefined;
digitStartsAt = null;
currentRow = 1;
if (opts.returnRangesOnly) {
console.log(`541`);
return finalIndexesToDelete.current();
}
if (finalIndexesToDelete.current()) {
console.log(`545`);
return rApply(str, finalIndexesToDelete.current());
}
console.log(`548`);
return str;
}
export { fixRowNums, defaults, version }; | the_stack |
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || {__proto__: []} instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2)
if (Object.prototype.hasOwnProperty.call(b2, p))
d2[p] = b2[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign2(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function(target, key) {
decorator(target, key, paramIndex);
};
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = {label: 0, sent: function() {
if (t[0] & 1)
throw t[1];
return t[1];
}, trys: [], ops: []}, f, y, t, g;
return g = {next: verb(0), throw: verb(1), return: verb(2)}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {value: op[1], done: false};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return {value: op[0] ? op[1] : void 0, done: true};
}
}
var __createBinding = Object.create ? function(o, m, k, k2) {
if (k2 === void 0)
k2 = k;
Object.defineProperty(o, k2, {enumerable: true, get: function() {
return m[k];
}});
} : function(o, m, k, k2) {
if (k2 === void 0)
k2 = k;
o[k2] = m[k];
};
function __exportStar(m, o) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
__createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function() {
if (o && i >= o.length)
o = void 0;
return {value: o && o[i++], done: !o};
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
} catch (error) {
e = {error};
} finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
} finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i;
function verb(n) {
if (g[n])
i[n] = function(v) {
return new Promise(function(a, b) {
q.push([n, v, a, b]) > 1 || resume(n, v);
});
};
}
function resume(n, v) {
try {
step(g[n](v));
} catch (e) {
settle(q[0][3], e);
}
}
function step(r) {
r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
}
function fulfill(value) {
resume("next", value);
}
function reject(value) {
resume("throw", value);
}
function settle(f, v) {
if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]);
}
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function(e) {
throw e;
}), verb("return"), i[Symbol.iterator] = function() {
return this;
}, i;
function verb(n, f) {
i[n] = o[n] ? function(v) {
return (p = !p) ? {value: __await(o[n](v)), done: n === "return"} : f ? f(v) : v;
} : f;
}
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i);
function verb(n) {
i[n] = o[n] && function(v) {
return new Promise(function(resolve, reject) {
v = o[n](v), settle(resolve, reject, v.done, v.value);
});
};
}
function settle(resolve, reject, d, v) {
Promise.resolve(v).then(function(v2) {
resolve({value: v2, done: d});
}, reject);
}
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", {value: raw});
} else {
cooked.raw = raw;
}
return cooked;
}
var __setModuleDefault = Object.create ? function(o, v) {
Object.defineProperty(o, "default", {enumerable: true, value: v});
} : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null) {
for (var k in mod)
if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return mod && mod.__esModule ? mod : {default: mod};
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
export {__assign, __asyncDelegator, __asyncGenerator, __asyncValues, __await, __awaiter, __classPrivateFieldGet, __classPrivateFieldSet, __createBinding, __decorate, __exportStar, __extends, __generator, __importDefault, __importStar, __makeTemplateObject, __metadata, __param, __read, __rest, __spread, __spreadArray, __spreadArrays, __values};
export default null; | the_stack |
import * as path from 'path';
import {IConfusionMatrix} from '@microsoft/bf-dispatcher';
import {MultiLabelObjectConfusionMatrixExact} from '@microsoft/bf-dispatcher';
import {MultiLabelObjectConfusionMatrixSubset} from '@microsoft/bf-dispatcher';
import {ILabelArrayAndMap} from '@microsoft/bf-dispatcher';
import {ITextUtteranceLabelMapDataStructure} from '@microsoft/bf-dispatcher';
import {Label} from '@microsoft/bf-dispatcher';
import {OrchestratorHelper} from './orchestratorhelper';
import {PredictionStructureWithPluralEvaluationLabelObject} from '@microsoft/bf-dispatcher';
import {PredictionStructureWithPluralEvaluationLabelString} from '@microsoft/bf-dispatcher';
import {StructTextLabelObjects} from '@microsoft/bf-dispatcher';
import {StructTextNumber} from '@microsoft/bf-dispatcher';
import {StructTextLabelStrings} from '@microsoft/bf-dispatcher';
import {StructTextText} from '@microsoft/bf-dispatcher';
import {UtilityLabelResolver} from './utilitylabelresolver';
import {Utility} from './utility';
export class OrchestratorAssess {
public static readonly assessmentSetIntentSummaryHtmlOutputFilename: string = 'orchestrator_assessment_set_intent_summary.html';
public static readonly assessmentSetIntentLabelsOutputFilename: string = 'orchestrator_assessment_set_intent_labels.txt';
public static readonly assessmentSetEntitySummaryHtmlOutputFilename: string = 'orchestrator_assessment_set_entity_summary.html';
public static readonly assessmentSetEntityLabelsOutputFilename: string = 'orchestrator_assessment_set_entity_labels.txt';
// eslint-disable-next-line complexity
// eslint-disable-next-line max-params
public static async runAsync(
inputPathConfiguration: string, predictionPathConfiguration: string, outputPath: string,
obfuscateEvaluationReport: boolean = false): Promise<void> {
// -----------------------------------------------------------------------
// ---- NOTE ---- process arguments --------------------------------------
if (Utility.isEmptyString(inputPathConfiguration)) {
Utility.debuggingThrow(`Please provide one or more ground-truth files, CWD=${process.cwd()}, called from OrchestratorAssess.runAsync()`);
}
if (Utility.isEmptyString(predictionPathConfiguration)) {
Utility.debuggingThrow(`Please provide ane or more prediction files, CWD=${process.cwd()}, called from OrchestratorAssess.runAsync()`);
}
if (Utility.isEmptyString(outputPath)) {
Utility.debuggingThrow(`Please provide an output directory, CWD=${process.cwd()}, called from OrchestratorAssess.runAsync()`);
}
Utility.debuggingLog(`inputPath=${inputPathConfiguration}`);
Utility.debuggingLog(`predictionPath=${predictionPathConfiguration}`);
Utility.debuggingLog(`outputPath=${outputPath}`);
Utility.toObfuscateLabelTextInReportUtility = obfuscateEvaluationReport;
UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver = obfuscateEvaluationReport;
// -----------------------------------------------------------------------
// ---- NOTE ---- load the ground truth set ------------------------------
const groundTruthFileConfiguration: string = inputPathConfiguration;
if (Utility.isEmptyString(groundTruthFileConfiguration)) {
Utility.debuggingThrow('ground-truth file configuration is empty');
}
const predictionFileConfiguration: string = predictionPathConfiguration;
if (Utility.isEmptyString(predictionFileConfiguration)) {
Utility.debuggingThrow('prediction file configuration is empty');
}
const assessmentSetIntentSummaryHtmlOutputFilename: string = path.join(outputPath, OrchestratorAssess.assessmentSetIntentSummaryHtmlOutputFilename);
const assessmentSetIntentLabelsOutputFilename: string = path.join(outputPath, OrchestratorAssess.assessmentSetIntentLabelsOutputFilename);
const assessmentSetEntitySummaryHtmlOutputFilename: string = path.join(outputPath, OrchestratorAssess.assessmentSetEntitySummaryHtmlOutputFilename);
const assessmentSetEntityLabelsOutputFilename: string = path.join(outputPath, OrchestratorAssess.assessmentSetEntityLabelsOutputFilename);
// ---- NOTE ---- process the ground-truth set and retrieve labels -------
const groundTruthFileProcessedUtteranceLabelsMap: ITextUtteranceLabelMapDataStructure =
await OrchestratorHelper.getUtteranceLabelsMap(groundTruthFileConfiguration, false);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), groundTruthFileProcessedUtteranceLabelsMap.utteranceLabelsMap.keys()=${[...groundTruthFileProcessedUtteranceLabelsMap.utteranceLabelsMap.keys()]}`);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), groundTruthFileProcessedUtteranceLabelsMap.utteranceEntityLabelsMap.keys()=${[...groundTruthFileProcessedUtteranceLabelsMap.utteranceEntityLabelsMap.keys()]}`);
const groundTruthSetUtteranceLabelsMap: Map<string, Set<string>> =
groundTruthFileProcessedUtteranceLabelsMap.utteranceLabelsMap;
const groundTruthSetUtteranceLabelDuplicateMap: Map<string, Set<string>> =
groundTruthFileProcessedUtteranceLabelsMap.utteranceLabelDuplicateMap;
const groundTruthSetUtteranceEntityLabelsMap: Map<string, Label[]> =
groundTruthFileProcessedUtteranceLabelsMap.utteranceEntityLabelsMap;
const groundTruthSetUtteranceEntityLabelDuplicateMap: Map<string, Label[]> =
groundTruthFileProcessedUtteranceLabelsMap.utteranceEntityLabelDuplicateMap;
/** ---- NOTE-FOR-REFERENCE-REFACTORED ----
* const groundTruthSetUtteranceLabelsMap: Map<string, Set<string>> = new Map<string, Set<string>>();
* const groundTruthSetUtteranceLabelDuplicateMap: Map<string, Set<string>> = new Map<string, Set<string>>();
* const groundTruthSetUtteranceEntityLabelsMap: Map<string, Label[]> = new Map<string, Label[]>();
* const groundTruthSetUtteranceEntityLabelDuplicateMap: Map<string, Label[]> = new Map<string, Label[]>();
* const groundTruthSetJsonObjectArray: any = fs.readJsonSync(groundTruthFileConfiguration);
* OrchestratorHelper.getJsonIntentsEntitiesUtterances(
* groundTruthSetJsonObjectArray,
* '',
* groundTruthSetUtteranceLabelsMap,
* groundTruthSetUtteranceLabelDuplicateMap,
* groundTruthSetUtteranceEntityLabelsMap,
* groundTruthSetUtteranceEntityLabelDuplicateMap);
* Utility.processUnknownSpuriousLabelsInUtteranceLabelsMap(
* {
* utteranceLabelsMap: groundTruthSetUtteranceLabelsMap,
* utteranceLabelDuplicateMap: groundTruthSetUtteranceLabelDuplicateMap,
* });
*/
Utility.debuggingLog('OrchestratorAssess.runAsync(), after calling OrchestratorHelper.getUtteranceLabelsMap() for groundTruth set');
// -----------------------------------------------------------------------
// ---- NOTE ---- process the ground-truth set intent labels -------------
const groundTruthSetLabels: string[] =
[...groundTruthSetUtteranceLabelsMap.values()].reduce(
(accumulant: string[], entry: Set<string>) => accumulant.concat([...entry]), []);
const groundTruthSetLabelSet: Set<string> =
new Set<string>(groundTruthSetLabels);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), groundTruthSetLabelSet=${Utility.jsonStringify(groundTruthSetLabelSet)}`);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), groundTruthSetUtteranceLabelsMap=${Utility.jsonStringify(groundTruthSetUtteranceLabelsMap)}`);
// ---- Utility.debuggingLog(`OrchestratorAssess.runAsync(), Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(groundTruthSetUtteranceLabelDuplicateMap)=${Utility.jsonStringify(Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(groundTruthSetUtteranceLabelDuplicateMap))}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of ground-truth set unique utterances=${groundTruthSetUtteranceLabelsMap.size}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of ground-truth set duplicate utterance/label pairs=${groundTruthSetUtteranceLabelDuplicateMap.size}`);
// ---- NOTE ---- process the ground-truth set entity labels -------------
const groundTruthSetEntityLabels: string[] =
[...groundTruthSetUtteranceEntityLabelsMap.values()].reduce(
(accumulant: string[], entry: Label[]) => accumulant.concat(entry.map((x: Label) => x.name)), []);
const groundTruthSetEntityLabelSet: Set<string> =
new Set<string>(groundTruthSetEntityLabels);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), groundTruthSetEntityLabelSet=${Utility.jsonStringify(groundTruthSetEntityLabelSet)}`);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), groundTruthSetUtteranceEntityLabelsMap=${Utility.jsonStringify(groundTruthSetUtteranceEntityLabelsMap)}`);
// ---- Utility.debuggingLog(`OrchestratorAssess.runAsync(), Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(groundTruthSetUtteranceEntityLabelDuplicateMap)=${Utility.jsonStringify(Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(groundTruthSetUtteranceEntityLabelDuplicateMap))}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of ground-truth entity set unique utterances=${groundTruthSetUtteranceEntityLabelsMap.size}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of ground-truth entity set duplicate utterance/label pairs=${groundTruthSetUtteranceEntityLabelDuplicateMap.size}`);
// -----------------------------------------------------------------------
// ---- NOTE ---- process the prediction set and retrieve labels ---------
const predictionFileProcessedUtteranceLabelsMap: ITextUtteranceLabelMapDataStructure =
await OrchestratorHelper.getUtteranceLabelsMap(predictionFileConfiguration, false);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), predictionFileProcessedUtteranceLabelsMap.utteranceLabelsMap.keys()=${[...predictionFileProcessedUtteranceLabelsMap.utteranceLabelsMap.keys()]}`);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), predictionFileProcessedUtteranceLabelsMap.utteranceEntityLabelsMap.keys()=${[...predictionFileProcessedUtteranceLabelsMap.utteranceEntityLabelsMap.keys()]}`);
const predictionSetUtteranceLabelsMap: Map<string, Set<string>> =
predictionFileProcessedUtteranceLabelsMap.utteranceLabelsMap;
const predictionSetUtteranceLabelDuplicateMap: Map<string, Set<string>> =
predictionFileProcessedUtteranceLabelsMap.utteranceLabelDuplicateMap;
const predictionSetUtteranceEntityLabelsMap: Map<string, Label[]> =
predictionFileProcessedUtteranceLabelsMap.utteranceEntityLabelsMap;
const predictionSetUtteranceEntityLabelDuplicateMap: Map<string, Label[]> =
predictionFileProcessedUtteranceLabelsMap.utteranceEntityLabelDuplicateMap;
/** ---- NOTE-FOR-REFERENCE-REFACTORED ----
* const predictionSetUtteranceLabelsMap: Map<string, Set<string>> = new Map<string, Set<string>>();
* const predictionSetUtteranceLabelDuplicateMap: Map<string, Set<string>> = new Map<string, Set<string>>();
* const predictionSetUtteranceEntityLabelsMap: Map<string, Label[]> = new Map<string, Label[]>();
* const predictionSetUtteranceEntityLabelDuplicateMap: Map<string, Label[]> = new Map<string, Label[]>();
* const predictionSetJsonObjectArray: any = fs.readJsonSync(predictionFileConfiguration);
* OrchestratorHelper.getJsonIntentsEntitiesUtterances(
* predictionSetJsonObjectArray,
* '',
* predictionSetUtteranceLabelsMap,
* predictionSetUtteranceLabelDuplicateMap,
* predictionSetUtteranceEntityLabelsMap,
* predictionSetUtteranceEntityLabelDuplicateMap);
*/
Utility.debuggingLog('OrchestratorAssess.runAsync(), after calling OrchestratorHelper.getUtteranceLabelsMap() for prediction set');
// -----------------------------------------------------------------------
// ---- NOTE ---- process unknown intent labels --------------------------
/** ---- NOTE-FOR-REFERENCE-NOT-USED-YET ----
* const unknownSpuriousLabelsProcessed: {
* 'utteranceUnknownLabelsMap': Map<string, Set<string>>;
* 'utteranceUnknownLabelDuplicateMap': Map<string, Set<string>>;
* 'utteranceSpuriousLabelsMap': Map<string, Set<string>>;
* 'utteranceSpuriousLabelDuplicateMap': Map<string, Set<string>>;
* 'utteranceLabelMapSetAddedWithUnknownLabel': boolean;
* 'utteranceLabelDuplicateMapSetAddedWithUnknownLabel': boolean; } =
*/
Utility.processUnknownSpuriousLabelsInUtteranceLabelsMapUsingLabelSet(
{
utteranceLabelsMap: predictionSetUtteranceLabelsMap,
utteranceLabelDuplicateMap: predictionSetUtteranceLabelDuplicateMap},
groundTruthSetLabelSet);
Utility.debuggingLog('OrchestratorAssess.runAsync(), after calling Utility.processUnknownSpuriousLabelsInUtteranceLabelsMapUsingLabelSet() for prediction intent labels');
// ---- NOTE ---- process unknown entity labels --------------------------
/** ---- NOTE-FOR-REFERENCE-NOT-USED-YET ----
* const unknownSpuriousEntityLabelsProcessed: {
* 'utteranceUnknownEntityLabelsMap': Map<string, Label[]>;
* 'utteranceUnknownEntityLabelDuplicateMap': Map<string, Label[]>;
* 'utteranceSpuriousEntityLabelsMap': Map<string, Label[]>;
* 'utteranceSpuriousEntityLabelDuplicateMap': Map<string, Label[]>;
* 'utteranceLabelMapSetAddedWithUnknownLabel': boolean;
* 'utteranceLabelDuplicateMapSetAddedWithUnknownLabel': boolean; } =
*/
Utility.processUnknownSpuriousEntityLabelsInUtteranceEntityLabelsMapUsingLabelSet(
{
utteranceEntityLabelsMap: predictionSetUtteranceEntityLabelsMap,
utteranceEntityLabelDuplicateMap: predictionSetUtteranceEntityLabelDuplicateMap},
groundTruthSetEntityLabelSet);
Utility.debuggingLog('OrchestratorAssess.runAsync(), after calling Utility.processUnknownSpuriousLabelsInUtteranceEntityLabelsMapUsingLabelSet() for prediction entity labels');
// -----------------------------------------------------------------------
// ---- NOTE ---- process the prediction set intent labels ---------------
const predictionSetLabels: string[] =
[...predictionSetUtteranceLabelsMap.values()].reduce(
(accumulant: string[], entry: Set<string>) => accumulant.concat([...entry]), []);
const predictionSetLabelSet: Set<string> =
new Set<string>(predictionSetLabels);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), predictionSetUtteranceLabelsMap=${Utility.jsonStringify(predictionSetUtteranceLabelsMap)}`);
// ---- Utility.debuggingLog(`OrchestratorAssess.runAsync(), Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(predictionSetUtteranceLabelDuplicateMap)=${Utility.jsonStringify(Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(predictionSetUtteranceLabelDuplicateMap))}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of prediction-set duplicate utterance/label pairs=${predictionSetUtteranceLabelDuplicateMap.size}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of prediction set unique utterances=${predictionSetUtteranceLabelsMap.size}`);
// if (predictionSetUtteranceLabelsMap.size <= 0) {
// Utility.debuggingThrow('There is no example, something wrong?');
// }
// ---- NOTE ---- process the prediction set entity labels ---------------
const predictionSetEntityLabels: string[] =
[...predictionSetUtteranceEntityLabelsMap.values()].reduce(
(accumulant: string[], entry: Label[]) => accumulant.concat(entry.map((x: Label) => x.name)), []);
const predictionSetEntityLabelSet: Set<string> =
new Set<string>(predictionSetEntityLabels);
// Utility.debuggingLog(`OrchestratorAssess.runAsync(), predictionSetUtteranceEntityLabelsMap=${Utility.jsonStringify(predictionSetUtteranceEntityLabelsMap)}`);
// ---- Utility.debuggingLog(`OrchestratorAssess.runAsync(), Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(predictionSetUtteranceEntityLabelDuplicateMap)=${Utility.jsonStringify(Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(predictionSetUtteranceEntityLabelDuplicateMap))}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of prediction set entity unique utterances=${predictionSetUtteranceEntityLabelsMap.size}`);
Utility.debuggingLog(`OrchestratorAssess.runAsync(), number of prediction-set entity duplicate utterance/label pairs=${predictionSetUtteranceEntityLabelDuplicateMap.size}`);
// if (predictionSetUtteranceEntityLabelsMap.size <= 0) {
// Utility.debuggingThrow('there is no entity example, something wrong?');
// }
// -----------------------------------------------------------------------
// ---- NOTE ---- integrated step to produce analysis reports ------------
Utility.debuggingLog('OrchestratorAssess.runAsync(), ready to call Utility.generateAssessmentEvaluationReport()');
const intentEvaluationOutput: {
'evaluationReportGroundTruthSetLabelUtteranceStatistics': {
'evaluationSummary': string;
'labelArrayAndMap': ILabelArrayAndMap;
'labelStatisticsAndHtmlTable': {
'labelUtterancesMap': Map<string, Set<string>>;
'labelUtterancesTotal': number;
'labelStatistics': string[][];
'labelStatisticsHtml': string;};
'utteranceStatisticsAndHtmlTable': {
'utteranceStatisticsMap': Map<number, number>;
'utteranceStatistics': StructTextNumber[];
'utteranceCount': number;
'utteranceStatisticsHtml': string;};
/** ---- NOTE-SPURIOUS-STATISTICS-AND-OUTPUT-HTML-TABLE-PLACE-HOLDER-FOR-FUTURE-NEED ----
* 'spuriousLabelStatisticsAndHtmlTable': {
* 'spuriousLabelUtterancesMap': StructTextStringSet[];
* 'spuriousLabelUtterancesTotal': number;
* 'spuriousLabelStatistics': string[][];
* 'spuriousLabelStatisticsHtml': string; };
*/
'utterancesMultiLabelArrays': StructTextText[];
'utterancesMultiLabelArraysHtml': string;
'utteranceLabelDuplicateHtml': string; };
'evaluationReportPredictionSetLabelUtteranceStatistics': {
'evaluationSummary': string;
'labelArrayAndMap': ILabelArrayAndMap;
'labelStatisticsAndHtmlTable': {
'labelUtterancesMap': Map<string, Set<string>>;
'labelUtterancesTotal': number;
'labelStatistics': string[][];
'labelStatisticsHtml': string;};
'utteranceStatisticsAndHtmlTable': {
'utteranceStatisticsMap': Map<number, number>;
'utteranceStatistics': StructTextNumber[];
'utteranceCount': number;
'utteranceStatisticsHtml': string;};
/** ---- NOTE-SPURIOUS-STATISTICS-AND-OUTPUT-HTML-TABLE-PLACE-HOLDER-FOR-FUTURE-NEED ----
* 'spuriousLabelStatisticsAndHtmlTable': {
* 'spuriousLabelUtterancesMap': StructTextStringSet[];
* 'spuriousLabelUtterancesTotal': number;
* 'spuriousLabelStatistics': string[][];
* 'spuriousLabelStatisticsHtml': string; };
*/
'utterancesMultiLabelArrays': StructTextText[];
'utterancesMultiLabelArraysHtml': string;
'utteranceLabelDuplicateHtml': string; };
'evaluationReportSpuriousPredictions': {
'evaluationSummary': string;
'spuriousPredictions': StructTextLabelStrings[]; };
'evaluationReportAnalyses': {
'evaluationSummary': string;
'misclassifiedAnalysis': {
'predictingMisclassifiedUtterancesArrays': string[][];
'predictingMisclassifiedUtterancesArraysHtml': string;
'predictingMisclassifiedUtterancesSimpleArrays': string[][];};
'confusionMatrixAnalysis': {
'confusionMatrix': IConfusionMatrix;
'multiLabelObjectConfusionMatrixExact': MultiLabelObjectConfusionMatrixExact;
'multiLabelObjectConfusionMatrixSubset': MultiLabelObjectConfusionMatrixSubset;
'predictingConfusionMatrixOutputLines': string[][];
'confusionMatrixMetricsHtml': string;
'confusionMatrixAverageMetricsHtml': string;
'confusionMatrixAverageDescriptionMetricsHtml': string;};};
'predictionStructureWithPluralEvaluationLabelStringArray': PredictionStructureWithPluralEvaluationLabelString[];
} =
Utility.generateAssessmentEvaluationReport(
groundTruthSetLabels,
predictionSetLabelSet,
groundTruthSetUtteranceLabelsMap,
groundTruthSetUtteranceLabelDuplicateMap,
predictionSetUtteranceLabelsMap,
predictionSetUtteranceLabelDuplicateMap);
if (Utility.toPrintDetailedDebuggingLogToConsole) {
Utility.debuggingLog(`intentEvaluationOutput=${Utility.jsonStringify(intentEvaluationOutput)}`);
}
Utility.debuggingLog('OrchestratorAssess.runAsync(), finished calling Utility.generateAssessmentEvaluationReport()');
// ---- NOTE ---- integrated step to produce analysis report output files.
if (Utility.toPrintDetailedDebuggingLogToConsole) {
Utility.debuggingLog(`OrchestratorAssess.runAsync(), intentEvaluationOutput.evaluationReportGroundTruthSetLabelUtteranceStatistics.evaluationSummary=\n${intentEvaluationOutput.evaluationReportGroundTruthSetLabelUtteranceStatistics.evaluationSummary}`);
}
let intentEvaluationSummary: string =
intentEvaluationOutput.evaluationReportAnalyses.evaluationSummary;
// -----------------------------------------------------------------------
intentEvaluationSummary = intentEvaluationSummary.replace(
'{APP_NAME}',
'');
intentEvaluationSummary = intentEvaluationSummary.replace(
'{MODEL_SPECIFICATION}',
'');
// -----------------------------------------------------------------------
Utility.generateAssessmentEvaluationReportFiles(
intentEvaluationOutput.evaluationReportGroundTruthSetLabelUtteranceStatistics.labelArrayAndMap.stringArray,
intentEvaluationSummary,
assessmentSetIntentLabelsOutputFilename,
assessmentSetIntentSummaryHtmlOutputFilename);
Utility.debuggingLog('OrchestratorAssess.runAsync(), finished calling Utility.generateAssessmentEvaluationReportFiles()');
if (Utility.toPrintDetailedDebuggingLogToConsole) {
Utility.debuggingLog(`intentEvaluationOutput=${Utility.jsonStringify(intentEvaluationOutput)}`);
}
// -----------------------------------------------------------------------
// ---- NOTE ---- integrated step to produce analysis reports ------------
Utility.debuggingLog('OrchestratorAssess.runAsync(), ready to call Utility.generateAssessmentEvaluationReport()');
const entityEvaluationOutput: {
'evaluationReportGroundTruthSetLabelUtteranceStatistics': {
'evaluationSummary': string;
'labelArrayAndMap': ILabelArrayAndMap;
'labelStatisticsAndHtmlTable': {
'labelUtterancesMap': Map<string, Set<string>>;
'labelUtterancesTotal': number;
'labelStatistics': string[][];
'labelStatisticsHtml': string;};
'utteranceStatisticsAndHtmlTable': {
'utteranceStatisticsMap': Map<number, number>;
'utteranceStatistics': StructTextNumber[];
'utteranceCount': number;
'utteranceStatisticsHtml': string;};
/** ---- NOTE-SPURIOUS-STATISTICS-AND-OUTPUT-HTML-TABLE-PLACE-HOLDER-FOR-FUTURE-NEED ----
* 'spuriousLabelStatisticsAndHtmlTable': {
* 'spuriousLabelUtterancesMap': StructTextStringSet[];
* 'spuriousLabelUtterancesTotal': number;
* 'spuriousLabelStatistics': string[][];
* 'spuriousLabelStatisticsHtml': string; };
*/
'utterancesMultiLabelArrays': StructTextText[];
'utterancesMultiLabelArraysHtml': string;
'utteranceLabelDuplicateHtml': string; };
'evaluationReportPredictionSetLabelUtteranceStatistics': {
'evaluationSummary': string;
'labelArrayAndMap': ILabelArrayAndMap;
'labelStatisticsAndHtmlTable': {
'labelUtterancesMap': Map<string, Set<string>>;
'labelUtterancesTotal': number;
'labelStatistics': string[][];
'labelStatisticsHtml': string;};
'utteranceStatisticsAndHtmlTable': {
'utteranceStatisticsMap': Map<number, number>;
'utteranceStatistics': StructTextNumber[];
'utteranceCount': number;
'utteranceStatisticsHtml': string;};
/** ---- NOTE-SPURIOUS-STATISTICS-AND-OUTPUT-HTML-TABLE-PLACE-HOLDER-FOR-FUTURE-NEED ----
* 'spuriousLabelStatisticsAndHtmlTable': {
* 'spuriousLabelUtterancesMap': StructTextStringSet[];
* 'spuriousLabelUtterancesTotal': number;
* 'spuriousLabelStatistics': string[][];
* 'spuriousLabelStatisticsHtml': string; };
*/
'utterancesMultiLabelArrays': StructTextText[];
'utterancesMultiLabelArraysHtml': string;
'utteranceLabelDuplicateHtml': string; };
'evaluationReportSpuriousPredictions': {
'evaluationSummary': string;
'spuriousPredictions': StructTextLabelObjects[]; };
'evaluationReportAnalyses': {
'evaluationSummary': string;
'misclassifiedAnalysis': {
'predictingMisclassifiedUtterancesArrays': string[][];
'predictingMisclassifiedUtterancesArraysHtml': string;
'predictingMisclassifiedUtterancesSimpleArrays': string[][];};
'confusionMatrixAnalysis': {
'confusionMatrix': IConfusionMatrix;
'multiLabelObjectConfusionMatrixExact': MultiLabelObjectConfusionMatrixExact;
'multiLabelObjectConfusionMatrixSubset': MultiLabelObjectConfusionMatrixSubset;
'predictingConfusionMatrixOutputLines': string[][];
'confusionMatrixMetricsHtml': string;
'confusionMatrixAverageMetricsHtml': string;
'confusionMatrixAverageDescriptionMetricsHtml': string;};};
'predictionStructureWithPluralEvaluationLabelObjectArray': PredictionStructureWithPluralEvaluationLabelObject[];
} =
Utility.generateAssessmentLabelObjectEvaluationReport(
groundTruthSetEntityLabels,
predictionSetEntityLabelSet,
groundTruthSetUtteranceEntityLabelsMap,
groundTruthSetUtteranceEntityLabelDuplicateMap,
predictionSetUtteranceEntityLabelsMap,
predictionSetUtteranceEntityLabelDuplicateMap);
if (Utility.toPrintDetailedDebuggingLogToConsole) {
Utility.debuggingLog(`entityEvaluationOutput=${Utility.jsonStringify(entityEvaluationOutput)}`);
}
Utility.debuggingLog('OrchestratorAssess.runAsync(), finished calling Utility.generateAssessmentEvaluationReport()');
// -----------------------------------------------------------------------
// ---- NOTE ---- integrated step to produce analysis report output files.
if (Utility.toPrintDetailedDebuggingLogToConsole) {
Utility.debuggingLog(`OrchestratorAssess.runAsync(), entityEvaluationOutput.evaluationReportGroundTruthSetLabelUtteranceStatistics.evaluationSummary=\n${entityEvaluationOutput.evaluationReportGroundTruthSetLabelUtteranceStatistics.evaluationSummary}`);
}
let entityEvaluationSummary: string =
entityEvaluationOutput.evaluationReportAnalyses.evaluationSummary;
// -----------------------------------------------------------------------
entityEvaluationSummary = entityEvaluationSummary.replace(
'{APP_NAME}',
'');
entityEvaluationSummary = entityEvaluationSummary.replace(
'{MODEL_SPECIFICATION}',
'');
// -----------------------------------------------------------------------
Utility.generateAssessmentEvaluationReportFiles(
entityEvaluationOutput.evaluationReportGroundTruthSetLabelUtteranceStatistics.labelArrayAndMap.stringArray,
entityEvaluationSummary,
assessmentSetEntityLabelsOutputFilename,
assessmentSetEntitySummaryHtmlOutputFilename);
Utility.debuggingLog('OrchestratorAssess.runAsync(), finished calling Utility.generateAssessmentEvaluationReportFiles()');
if (Utility.toPrintDetailedDebuggingLogToConsole) {
Utility.debuggingLog(`entityEvaluationOutput=${Utility.jsonStringify(entityEvaluationOutput)}`);
}
// -----------------------------------------------------------------------
// ---- NOTE ---- THE END
Utility.debuggingLog('OrchestratorAssess.runAsync(), THE END');
}
} | the_stack |
import editly = require('editly');
const { renderSingleFrame } = editly;
/* examples/alpha.json5 */
// $ExpectType Promise<void>
editly({
enableFfmpegLog: true,
outPath: './alpha.mp4',
clips: [
{
duration: 2,
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0.4, cutTo: 2 },
{ type: 'video', path: './assets/dancer1.webm', resizeMode: 'contain', cutFrom: 0, cutTo: 6 },
],
},
{
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0.4, cutTo: 2 },
{ type: 'video', path: './assets/dancer1.webm', resizeMode: 'contain' },
],
},
],
});
/* examples/audio-transition.json5 */
// $ExpectType Promise<void>
editly({
enableFfmpegLog: true,
outPath: './audio-transition.mp4',
keepSourceAudio: true,
defaults: {
duration: 3,
transition: { duration: 1, name: 'directional' },
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
layers: [
{ type: 'title-background', text: 'Default transition' },
{ type: 'audio', path: './assets/sample1.m4a' },
],
},
{
transition: { duration: 0.2 },
layers: [
{ type: 'title-background', text: 'Fast transition' },
{ type: 'audio', path: './assets/sample2.m4a' },
],
},
{
transition: { duration: 0 },
layers: [
{ type: 'title-background', text: 'No transition' },
{ type: 'audio', path: './assets/sample1.m4a' },
],
},
{
transition: { audioInCurve: 'exp', audioOutCurve: 'exp' },
layers: [
{ type: 'title-background', text: 'Exp curve' },
{ type: 'audio', path: './assets/sample2.m4a' },
],
},
{
transition: { name: 'dummy' },
layers: [
{ type: 'title-background', text: 'Dummy' },
{ type: 'audio', path: './assets/sample1.m4a' },
],
},
{
transition: { duration: 2 },
layers: [
{ type: 'title-background', text: 'Too short' },
{ type: 'audio', path: './assets/sample2.m4a' },
],
},
{
duration: 1,
transition: { duration: 2 },
layers: [
{ type: 'title-background', text: 'Too short' },
{ type: 'audio', path: './assets/sample2.m4a' },
],
},
{
duration: 1,
transition: { duration: 2 },
layers: [
{ type: 'title-background', text: 'Too short' },
{ type: 'audio', path: './assets/sample2.m4a' },
],
},
{
layers: [
{ type: 'title-background', text: 'THE END' },
{ type: 'audio', path: './assets/sample2.m4a' },
],
},
],
});
/* examples/audio-volume.json5 */
// $ExpectType Promise<void>
editly({
outPath: './audio-volume.mp4',
width: 200,
height: 200,
clips: [{ duration: 2, layers: [{ type: 'title-background', text: 'Audio output volume' }] }],
audioTracks: [{ path: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a', cutFrom: 18 }],
outputVolume: '-10dB',
});
/* examples/audio1.json5 */
// $ExpectType Promise<void>
editly({
enableFfmpegLog: true,
outPath: './audio1.mp4',
keepSourceAudio: true,
defaults: {
transition: null,
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{ duration: 0.5, layers: [{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0.4, cutTo: 2 }] },
{
layers: [
{ type: 'title-background', text: 'test' },
{
type: 'audio',
path: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a',
cutFrom: 2,
cutTo: 5,
},
],
},
{
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0, cutTo: 2, mixVolume: 0 },
{
type: 'audio',
path: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a',
mixVolume: 0.1,
},
],
},
{
duration: 2,
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0.4, cutTo: 2 },
{
type: 'audio',
path: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a',
cutFrom: 2,
cutTo: 3,
mixVolume: 0.5,
},
],
},
{ duration: 1.8, layers: [{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 1, cutTo: 2 }] },
],
});
/* examples/audio2.json5 */
// $ExpectType Promise<void>
editly({
enableFfmpegLog: true,
outPath: './audio2.mp4',
width: 200,
height: 200,
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{ layers: [{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 1, cutTo: 2 }] },
{ duration: 15, layers: { type: 'title-background', text: 'Audio track' } },
],
audioNorm: { enable: true, gaussSize: 3, maxGain: 100 },
clipsAudioVolume: 50,
audioTracks: [
{ path: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a', cutFrom: 18 },
{ path: './assets/winxp.mp3', mixVolume: 10, cutFrom: 1, cutTo: 2, start: 2 },
{ path: './assets/Julen_ribas.m4a', mixVolume: 50, cutTo: 7, start: 5 },
],
});
/* examples/audio3.json5 */
// $ExpectType Promise<void>
editly({
outPath: './audio3.mp4',
width: 200,
height: 200,
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutTo: 2 },
{ type: 'title', text: 'Arbitrary audio' },
],
},
{
duration: 3,
layers: [
{ type: 'title-background', text: 'Voice starts in 1 sec' },
{ type: 'detached-audio', path: './assets/Julen_ribas.m4a', mixVolume: 50, cutFrom: 2, start: 1 },
],
},
{ duration: 1, layers: [{ type: 'title-background', text: 'Voice continues over clip 2' }] },
{ duration: 3, layers: [{ type: 'title-background', text: 'Voice continues over clip 3' }] },
{
duration: 2,
layers: [
{ type: 'title-background', text: 'XP sound starts' },
{ type: 'detached-audio', path: './assets/winxp.mp3', mixVolume: 10, cutFrom: 0.5 },
],
},
],
audioNorm: { enable: true, gaussSize: 3, maxGain: 100 },
audioTracks: [{ path: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a', cutFrom: 18 }],
});
/* examples/audioLoop.json5 */
// $ExpectType Promise<void>
editly({
outPath: './audioLoop.mp4',
width: 200,
height: 200,
audioFilePath: './assets/winxp.mp3',
loopAudio: true,
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [{ duration: 10, layers: [{ type: 'title-background', text: 'Looping audio!' }] }],
});
/* examples/commonFeatures.json5 */
// $ExpectType Promise<void>
editly({
width: 720,
height: 1280,
fps: 30,
outPath: './commonFeatures.mp4',
audioFilePath: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a',
defaults: {
transition: { name: 'random' },
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 3,
transition: { name: 'directional-left' },
layers: [
{
type: 'title-background',
text: 'EDITLY\nVideo editing framework',
background: { type: 'linear-gradient', colors: ['#02aab0', '#00cdac'] },
},
],
},
{
duration: 4,
transition: { name: 'dreamyzoom' },
layers: [
{
type: 'title-background',
text: 'Multi-line text with animated linear or radial gradients',
background: { type: 'radial-gradient' },
},
],
},
{
duration: 3,
transition: { name: 'directional-right' },
layers: [{ type: 'rainbow-colors' }, { type: 'title', text: 'Colorful backgrounds' }],
},
{ duration: 3, layers: [{ type: 'pause' }, { type: 'title', text: 'and separators' }] },
{
duration: 3,
transition: { name: 'fadegrayscale' },
layers: [
{
type: 'title-background',
text: 'Image slideshows with Ken Burns effect',
background: { type: 'linear-gradient' },
},
],
},
{
duration: 2.5,
transition: { name: 'directionalWarp' },
layers: [{ type: 'image', path: './assets/vertical.jpg', zoomDirection: 'out' }],
},
{
duration: 3,
transition: { name: 'dreamyzoom' },
layers: [
{ type: 'image', path: './assets/img1.jpg', duration: 2.5, zoomDirection: 'in' },
{
type: 'subtitle',
text: 'Indonesia has many spectacular locations. Here is the volcano Kelimutu, which has three lakes in its core, some days with three different colors!',
},
{ type: 'title', position: 'top', text: 'With text' },
],
},
{
duration: 3,
transition: { name: 'colorphase' },
layers: [
{ type: 'image', path: './assets/img2.jpg', zoomDirection: 'out' },
{ type: 'subtitle', text: 'Komodo national park is the only home of the endangered Komodo dragons' },
],
},
{
duration: 2.5,
transition: { name: 'simplezoom' },
layers: [{ type: 'image', path: './assets/img3.jpg', zoomDirection: 'in' }],
},
{
duration: 1.5,
transition: { name: 'crosszoom', duration: 0.3 },
layers: [
{ type: 'video', path: 'assets/kohlipe1.mp4', cutTo: 58 },
{ type: 'title', text: 'Videos' },
],
},
{
duration: 3,
transition: { name: 'fade' },
layers: [{ type: 'video', path: 'assets/kohlipe1.mp4', cutFrom: 58 }],
},
{ transition: { name: 'fade' }, layers: [{ type: 'video', path: 'assets/kohlipe2.mp4', cutTo: 2.5 }] },
{ duration: 1.5, layers: [{ type: 'video', path: 'assets/kohlipe3.mp4', cutFrom: 3, cutTo: 30 }] },
{
duration: 3,
transition: { name: 'crosszoom' },
layers: [
{ type: 'gl', fragmentPath: './assets/shaders/3l23Rh.frag' },
{ type: 'title', text: 'OpenGL\nshaders' },
],
},
{ duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/MdXyzX.frag' }] },
{ duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/30daysofshade_010.frag' }] },
{ duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/wd2yDm.frag', speed: 5 }] },
{
duration: 3,
layers: [
{ type: 'image', path: './assets/91083241_573589476840991_4224678072281051330_n.jpg' },
{ type: 'news-title', text: 'BREAKING NEWS' },
{
type: 'subtitle',
text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ' +
'exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla ' +
'pariatur.',
backgroundColor: 'rgba(0,0,0,0.5)',
},
],
},
{
duration: 3,
layers: [
{ type: 'rainbow-colors' },
{
type: 'video',
path: './assets/tungestolen.mp4',
resizeMode: 'contain',
width: 0.4,
height: 0.4,
top: 0.05,
left: 0.95,
originY: 'top',
originX: 'right',
},
{ type: 'title', position: 'bottom', text: 'Picture-in-Picture' },
],
},
{ duration: 3, layers: [{ type: 'editly-banner' }] },
],
});
/* examples/contain-blur.json5 */
// $ExpectType Promise<void>
editly({
width: 3000,
height: 2000,
fps: 15,
outPath: './contain-blur.mp4',
defaults: {
transition: null,
},
clips: [
{ duration: 0.3, layers: [{ type: 'image', path: './assets/vertical.jpg', zoomDirection: null }] },
{ duration: 0.5, layers: [{ type: 'video', path: './assets/IMG_1884.MOV', cutFrom: 0, cutTo: 2 }] },
],
});
/* examples/customCanvas.js */
// $ExpectType Promise<void>
editly({
fast: true,
outPath: './customCanvas.gif',
clips: [
{
duration: 2,
layers: [
{ type: 'rainbow-colors' },
{
type: 'canvas',
func: ({ canvas }) => ({
onRender: progress => {
const context = canvas.getContext();
const centerX = canvas.width! / 2;
const centerY = canvas.height! / 2;
const radius = 40 * (1 + progress * 0.5);
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'hsl(350, 100%, 37%)';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#fff';
context.stroke();
},
}),
},
],
},
],
});
/* examples/customFabric.js */
// $ExpectType Promise<void>
editly({
fast: true,
outPath: './customFabric.gif',
clips: [
{
duration: 2,
layers: [
{
type: 'fabric',
func: ({ width, height, fabric }) => ({
onRender: (progress, canvas) => {
canvas.backgroundColor = 'hsl(33, 100%, 50%)';
const text = new fabric.Text(`PROGRESS\n${Math.floor(progress * 100)}%`, {
originX: 'center',
originY: 'center',
left: width / 2,
top: (height / 2) * (1 + (progress * 0.1 - 0.05)),
fontSize: 20,
textAlign: 'center',
fill: 'white',
});
canvas.add(text);
},
}),
},
],
},
],
});
/* examples/customOutputArgs.json5 */
// $ExpectType Promise<void>
editly({
outPath: './customOutputArgs.webp',
clips: [{ duration: 2, layers: [{ type: 'title-background', text: 'Custom output args' }] }],
customOutputArgs: ['-compression_level', '5', '-qscale', '60', '-vcodec', 'libwebp'],
});
/* examples/gl.json5 */
// $ExpectType Promise<void>
editly({
outPath: './gl.mp4',
clips: [
{ transition: null, duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/3l23Rh.frag' }] },
{ duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/MdXyzX.frag' }] },
{ duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/30daysofshade_010.frag', speed: 1 }] },
{ duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/rainbow-background.frag' }] },
{ duration: 3, layers: [{ type: 'gl', fragmentPath: './assets/shaders/wd2yDm.frag', speed: 5 }] },
],
});
/* examples/gradients.json5 */
// $ExpectType Promise<void>
editly({
outPath: './gradients.mp4',
defaults: {
transition: { name: 'linearblur', duration: 0.1 },
},
clips: [
{ duration: 1, layers: [{ type: 'linear-gradient', colors: ['#02aab0', '#00cdac'] }] },
{ duration: 1, layers: [{ type: 'radial-gradient', colors: ['#b002aa', '#ac00cd'] }] },
{ duration: 1, layers: [{ type: 'linear-gradient' }] },
{ duration: 1, layers: [{ type: 'radial-gradient' }] },
],
});
/* examples/image.json5 */
// $ExpectType Promise<void>
editly({
width: 600,
height: 300,
outPath: './image.mp4',
defaults: {
transition: null,
duration: 0.2,
},
clips: [
{ layers: [{ type: 'image', path: './assets/pano.jpg' }] },
{ layers: [{ type: 'image', path: './assets/vertical.jpg' }] },
{
layers: [
{ type: 'fill-color', color: 'white' },
{ type: 'image', path: './assets/pano.jpg', resizeMode: 'contain' },
],
},
{
layers: [
{ type: 'fill-color', color: 'white' },
{ type: 'image', path: './assets/vertical.jpg', resizeMode: 'contain' },
],
},
{ layers: [{ type: 'image', path: './assets/pano.jpg', resizeMode: 'cover' }] },
{ layers: [{ type: 'image', path: './assets/vertical.jpg', resizeMode: 'cover' }] },
{ layers: [{ type: 'image', path: './assets/pano.jpg', resizeMode: 'stretch' }] },
{ layers: [{ type: 'image', path: './assets/vertical.jpg', resizeMode: 'stretch' }] },
],
});
/* examples/imageOverlay.json5 */
// $ExpectType Promise<void>
editly({
outPath: './imageOverlay.mp4',
clips: [
{
layers: [
{ type: 'video', path: './assets/changi.mp4', cutTo: 2 },
{
type: 'image-overlay',
path: './assets/overlay.svg',
width: 0.2,
position: { x: 0.95, y: 0.03, originX: 'right' },
},
{ type: 'image-overlay', path: './assets/emoji.png', stop: 0.5, zoomDirection: 'in' },
{
type: 'image-overlay',
path: './assets/emoji2.svg',
position: 'top',
start: 0.7,
stop: 1.5,
width: 0.2,
},
{
type: 'image-overlay',
path: './assets/emoji2.svg',
position: 'bottom',
start: 0.7,
stop: 1.5,
height: 0.2,
},
],
},
],
});
/* examples/kenBurns.json5 */
// $ExpectType Promise<void>
editly({
outPath: './kenBurns.mp4',
defaults: {
transition: { name: 'fade' },
},
clips: [
{ duration: 3, layers: [{ type: 'image', path: './assets/img2.jpg', zoomDirection: 'out' }] },
{ duration: 3, layers: [{ type: 'image', path: './assets/img3.jpg', zoomDirection: 'in' }] },
{ duration: 3, layers: [{ type: 'image', path: './assets/img1.jpg', zoomDirection: null }] },
],
});
/* examples/losslesscut.json5 */
// $ExpectType Promise<void>
editly({
fast: false,
outPath: './losslesscut.mp4',
verbose: true,
enableFfmpegLog: true,
fps: 30,
audioFilePath: './Believe - Roa [Vlog No Copyright Music]-qldyHxWPFUY.m4a',
defaults: {
transition: { name: 'crossZoom', duration: 1 },
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 3,
layers: [{ type: 'title-background', text: 'LosslessCut', background: { type: 'linear-gradient' } }],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/intro.mov' }] },
{
duration: 3,
layers: [
{
type: 'title-background',
text: 'Capture full resolution screenshots',
background: { type: 'radial-gradient' },
},
],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/capture screenshots.mov' }] },
{
duration: 3,
layers: [
{
type: 'title-background',
text: 'Extract tracks as individual files',
background: { type: 'radial-gradient' },
},
],
},
{
layers: [
{
type: 'video',
path: '/Users/mifi/Desktop/losslesscut-usage/extract tracks as individual files.mov',
},
],
},
{
duration: 3,
layers: [
{
type: 'title-background',
text: 'Keyframes and zoom',
background: { type: 'radial-gradient' },
},
],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/keyframes and zoom.mov' }] },
{
duration: 3,
layers: [{ type: 'title-background', text: 'Label segments', background: { type: 'radial-gradient' } }],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/label segments.mov' }] },
{
duration: 3,
layers: [
{
type: 'title-background',
text: 'Lossless rotation',
background: { type: 'radial-gradient' },
},
],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/lossless rotation.mov' }] },
{
duration: 3,
layers: [{ type: 'title-background', text: 'Thumbnails', background: { type: 'radial-gradient' } }],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/thumbnails.mov' }] },
{
duration: 3,
layers: [
{
type: 'title-background',
text: 'Audio waveforms',
background: { type: 'radial-gradient' },
},
],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/audio waveform.mov' }] },
{
duration: 3,
layers: [
{
type: 'title-background',
text: 'Track information',
background: { type: 'radial-gradient' },
},
],
},
{ layers: [{ type: 'video', path: '/Users/mifi/Desktop/losslesscut-usage/track information.mov' }] },
{
duration: 3,
layers: [
{
type: 'title-background',
text: 'Tracks editor and audio swap',
background: { type: 'radial-gradient' },
},
],
},
{
layers: [
{
type: 'video',
path: '/Users/mifi/Desktop/losslesscut-usage/tracks editor and replace audio.mov',
},
],
},
{
duration: 4,
layers: [
{
type: 'title-background',
text: 'Get it from\nMac App Store\nWindows Store',
background: { type: 'fill-color', color: 'black' },
},
],
},
{ duration: 2, layers: [{ type: 'editly-banner' }] },
],
});
/* examples/lowerThirds1Line.json5 */
// $ExpectType Promise<void>
editly({
width: 1280,
height: 720,
outPath: './lowerThirds1Line.mp4',
clips: [
{
duration: 7,
layers: [
{ type: 'fill-color', color: '#555' },
{ type: 'video', path: 'assets/lowerthirds/UHD_DMGMORI_Lwr3rd_1Line.mov', resizeMode: 'contain' },
{
type: 'slide-in-text',
text: 'Lower Line Regular Source Text',
position: { x: 0.035, y: 0.93, originX: 'left', originY: 'bottom' },
color: '#000',
fontSize: 0.021,
charSpacing: 0.025,
fontPath: './assets/lowerthirds/FF DIN Pro Light.otf',
},
],
},
],
});
/* examples/lowerThirds2Lines.json5 */
// $ExpectType Promise<void>
editly({
width: 1280,
height: 720,
outPath: './lowerThirds2Lines.mp4',
clips: [
{
duration: 7,
layers: [
{ type: 'fill-color', color: '#555' },
{ type: 'video', path: 'assets/lowerthirds/UHD_DMGMORI_Lwr3rd_2Lines.webm', resizeMode: 'contain' },
{
type: 'slide-in-text',
text: 'Upper Line Bold Source Text',
position: { x: 0.035, y: 0.877, originX: 'left', originY: 'bottom' },
color: '#000',
fontSize: 0.021,
charSpacing: 0.03,
fontPath: './assets/lowerthirds/FF DIN Pro Medium.otf',
},
{
type: 'slide-in-text',
text: 'Lower Line Regular Source Text',
position: { x: 0.035, y: 0.93, originX: 'left', originY: 'bottom' },
color: '#000',
fontSize: 0.021,
charSpacing: 0.025,
fontPath: './assets/lowerthirds/FF DIN Pro Light.otf',
},
],
},
],
});
/* examples/mosaic.json5 */
// $ExpectType Promise<void>
editly({
width: 500,
height: 500,
outPath: './mosaic.mp4',
defaults: {
transition: { duration: 0 },
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
layerType: {
video: { width: 0.4, height: 0.4 },
},
},
clips: [
{
duration: 2,
layers: [
{
type: 'video',
path: './assets/palawan.mp4',
cutFrom: 0,
cutTo: 2,
resizeMode: 'cover',
top: 0.5,
left: 0.5,
originY: 'center',
originX: 'center',
},
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'contain' },
{
type: 'video',
path: './assets/palawan.mp4',
cutFrom: 0,
cutTo: 2,
resizeMode: 'contain-blur',
left: 1,
originX: 'right',
},
{
type: 'video',
path: './assets/IMG_1884.MOV',
cutFrom: 0,
cutTo: 2,
resizeMode: 'contain-blur',
left: 1,
top: 1,
originX: 'right',
originY: 'bottom',
},
{
type: 'video',
path: './assets/palawan.mp4',
cutFrom: 0,
cutTo: 2,
resizeMode: 'stretch',
top: 1,
originY: 'bottom',
},
],
},
],
});
/* examples/newsTitle.json5 */
// $ExpectType Promise<void>
editly({
width: 900,
height: 1600,
outPath: './newsTitle.mp4',
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 10,
layers: [
{ type: 'image', path: './assets/91083241_573589476840991_4224678072281051330_n.jpg' },
{ type: 'news-title', text: 'BREAKING NEWS' },
{
type: 'subtitle',
text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ' +
'exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla ' +
'pariatur.',
backgroundColor: 'rgba(0,0,0,0.5)',
},
],
},
],
});
/* examples/ph.json5 */
// $ExpectType Promise<void>
editly({
width: 240,
height: 240,
fps: 14,
outPath: './ph.gif',
defaults: {
transition: { duration: 0.4 },
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 1,
transition: { name: 'directionalWarp' },
layers: [
{ type: 'image', path: './assets/vertical.jpg', zoomDirection: 'out' },
{ type: 'title', text: 'EDITLY' },
],
},
{
duration: 1.5,
transition: { name: 'dreamyzoom' },
layers: [
{ type: 'image', path: './assets/img1.jpg', duration: 2.5, zoomDirection: 'in' },
{ type: 'title', position: 'bottom', text: 'Video editing API' },
],
},
{
duration: 2,
layers: [
{ type: 'image', path: './assets/91083241_573589476840991_4224678072281051330_n.jpg' },
{ type: 'news-title', text: 'EDITLY' },
{ type: 'subtitle', text: 'Get it from npm', backgroundColor: 'rgba(0,0,0,0.5)' },
],
},
],
});
/* examples/pip.json5 */
// $ExpectType Promise<void>
editly({
outPath: './pip.mp4',
width: 1280,
height: 720,
fps: 30,
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 4,
layers: [
{ type: 'rainbow-colors' },
{
type: 'video',
path: './assets/tungestolen.mp4',
resizeMode: 'cover',
width: 0.3,
height: 0.4,
top: 0.05,
left: 0.95,
originY: 'top',
originX: 'right',
},
{
type: 'video',
path: './assets/tungestolen.mp4',
resizeMode: 'cover',
width: 0.4,
height: 0.2,
top: 0.05,
left: 0.05,
originY: 'top',
originX: 'left',
},
{ type: 'title', position: 'bottom', text: 'Picture-in-Picture' },
],
},
],
});
/* examples/position.json5 */
// $ExpectType Promise<void>
editly({
outPath: './position.mp4',
defaults: {
layerType: {
'image-overlay': { width: 0.1 },
},
},
clips: [
{
layers: [
{ type: 'rainbow-colors' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'top' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'center' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'bottom' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'top-left' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'top-right' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'center-left' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'center-right' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'bottom-left' },
{ type: 'image-overlay', path: './assets/emoji2.svg', position: 'bottom-right' },
{
type: 'image-overlay',
path: './assets/emoji.png',
width: 0.06,
position: { originX: 'center', originY: 'center', x: 0.75, y: 0.75 },
},
],
},
],
});
/* examples/remote.json5 */
// $ExpectType Promise<void>
editly({
outPath: './remote.mp4',
allowRemoteRequests: true,
audioFilePath: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a',
clips: [
{ layers: [{ type: 'image', path: 'https://picsum.photos/400/400' }] },
{ layers: [{ type: 'image', path: 'https://picsum.photos/200/400' }] },
{ layers: [{ type: 'image', path: 'https://picsum.photos/400/200' }] },
],
});
/* examples/renderSingleFrame.js */
// $ExpectType Promise<void>
renderSingleFrame({
time: 0,
clips: [
{
duration: 2,
layers: [
{
type: 'title-background',
text: 'Editly can handle all formats and sizes with different fits',
background: { type: 'radial-gradient' },
},
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'contain' },
{ type: 'title', text: 'Contain' },
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'contain-blur' },
{ type: 'title', text: 'Contain (blur)' },
],
},
{
layers: [
{ type: 'video', path: './assets/IMG_1884.MOV', cutFrom: 0, cutTo: 2, resizeMode: 'contain-blur' },
{ type: 'title', text: 'Contain\n(blur, vertical)' },
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'stretch' },
{ type: 'title', text: 'Stretch' },
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'cover' },
{ type: 'title', text: 'Cover' },
],
},
],
});
/* examples/single.json5 */
// $ExpectType Promise<void>
editly({
// This is a test of a single clip to make sure that it works
outPath: './single.mp4',
keepSourceAudio: true,
clips: [{ layers: [{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0, cutTo: 2 }] }],
});
/* examples/slideInText.json5 */
// $ExpectType Promise<void>
editly({
outPath: './slideInText.mp4',
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 3,
layers: [
{ type: 'image', path: 'assets/img2.jpg' },
{
type: 'slide-in-text',
text: 'Text that slides in',
color: '#fff',
position: { x: 0.04, y: 0.93, originY: 'bottom', originX: 'left' },
fontSize: 0.05,
},
],
},
],
});
/* examples/smartFit.json5 */
// $ExpectType Promise<void>
editly({
enableFfmpegLog: true,
outPath: './smartFit.mp4',
defaults: {
transition: null,
layer: { backgroundColor: 'white' },
},
clips: [
{ layers: [{ type: 'video', path: './assets/changi.mp4', cutFrom: 0.4, cutTo: 2 }] },
{ layers: [{ type: 'video', path: './assets/changi.mp4', cutFrom: 0.4, cutTo: 2, resizeMode: 'contain' }] },
{ layers: [{ type: 'video', path: './assets/changi.mp4', cutFrom: 0.4, cutTo: 2, resizeMode: 'stretch' }] },
],
});
/* examples/speedTest.json5 */
// $ExpectType Promise<void>
editly({
outPath: './speedTest.mp4',
defaults: {
transition: null,
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 2,
layers: [
{
type: 'title-background',
text: 'Speed up or slow down video',
background: { type: 'radial-gradient' },
},
],
},
{
duration: 2,
layers: [
{ type: 'video', path: './assets/changi.mp4', cutFrom: 0, cutTo: 2 },
{ type: 'title', text: 'Same speed' },
],
},
{
duration: 1,
layers: [
{ type: 'video', path: './assets/changi.mp4', cutFrom: 0, cutTo: 4 },
{ type: 'title', text: '4x' },
],
},
{
duration: 2,
layers: [
{ type: 'video', path: './assets/changi.mp4', cutFrom: 0, cutTo: 1 },
{ type: 'title', text: '1/2x' },
],
},
],
});
/* examples/subtitle.json5 */
// $ExpectType Promise<void>
editly({
outPath: './subtitle.mp4',
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
layerType: { 'fill-color': { color: '#00aa00' } },
},
clips: [
{
duration: 2,
layers: [
{ type: 'rainbow-colors' },
{
type: 'subtitle',
text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ' +
'exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla ' +
'pariatur. Excepteur sint occaecat cupidatat non proident.',
},
{ type: 'title', position: 'top', text: 'Subtitles' },
],
},
{
duration: 2,
layers: [
{ type: 'fill-color' },
{
type: 'title',
position: { x: 0, y: 1, originY: 'bottom' },
text: 'Custom position',
zoomDirection: null,
},
],
},
],
});
/* examples/timeoutTest.json5 */
// $ExpectType Promise<void>
editly({
outPath: './timeoutTest.mp4',
clips: [
{
duration: 1.5,
transition: { name: 'crosszoom', duration: 0.3 },
layers: [{ type: 'video', path: './assets/tungestolen.mp4', cutTo: 58 }],
},
{
duration: 3,
transition: { name: 'fade' },
layers: [{ type: 'video', path: './assets/tungestolen.mp4', cutFrom: 0 }],
},
],
});
/* examples/transitionEasing.json5 */
// $ExpectType Promise<void>
editly({
fast: true,
outPath: './transitionEasing.mp4',
defaults: {
duration: 2,
},
clips: [
{
transition: { name: 'directional', duration: 0.5 },
layers: [{ type: 'video', path: 'assets/changi.mp4', cutTo: 2 }],
},
{
transition: { name: 'directional', duration: 0.5, params: { direction: [1, 0] } },
layers: [{ type: 'video', path: 'assets/lofoten.mp4', cutTo: 2 }],
},
{
transition: { name: 'directional', duration: 0.5, easing: null },
layers: [{ type: 'video', path: 'assets/lofoten.mp4', cutTo: 2 }],
},
{ layers: [{ type: 'pause' }] },
],
});
/* examples/transparentGradient.json5 */
// $ExpectType Promise<void>
editly({
fast: true,
outPath: './transparentGradient.mp4',
clips: [
{
duration: 0.1,
layers: [
{ type: 'fill-color', color: 'green' },
{ type: 'linear-gradient', colors: ['#ffffffff', '#ffffff00'] },
],
},
],
});
/* examples/videos.json5 */
// $ExpectType Promise<void>
editly({
width: 600,
height: 800,
outPath: './videos.mp4',
defaults: {
transition: { duration: 0 },
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 2,
layers: [
{
type: 'title-background',
text: 'Editly can handle all formats and sizes with different fits',
background: { type: 'radial-gradient' },
},
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'contain' },
{ type: 'title', text: 'Contain' },
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'contain-blur' },
{ type: 'title', text: 'Contain (blur)' },
],
},
{
layers: [
{ type: 'video', path: './assets/IMG_1884.MOV', cutFrom: 0, cutTo: 2, resizeMode: 'contain-blur' },
{ type: 'title', text: 'Contain\n(blur, vertical)' },
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'stretch' },
{ type: 'title', text: 'Stretch' },
],
},
{
layers: [
{ type: 'video', path: './assets/palawan.mp4', cutFrom: 0, cutTo: 2, resizeMode: 'cover' },
{ type: 'title', text: 'Cover' },
],
},
],
});
/* examples/videos2.json5 */
// $ExpectType Promise<void>
editly({
verbose: true,
enableFfmpegLog: true,
outPath: './video2.mp4',
defaults: {
transition: {
name: 'linearblur',
},
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
layers: [
{ type: 'video', path: './assets/changi.mp4', cutFrom: 0, cutTo: 2 },
{ type: 'title', text: 'Video 1' },
],
},
{ layers: [{ type: 'video', path: './assets/IMG_1884.MOV', cutFrom: 0, cutTo: 2 }] },
],
});
/* examples/vignette.json5 */
// $ExpectType Promise<void>
editly({
outPath: './vignette.mp4',
clips: [
{
layers: [
{ type: 'video', path: './assets/tungestolen.mp4', cutTo: 2 },
{ type: 'image', path: './assets/vignette.png', resizeMode: 'stretch', zoomDirection: null },
],
},
],
});
/* examples/visibleFromUntil.json5 */
// $ExpectType Promise<void>
editly({
enableFfmpegLog: true,
outPath: './visibleFromUntil.mp4',
defaults: {
layer: { fontPath: './assets/Patua_One/PatuaOne-Regular.ttf' },
},
clips: [
{
duration: 2,
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0.4, cutTo: 2 },
{
type: 'video',
path: './assets/dancer1.webm',
resizeMode: 'contain',
cutFrom: 0,
cutTo: 6,
start: 0.5,
stop: 1,
},
],
},
{
duration: 2,
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0.5, cutTo: 3.5 },
{ type: 'news-title', text: 'Hei', start: 0.5, stop: 1 },
],
},
{
layers: [
{ type: 'video', path: './assets/lofoten.mp4', cutFrom: 0, cutTo: 4 },
{ type: 'video', path: './assets/changi.mp4', cutFrom: 0, cutTo: 1, start: 1, stop: 2 },
],
},
],
}); | the_stack |
import { UInt64 } from '../int64'
import { Pos } from '../pos'
import { Storage, types, intTypes } from "../ast"
import { ID, Fun, Block, Value, BranchPrediction, Location, BlockKind } from './ssa'
import { Config } from './config'
import { DesiredState } from './reg_desiredstate'
import { IntGraph } from '../intgraph'
import { Op } from './op'
import { ops, opinfo } from "./ops"
import { BlockTree } from "./blocktree"
// import { printir } from './repr'
import {
Register,
Reg,
RegSet,
RegInfo,
fmtRegSet,
emptyRegSet,
nilRegInfo,
} from './reg'
// set to true to enable debugging output
const DEBUG_REGALLOC = DEBUG && false
import { debuglog as dlog_ } from '../util'
const dlog = DEBUG_REGALLOC ? dlog_ : function(..._ :any[]){}
const allocatorCache = new Map<Config,RegAllocator>()
let allocator :RegAllocator|null = null
// regalloc allocates registers for function f
//
export function regalloc(f :Fun, config :Config) {
if (!allocator || allocator.config !== config) {
allocator = allocatorCache.get(config) || null
if (!allocator) {
allocator = new RegAllocator(config)
allocatorCache.set(config, allocator)
}
}
allocator.regallocFun(f)
}
// distance is a measure of how far into the future values are used.
// distance is measured in units of instructions.
const
likelyDistance = 1
, normalDistance = 10
, unlikelyDistance = 100
interface LiveInfo {
id :ID // ID of value
dist :int // # of instructions before next use
pos :Pos // source position of next use
}
interface ValMapEntry {
val :int
pos :Pos
}
class StartReg {
r :Register
v :Value // pre-regalloc value needed in this register
c :Value // cached version of the value
pos :Pos // source position of use of this register
}
class EndReg {
r :Register
v :Value // pre-regalloc value held in this register (TODO: can we use ID here?)
c :Value // cached version of the value
}
const maxregs = 64 // maximum number of registers we can manage
const noReg :Reg = 255 >>> 0 // symbolizes "none"
// countRegs returns the number of set bits in the register mask.
//
function countRegs(m :RegSet) :int {
return m.popcnt()
// let n = 0
// while (m != 0) {
// n += m & 1
// m >>= 1
// }
// return n
}
// pickReg picks an arbitrary register from the register mask.
//
function pickReg(m :RegSet) :Reg {
// pick the lowest one
if (m.isZero()) {
panic("can't pick a register from an empty set")
}
for (let i :Reg = 0; ; i++) {
if (!m.and(UInt64.ONE).isZero()) {
return i
}
m = m.shr(1) // m = m >> 1
}
}
// interface Use {
// dist :int // distance from start of the block to a use of a value
// next :Use|null // linked list of uses of a value in nondecreasing dist order
// // pos :Pos // source position of the use
// }
// ValState records the register allocation state for a (pre-regalloc) value.
class ValState {
v :Value
regs = emptyRegSet as RegSet
// the set of registers holding a Value (usually just one)
// uses = null as Use|null // list of uses in this block
spill = null as Value|null // spilled copy of the Value (if any)
restoreMin = 0 as int // minimum of all restores' blocks' sdom.entry
restoreMax = 0 as int // maximum of all restores' blocks' sdom.exit
needReg = false as bool
rematerializeable = false as bool // cached value of v.rematerializeable()
mindist :int = 0 // distance between definition and first use
maxdist :int = 0 // distance between definition and last use
constructor(v :Value) {
this.v = v
}
toString() :string {
return `ValState{${this.v}, regs=${this.regs}}`
}
}
// interface RegState {
// v :Value|null // Original (preregalloc) Value stored in this register.
// c :Value|null // A Value equal to v which is currently in a register.
// // Might be v or a copy of it.
// // If a register is unused, v==c==nil
// }
export class RegAllocator {
readonly config :Config
readonly addrsize :Storage
readonly addrtype = types.u32
// labels :Map<Value,int> // maps values to addresses
readonly registers :Register[] // registers of the target architecture
readonly numregs :int // always == registers.length
readonly allocatable :RegSet // registers we are allowed to allocate
f :Fun // function being processed
sdom :BlockTree // initially the result of f.sdom()
visitOrder :Block[] = []
// For each Value, map from its value id back to the
// preregalloc Value it was derived from.
orig :(Value|null)[]
SPReg :Reg // the SP register
SBReg :Reg // the SB register
GReg :Reg // the g register (current coroutine)
// current state of each (preregalloc) Value
values :ValState[] = []
sp :Value|null = null // ID of SP register Value
sb :Value|null = null // ID of SB register Value
// current state of each register
// regs :RegState[]
nospill :RegSet // registers that contain values which can't be kicked out
used :RegSet // registers currently in use
tmpused :RegSet // registers used in the current instruction
// reserved spill registers
gpSpillRegs :Reg[] = []
gpSpillRegIdx :int = 0
// live and desired holds information about block's live values at the end
// of the block, and those value's desired registers (if any.)
// These are created by computeLive()
live :LiveInfo[][] = [] // indexed by block
desired :DesiredState[] = []
// startRegs[blockid] is the register state at the start of merge blocks.
// saved state does not include the state of phi ops in the block.
startRegs :StartReg[][]
// endRegs[blockid] is the register state at the end of each block.
// encoded as a set of endReg records.
endRegs :EndReg[][]
constructor(config :Config) {
const a = this
this.config = config
this.addrtype = intTypes(config.addrSize)[1]
this.addrsize = config.addrSize
// TODO provide registers as an argument
this.registers = config.registers
this.numregs = config.registers.length
if (a.numregs == 0 || a.numregs > maxregs) {
panic(`invalid number of registers: ${a.numregs}`)
}
// Locate SP, SB, and g registers.
this.SPReg = noReg
this.SBReg = noReg
this.GReg = noReg
for (let r :Reg = 0; r < a.numregs; r++) {
switch (a.registers[r].name) {
case "SP": a.SPReg = r; break
case "SB": a.SBReg = r; break
case "g": if (config.hasGReg) { a.GReg = r }; break
}
}
if (a.SPReg == noReg) { panic("no SP register found") }
if (a.SBReg == noReg) { panic("no SB register found") }
if (config.hasGReg && a.GReg == noReg) { panic("no g register found") }
// Figure out which registers we're allowed to use.
this.allocatable = config.gpRegMask.or(config.fpRegMask.or(config.specialRegMask))
// .allocatable &^= 1 << s.SPReg
// .allocatable = .allocatable & ~(1 << s.SPReg)
this.allocatable = this.allocatable.and(UInt64.ONE.shl(a.SPReg).not())
this.allocatable = this.allocatable.and(UInt64.ONE.shl(a.SBReg).not())
if (config.hasGReg) {
this.allocatable = this.allocatable.and(UInt64.ONE.shl(a.GReg).not())
}
// dlog(`allocatable:`, fmtRegSet(a.allocatable))
}
// reserveGpSpillRegs reserves count regs starting with r for spills
reserveGpSpillRegs(...regs :Reg[]) {
this.gpSpillRegs = regs
this.gpSpillRegIdx = 0
dlog(`reserved spill registers ${regs.map(r => `R${r}`).join(",")}`)
}
nextSpillReg() :Reg {
const a = this
return a.gpSpillRegs[a.gpSpillRegIdx++ % a.gpSpillRegs.length]
}
regallocFun(f :Fun) {
const a = this
a.f = f
// reset spill reg
a.gpSpillRegs.length = 0
a.gpSpillRegIdx = 0
a.sp = null
a.sb = null
assert(f.regAlloc == null, `registers already allocated for ${f}`)
f.regAlloc = new Array<Location>(f.numValues()) // TODO: fill this
// Assign stack pointer (SP) and static base pointer (SB) registers.
// Note that dead-code elimination might have removed SP, SB or both.
// However, we know that they are always in the same order (SP, SB), so
// we look at the two first values in the block.
let v1 = f.entry.values[1]
let v2 = f.entry.values[2]
if (v1) {
if (v1.op == ops.SP) {
v1.reg = a.registers[this.SPReg]
a.sp = v1
if (v2 && v2.op == ops.SB) {
v2.reg = a.registers[this.SBReg]
a.sb = v2
}
} else if (v1.op == ops.SB) {
v1.reg = a.registers[this.SBReg]
a.sb = v1
}
}
// DISABLED
// Decouple the register allocation order from the generated block order.
// This also creates an opportunity for experiments to find a better order.
// a.visitOrder = layoutOrder(f)
// if (a.config.optimize) {
// // update function block order with new layout
// f.blocks = a.visitOrder
// }
a.visitOrder = f.blocks
// DISABLED
// Compute block order. This array allows us to distinguish forward edges
// from backward edges and compute how far they go.
// let blockOrder = new Array<int>(f.numBlocks())
// for (let i = 0; i < a.visitOrder.length; i++) {
// blockOrder[a.visitOrder[i].id] = i >>> 0
// }
// s.regs = new Array<regState>(s.numRegs)
let nvals = f.numValues()
a.values = new Array<ValState>(nvals)
a.orig = new Array<Value>(nvals)
// s.copies = new Map<Value,bool>()
for (let b of a.visitOrder) {
for (let v of b.values) {
let t = v.type
let val = new ValState(v)
a.values[v.id] = val
// if (!t.isMemory() && !t.isVoid() && !t.isFlags() && !t.isTuple())
if (!t.isMemType() /*&& !t.isTupleType()*/ && !v.reg) {
val.needReg = true
val.rematerializeable = v.rematerializeable()
a.orig[v.id] = v
}
}
}
// dlog('a.values:', a.values)
// we start by computing live ranges, mapping each value definition
// to a set of values alive at the point of the definition.
a.computeLive()
dlog("\nlive values at end of each block\n" + a.fmtLive())
// printir(f)
// process.exit(0)
// debug valstate
if (DEBUG_REGALLOC) {
dlog(`\nvalstate:`)
for (let vs of a.values) {
if (vs) {
dlog(` v${vs.v.id} - ` + [
['needReg', vs.needReg],
['mindist', vs.mindist],
['maxdist', vs.maxdist],
].map(v => v.join(': ')).join(', '))
}
}
}
a.startRegs = new Array<StartReg[]>(f.numBlocks()) // TODO: populate
a.endRegs = new Array<EndReg[]>(f.numBlocks()) // TODO: populate
a.sdom = f.sdom()
// We then build an interference graph of values that interfere.
// Two values interfere if one of them is live at a definition point of
// the other.
let ig = a.buildInterferenceGraph()
// debug log state of interference graph
if (DEBUG_REGALLOC) {
let ifstr = ig.fmt()
let vizurl = (
'https://rsms.me/co/doc/chaitin/?'+
'input=ifg&enable-briggs=1&immediate=1&ifg=' +
encodeURIComponent(
ifstr.trim().split(/[\r\n]+/).map(s => s.trim()).join('\n')
).replace(/\%20/g, '+')
)
dlog(`\ninterference:\n` + ifstr + '\nView at ' + vizurl)
}
let spills = a.pickValues(ig)
// handle spilling, creating load and stores
if (spills.size > 0) {
this.handleSpills(spills)
}
}
handleSpills(spills :Set<ID>) {
const a = this
const f = a.f
a.reserveGpSpillRegs(4, 5) // XXX
dlog(`spills:`, Array.from(spills).reverse().map(id => `v${id}`).join(" "))
// make sure we have SP (stack pointer) value
if (!a.sp) {
a.sp = f.newValue(f.entry, ops.SP, a.addrtype, 0, null)
a.sp.reg = a.registers[a.SPReg]
f.entry.values.splice(1, 0, a.sp) // InitMem is always at 0
}
// map dependency => dependant
let usermap = a.buildDepMap()
// TODO: figure out how to compute spill addresses on the stack.
// A really simple approach would be to add on top of the stack, i.e.
// beyond the last address in the entire function.
let spoffs = 30 // XXX
let stacktop = a.sp
let stores = new Map<ID,{spoffs:int}>()
for (let sid of spills) {
let v = a.values[sid].v
v.comment = (v.comment ? "; " : "") + "spill"
// // Insert store code for spill operation
// //
// // First allocate a temporary spill reg to the operation for storing
// // its result.
// v.reg = a.registers[a.nextSpillReg()]
// //
// // Compute address where to store spill (SP + stack offset)
// let addr = v.b.newValue1(ops.OffPtr, t_mem, a.sp, spoffs)
// v.b.insertValueAfter(v, v.b.values.pop()!) // move from end of block to after v
// // Store v to addr. arg2=mem, aux=type
// stacktop = v.b.newValue3(ops.Store, t_mem, addr, v, stacktop, 0, v.type)
// v.b.insertValueAfter(addr, v.b.values.pop()!) // move from end of block to after v
// // increment offset to stack pointer
// spoffs += v.type.size
// stores.set(v.id, {spoffs})
// }
// for (let sid of spills) {
// let v = a.values[sid].v
let users = usermap.get(v)!
assert(users, `${v} is spilled but has no users`)
for (let user of users) {
if (user instanceof Value) {
// Load v from its spill location.
let spill = a.makeSpill(v, user.b)
dlog(`load spill for ${v} from ${spill}`)
let aidx = user.args.indexOf(v)
assert(aidx != -1)
let loadreg = user.b.newValue1NoAdd(ops.LoadReg, v.type, spill, 0, null)
user.setArg(aidx, loadreg)
} else {
dlog(`TODO user of type ${user.constructor.name}`)
}
}
}
a.placeSpills(spills)
}
placeSpills(spills :Set<ID>) {
const a = this
const f = a.f
// Start maps block IDs to the list of spills
// that go at the start of the block (but after any phis).
let start = new Map<ID,Value[]>()
// After maps value IDs to the list of spills
// that go immediately after that value ID.
let after = new Map<ID,Value[]>()
let loopnest = f.loopnest()
for (let i = 0; i < a.values.length; i++) {
let vi = a.values[i]
if (!vi) {
continue
}
let spill = vi.spill
if (!spill) {
continue
}
if (spill.b) {
// Some spills are already fully set up, like ops.Args
dlog(`spill already complete ${vi}`)
continue
}
let v = a.orig[i]! ; assert(v)
dlog(`place spill ${v}`)
// Walk down the dominator tree looking for a good place to
// put the spill of v. At the start "best" is the best place
// we have found so far.
// TODO: find a way to make this O(1) without arbitrary cutoffs.
let best = v.b
let bestArg = v
let bestDepth :int = 0
let l = loopnest.b2l[best.id]
if (l) {
bestDepth = l.depth
}
let b :Block|null = best
const maxSpillSearch = 100
for (let i = 0; i < maxSpillSearch; i++) {
// Find the child of b in the dominator tree which
// dominates all restores.
let p = b! ; assert(p)
b = null
for (let c = a.sdom.child(p); c && i < maxSpillSearch; ) {
if (a.sdom.t[c.id].entry <= vi.restoreMin && a.sdom.t[c.id].exit >= vi.restoreMax) {
// c also dominates all restores. Walk down into c.
b = c
break
}
c = a.sdom.sibling(c)
i++
}
if (!b) {
// Ran out of blocks which dominate all restores.
break
}
let depth :int = 0
let l = loopnest.b2l[b.id]
if (l) {
depth = l.depth
}
if (depth > bestDepth) {
// Don't push the spill into a deeper loop.
continue
}
// If v is in a register at the start of b, we can
// place the spill here (after the phis).
if (b.preds.length == 1) {
//for _, e := range s.endRegs[b.Preds[0].b.ID]
let endRegs = a.endRegs[b.preds[0].id]
if (endRegs) for (let e of endRegs) {
if (e.v == v) {
// Found a better spot for the spill.
best = b
bestArg = e.c
bestDepth = depth
break
}
}
} else {
// for _, e := range s.startRegs[b.ID]
let startRegs = a.startRegs[b.id]
if (startRegs) for (let e of startRegs) {
if (e.v == v) {
// Found a better spot for the spill.
best = b
bestArg = e.c
bestDepth = depth
break
}
}
}
}
}
}
// makeSpill returns a Value which represents the spilled value of v.
// b is the block in which the spill is used.
makeSpill(v :Value, b :Block) :Value {
const a = this
let vi = a.values[v.id]
if (vi.spill) {
// Final block not known - keep track of subtree where restores reside.
vi.restoreMin = Math.min(vi.restoreMin, a.sdom.t[b.id].entry)
vi.restoreMax = Math.max(vi.restoreMax, a.sdom.t[b.id].exit)
return vi.spill
}
// Make a spill for v. We don't know where we want
// to put it yet, so we leave it blockless for now.
let spill = a.f.newValueNoBlock(ops.StoreReg, v.type, 0, null)
// We also don't know what the spill's arg will be.
// Leave it argless for now.
a.setOrig(spill, v)
vi.spill = spill
vi.restoreMin = a.sdom.t[b.id].entry
vi.restoreMax = a.sdom.t[b.id].exit
return spill
}
// setOrig records that c's original value is the same as v's original value.
setOrig(c :Value, v :Value) {
const a = this
while (c.id >= a.orig.length) {
a.orig.push(null)
}
assert(!a.orig[c.id], `orig value set twice ${c} ${v}`)
a.orig[c.id] = a.orig[v.id]
}
// buildDepMap creates mappings of dependency => dependant
//
buildDepMap() :Map<Value,Set<Value|Block>> {
const a = this
let m = new Map<Value,Set<Value|Block>>()
const addDep = (dependant :Value|Block, dependency :Value) => {
// if (!spills.has(dependency.id)) { return }
let s = m.get(dependency)
if (s) {
s.add(dependant)
} else {
m.set(dependency, new Set<Value|Block>([dependant]))
}
}
for (let b of a.visitOrder) {
if (b.kind == BlockKind.If) {
// if-block branch depends on control value
assert(b.control, `if block ${b} missing control value`)
addDep(b, b.control!)
}
for (let v of b.values) {
for (let arg of v.args) {
// value v depends on argument value
addDep(v, arg)
}
}
}
// print usermap
if (DEBUG_REGALLOC) {
let mv = Array.from(m)
let dependants = mv.map(([, us]) => Array.from(us).join(", "))
let longestLeft = dependants.reduce((a, v) => Math.max(a, v.length), 0)
let spaces = " "
dlog(`depmap:\n ` +
mv.map(([v, ], i) => (
dependants[i] +
spaces.substr(0, longestLeft - dependants[i].length) +
` depends on ${v}`
)).join("\n ") + "\n"
)
}
return m
}
// pickValues assigns registers in a greedy fashion; e.g. say that some code
// could be allocated in only 4 registerd without spilling, but the arch
// has 8 available registers, this function might still make use of all
// available registers. This should have no side effects or negative impact,
// though it's good to know, would you wonder why many registers are used.
//
pickValues(ig :IntGraph) :Set<ID> {
const a = this
// {gp,fp}k is the maximum number of registers we have available for
// general-purpose and floating-point registers.
let gpk = countRegs(this.config.gpRegMask)
// let fpk = countRegs(this.config.fpRegMask)
// gpk = 4 // DEBUG XXX OVERRIDE test/dev spilling
// fpk = 4 // DEBUG XXX OVERRIDE test/dev spilling
let multiPass = true
// Stack of values
let valstack :{id:ID, edges:Set<ID>}[] = []
// Move values to stack, from interference graph
let sortedIds = ig.keys()
function sortIds() {
sortedIds.sort((a, b) => ig.degree(a) - ig.degree(b))
// dlog('sortedIds:', sortedIds.map(id =>
// `\n v${id} : ${ig.degree(id)}` ).join(''))
}
// initial sorting of IDs
sortIds()
// reserve preemptively.
// When disabled, the reserveGpSpillRegs function is called at the first
// sight of what might lead to spill during the picking phase.
// this.reserveGpSpillRegs(--gpk, --gpk)
dlog('\n---------------------------------------------------------')
// isSpilling
// During the picking phase, this is set to true if we pick n.degree >= R
// During the put-back phase, this is used to decide when to reserve
// a spill register.
let isSpilling = false
pick_loop: while (true) {
// console.log('nodes:', ig.keys().map(id =>
// `\n v${id} : ${ig.degree(id)}` ).join(''))
// try picking a node with degree < R
for (let i = 0; i < sortedIds.length; i++) {
let id = sortedIds[i]
let edges = ig.edges(id) as Set<ID>
assert(edges, `missing edge data for v${id}`)
if (edges.size < gpk) {
// dlog(`pick v${id} with degree ${edges.size} < R`)
sortedIds.splice(i, 1)
ig.remove(id)
valstack.push({ id, edges })
continue pick_loop
}
}
if (ig.length == 0) {
break // picking done
}
// we didn't find a node with degree < R.
// Optimistically pick next and continue
let id = sortedIds.shift() as ID
let edges = ig.edges(id) as Set<ID>
// dlog(`pick v${id} with degree ${edges.size} >= R (may spill)`)
ig.remove(id as ID)
valstack.push({ id, edges })
isSpilling = true
}
dlog(`picking done. isSpilling=${isSpilling}`)
dlog('valstack:', valstack.map(v => `v${v.id}`).join(' '))
// Determine if spilling is avoidable.
//
// At this point we don't know if we will need to spill, but we may need
// to as the picking phase encountered at least one case where it was
// unable to find a node with <R interference edges. However, our picking
// phase is pessimistic and the next phase, where we move nodes back into
// the interference graph, is where we know for certain if we will spill.
//
// This branch is taken only when we _might_ spill and performs a partial
// "move back" phase to determine if spilling can be avoided if we avoid
// reserving spill registers, which reduces the amount of total amount of
// registers.
//
// Thus, this branch trades compilation time for smaller code size and
// better code. It can be avoided to speed up compilation at the cost of
// more spills.
if (isSpilling) {
isSpilling = false
let reg = -1
let rallocmap = new Array<int>(sortedIds.length)
spill_check_loop: for (let i = valstack.length; i > 0;) {
let v = valstack[--i]
reg = (reg + 1) % gpk
let gpcount = gpk
while (gpcount--) {
for (let id2 of v.edges) {
let reg2 = rallocmap[id2]
if (reg2 != -1 && reg2 == reg) {
// conflict -- definitely spilling
isSpilling = true
break spill_check_loop
}
}
break // ok -- picked reg does not conflict with interfering values
}
rallocmap[v.id] = reg
}
if (!isSpilling) {
dlog(`isSpilling check was useful: avoided spill`)
} else {
dlog(`isSpilling check was not useful: no spills avoided`)
}
}
if (isSpilling) {
// Reserve spill register.
//
// We take an opportunistic approach to reserving a register for
// spills by doing it only when we _might_ spill, i.e. when picking
// results in selecting a node with interference greater than the
// number of available registers. This allows us to use all available
// registers in cases where there is no spill. However, the downside
// is that since we do not actually know for sure if picking a node
// leads to a spill later on, we can paradoxically cause spills which
// would otherwise be avoidable with the same number of registers.
//
// TODO: Consider a multi-pass approach, perhaps when config.optimize
// is set. We would trade compilation time for possibly much better
// code, but how much better remains to be tested & researched.
// this.reserveGpSpillRegs(--gpk, --gpk)
}
// Values that definitely spill (returned from this function)
let spills = new Set<ID>()
// rebuild ig by moving back values from the stack
// let reg = -1 // register number used by round-robin sparse allocation
for (let i = valstack.length; i > 0;) {
let v = valstack[--i]
// pick register
//
// Note: We always start with the first register and search from there
// for a free register. This way we can use a minimal amount of
// registers.
//
// A slightly more efficient method which instead leads to a sparse
// allocation is to memorize reg outside this loop and to advance
// the initial reg using round-robin, e.g.
// reg = (reg + 1) % gpk
//
let reg = 0
// now, often round-robin is not enough. Resolve
let gpcount = gpk
let conflict = true
reg_conflict_loop: while (gpcount--) {
for (let id2 of v.edges) {
let reg2 = a.values[id2].v.reg
if (reg2 && reg2.num == reg) {
// conflict -- interfering v${id2} already assigned r${reg}
reg = (reg + 1) % gpk
continue reg_conflict_loop
}
}
// ok -- picked reg does not conflict with interfering values
conflict = false
break
}
// if there was no assignable register, we need to spill
if (conflict) {
// dlog(`unable to find register for v${v.id}`)
reg = noReg
// access SSA value
let val = a.values[v.id]
let x = val.v
if (x.uses == 1 && x.b.control === x) {
// Optimization: single-use "spills" that are block controls
// move up to control point (end of block) if all of their
// arguments are alive at the end of the block.
// This seems to avoid a lot of spills.
let idx = x.b.values.indexOf(x)
assert(
idx != -1,
`${x} not in parent block's ${x}.b.values=${x.b.values}`
)
if (idx == x.b.values.length - 1) {
// x is already last in b
// reg = a.nextSpillReg()
} else {
let live = a.live[x.b.id] // live values at end of b
if (live) {
// check to see if all of x's args are alive at end of block
let ndead = x.args.length
livecheck: for (let arg of x.args) {
for (let e /*LiveInfo*/ of live) {
if (e.id == arg.id && --ndead == 0) {
break livecheck // all args alive
}
}
}
if (ndead == 0) {
// move value to end of block
x.b.values.splice(idx, 1)
x.b.values.push(x)
// reg = a.nextSpillReg()
}
}
}
}
if (reg == noReg) {
// spill
// rewrite value as StoreReg with the original value as arg0
spills.add(v.id)
// let y = x.clone()
// assert(a.gpSpillRegs.length > 0, `no spill registers allocated`)
// y.reg = a.registers[a.nextSpillReg()]
// x.reset(ops.StoreReg)
// x.addArg(y)
// x.b.insertValue(x, y)
// dlog(`spill ${x} -> ${y}`)
}
}
// dlog(
// `pop v${v.id}`,
// `${reg == noReg ? "spill" : a.registers[reg].name} edges:`,
// Array.from(v.edges).map(id => `v${id}`).join(" ")
// )
// add back into graph
ig.add(v.id)
for (let id2 of v.edges) {
ig.connect(v.id, id2)
}
// assign register to value
if (reg != noReg) {
let val = a.values[v.id]
assert(val.needReg, `unexpected v${v.id}.needReg=false`)
val.v.reg = a.registers[reg]
// Note: computeLive() consults a.values and only includes values
// which needReg.
} else {
assert(
!a.values[v.id].v.reg,
`spilling but reg is assigned. v${v.id}.reg != null; reg=noReg`
)
}
// print interference graph at this point
// dlog(`ig.fmt():\n` + ig.fmt())
} // for (let i = valstack.length; i > 0;)
return spills
}
buildInterferenceGraph() :IntGraph {
const a = this
const f = a.f
// Chaitin's algorithm for building the interference graph is fairly
// straight forward:
//
// for every block B in F:
// CurrLive = LiveOut(B)
// for I in B in reverse order:
// for definition D in I:
// add an interference from D to every element in ...
// ... CurrLive - {D} creating nodes if necessary
// for every definition D in I
// remove D from CurrLive
// for every use U in I
// add U to CurrLive
//
// Since our IR is in SSA form, we always have exactly one definition
// per I, so the algorithm can be described in a simpler form:
//
// for every block B in F:
// CurrLive = LiveOut(B)
// for I in B in reverse order:
// let D be the definition of I
// remove D from CurrLive
// add an interference from D to every element in CurrLive
// for every use U in I
// add U to CurrLive
//
let g = new IntGraph()
// visit blocks in reverse order
for (let i = f.blocks.length, b :Block|undefined ; b = f.blocks[--i]; ) {
// live tracks currently-live IDs
let live = new Set<ID>()
let liveout :LiveInfo[] = a.live[b.id]
if (liveout) {
for (let e of liveout) {
live.add(e.id)
}
}
// visit instructions in reverse order
for (let i = b.values.length-1; i >= 0; --i) {
let v = b.values[i]
let vinfo = a.values[v.id]
if (g.length == 0) {
// very first value.
// we know there are no live values; this is the first.
if (vinfo.needReg) {
g.add(v.id)
}
} else {
// remove definition from live set
live.delete(v.id)
// Do not create interference for Copy ops.
// `v2 = Copy v1` does not create an interference between v1 and v2
// because the two live ranges have the same value and
// therefore can occupy the same register.
if (vinfo.needReg && v.op != ops.Copy) {
// update interference graph to add an edge from the definition v
// to each other value alive at this point
for (let id2 of live) {
if (a.values[id2].needReg) {
g.connect(v.id, id2)
}
}
}
}
for (let operand of v.args) {
live.add(operand.id)
}
}
}
return g
}
// regspec returns the RegInfo for operation op
//
regspec(op :Op) :RegInfo {
// const a = this
// if (op == ops.OpConvert) {
// // OpConvert is a generic op, so it doesn't have a
// // register set in the static table. It can use any
// // allocatable integer register.
// m := s.allocatable & s.f.Config.gpRegMask
// return regInfo{inputs: []inputInfo{{regs: m}},
// outputs: []outputInfo{{regs: m}}}
// }
return opinfo[op].reg || nilRegInfo
}
// computeLive computes a map from block ID to a list of value IDs live at
// the end of that block. Together with the value ID is a count of how many
// instructions to the next use of that value.
// The resulting map is stored in this.live.
//
// computeLive also computes the desired register information at the end of
// each block. This desired register information is stored in this.desired.
//
// TODO: this could be quadratic if lots of variables are live across lots of
// basic blocks. Figure out a way to make this function (or, more precisely,
// the user of this function) require only linear size & time.
//
computeLive() {
const a = this
const f = a.f
a.live = new Array<LiveInfo[]>(f.numBlocks())
a.desired = new Array<DesiredState>(f.numBlocks())
let phis :Value[] = []
let live = new Map<ID,ValMapEntry>()
let t = new Map<ID,ValMapEntry>()
// Keep track of which value we want in each register.
let desired = new DesiredState()
// Instead of iterating over f.blocks, iterate over their postordering.
// Liveness information flows backward, so starting at the end increases
// the probability that we will stabilize quickly.
//
// TODO: Do a better job yet. Here's one possibility:
// Calculate the dominator tree and locate all strongly connected
// components. If a value is live in one block of an SCC, it is live in all.
// Walk the dominator tree from end to beginning, just once, treating SCC
// components as single blocks, duplicated calculated liveness information
// out to all of them.
//
let po = f.postorder()
// dlog('postorder blocks:', po.join(' '))
// will be set to true if f.invalidateCFG() needs to be called at the end
// let invalidateCFG = false
while (true) {
let changed = false
for (let b of po) {
// Start with known live values at the end of the block.
// Add b.values.length to adjust from end-of-block distance
// to beginning-of-block distance.
live.clear()
let liv = a.live[b.id]; // LiveInfo[] | undefined
if (liv) for (let e of liv) {
live.set(e.id, { val: e.dist + b.values.length, pos: e.pos })
}
// Mark control value as live
if (b.control && a.values[b.control.id].needReg) {
live.set(b.control.id, { val: b.values.length, pos: b.pos })
}
// dlog(`live: ` + Array.from(live).map(p =>
// `v${p[0]} - v${p[1].val}`
// ).join('\n'))
// Propagate backwards to the start of the block
// Assumes Values have been scheduled.
phis = []
for (let i = b.values.length - 1; i >= 0; i--) {
let v = b.values[i]
// definition of v -- remove from live
let x = live.get(v.id)
if (x) {
// save longest distance
a.values[v.id].maxdist = x.val
live.delete(v.id)
}
if (v.op === ops.Phi) {
// save phi ops for later
phis.push(v)
continue
}
if (opinfo[v.op].call) {
for (let v of live.values()) {
v.val += unlikelyDistance
}
}
for (let arg of v.args) {
if (a.values[arg.id].needReg) {
live.set(arg.id, { val: i, pos: v.pos })
}
}
}
// Propagate desired registers backwards
let other = a.desired[b.id]
if (other) {
desired.copy(other)
} else {
desired.clear()
}
for (let i = b.values.length - 1; i >= 0; i--) {
let v = b.values[i]
let prefs = desired.remove(v.id)
if (v.op === ops.Phi) {
// TODO: if v is a phi, save desired register for phi inputs.
// For now, we just drop it and don't propagate
// desired registers back though phi nodes.
continue
}
let regspec = a.regspec(v.op)
// Cancel desired registers if they get clobbered.
desired.clobber(regspec.clobbers)
// Update desired registers if there are any fixed register inputs.
for (let j of regspec.inputs) {
if (countRegs(j.regs) != 1) {
continue
}
desired.clobber(j.regs)
desired.add(v.args[j.idx].id, pickReg(j.regs))
}
// Set desired register of input 0 if this is a 2-operand instruction.
if (opinfo[v.op].resultInArg0) {
if (opinfo[v.op].commutative) {
desired.addList(v.args[1].id, prefs)
}
desired.addList(v.args[0].id, prefs)
}
}
// dlog(`${b} desired: ${desired}`)
// For each predecessor of b, expand its list of live-at-end values.
// invariant: live contains the values live at the start of b
// (excluding phi inputs)
for (let i = 0; i < b.preds.length; i++) {
let p = b.preds[i]
// Compute additional distance for the edge.
// Note: delta must be at least 1 to distinguish the control
// value use from the first user in a successor block.
let delta = normalDistance
if (p.succs.length == 2) {
if (
p.succs[0] == b && p.likely == BranchPrediction.Likely ||
p.succs[1] == b && p.likely == BranchPrediction.Unlikely
) {
delta = likelyDistance
} else if (
p.succs[0] == b && p.likely == BranchPrediction.Unlikely ||
p.succs[1] == b && p.likely == BranchPrediction.Likely
) {
delta = unlikelyDistance
}
}
// Update any desired registers at the end of p.
let pdesired = a.desired[p.id]
if (!pdesired) {
a.desired[p.id] = new DesiredState(desired)
} else {
pdesired.merge(desired)
}
// Start t off with the previously known live values at the end of p.
t.clear()
let plive = a.live[p.id]
if (plive) for (let e of plive) {
t.set(e.id, { val: e.dist, pos: e.pos })
}
let update = false
// Add new live values from scanning this block.
for (let [key, e] of live) {
let d = e.val + delta
let e2 = t.get(key)
if (!e2 || d < e2.val) {
update = true
t.set(key, { val: d, pos: e.pos })
}
}
// Also add the correct arg from the saved phi values.
// All phis are at distance delta (we consider them
// simultaneously happening at the start of the block).
for (let v of phis) {
let id = v.args[i].id
if (a.values[id].needReg) {
let e2 = t.get(id)
if (!e2 || delta < e2.val) {
update = true
t.set(id, { val: delta, pos: v.pos })
}
}
}
if (!update) {
continue
}
// The live set has changed, update it.
let l :LiveInfo[] = new Array<LiveInfo>(t.size), j = 0
for (let [key, e] of t) {
l[j++] = { id: key, dist: e.val, pos: e.pos }
}
a.live[p.id] = l
changed = true
}
}
if (!changed) {
break
}
// break
}
// if (invalidateCFG) {
// f.invalidateCFG()
// }
} // computeLive
fmtLive() :string {
const a = this
let s = ''
for (let b of a.f.blocks) {
s += ` ${b}:`
let blive = a.live[b.id]
if (blive) for (let x of blive) {
// s += ` v${x.id} (${x.dist})`
s += ` v${x.id}`
let desired = a.desired[b.id]
if (desired) for (let e of desired.entries) {
if (e.id != x.id) {
continue
}
s += "["
let first = true
for (let r of e.regs) {
if (r == noReg) {
continue
}
if (!first) {
s += ","
}
let reg = a.registers[r]
s += `${reg.name}#${reg.num}`
first = false
}
s += "]"
}
}
if (a.desired[b.id]) {
let avoid = a.desired[b.id].avoid
if (!avoid.isZero()) {
s += " avoid=" + fmtRegSet(avoid)
}
}
s += "\n"
}
return s.trimRight()
}
// _usermapCache :Map<Value,Set<Value|Block>>|null = null
// getUserMap() {
// const a = this
// if (a._usermapCache) {
// return a._usermapCache
// }
// let usermap = new Map<Value,Set<Value|Block>>()
// for (let b of a.visitOrder) {
// if (b.control) {
// let s = usermap.get(b.control)
// if (s) {
// s.add(b)
// } else {
// usermap.set(b.control, new Set<Value|Block>([b]))
// }
// }
// for (let v of b.values) {
// for (let arg of v.args) {
// let s = usermap.get(arg)
// if (s) {
// s.add(v)
// } else {
// usermap.set(arg, new Set<Value|Block>([v]))
// }
// }
// }
// }
// a._usermapCache = usermap
// return usermap
// }
} | the_stack |
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { HttpMethods, QueryConfig, ResponseBody, ResponseText } from 'redux-query';
import * as runtime from '../runtime';
import {
User,
UserFromJSON,
UserToJSON,
} from '../models';
export interface CreateUserRequest {
body: User;
}
export interface CreateUsersWithArrayInputRequest {
body: Array<User>;
}
export interface CreateUsersWithListInputRequest {
body: Array<User>;
}
export interface DeleteUserRequest {
username: string;
}
export interface GetUserByNameRequest {
username: string;
}
export interface LoginUserRequest {
username: string;
password: string;
}
export interface UpdateUserRequest {
username: string;
body: User;
}
/**
* This can only be done by the logged in user.
* Create user
*/
function createUserRaw<T>(requestParameters: CreateUserRequest, requestConfig: runtime.TypedQueryConfig<T, void> = {}): QueryConfig<T> {
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.');
}
let queryParameters = null;
const headerParameters : runtime.HttpHeaders = {};
headerParameters['Content-Type'] = 'application/json';
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user`,
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'POST',
headers: headerParameters,
},
body: queryParameters || UserToJSON(requestParameters.body),
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
}
return config;
}
/**
* This can only be done by the logged in user.
* Create user
*/
export function createUser<T>(requestParameters: CreateUserRequest, requestConfig?: runtime.TypedQueryConfig<T, void>): QueryConfig<T> {
return createUserRaw(requestParameters, requestConfig);
}
/**
* Creates list of users with given input array
*/
function createUsersWithArrayInputRaw<T>(requestParameters: CreateUsersWithArrayInputRequest, requestConfig: runtime.TypedQueryConfig<T, void> = {}): QueryConfig<T> {
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.');
}
let queryParameters = null;
const headerParameters : runtime.HttpHeaders = {};
headerParameters['Content-Type'] = 'application/json';
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user/createWithArray`,
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'POST',
headers: headerParameters,
},
body: queryParameters || requestParameters.body?.map(UserToJSON),
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
}
return config;
}
/**
* Creates list of users with given input array
*/
export function createUsersWithArrayInput<T>(requestParameters: CreateUsersWithArrayInputRequest, requestConfig?: runtime.TypedQueryConfig<T, void>): QueryConfig<T> {
return createUsersWithArrayInputRaw(requestParameters, requestConfig);
}
/**
* Creates list of users with given input array
*/
function createUsersWithListInputRaw<T>(requestParameters: CreateUsersWithListInputRequest, requestConfig: runtime.TypedQueryConfig<T, void> = {}): QueryConfig<T> {
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.');
}
let queryParameters = null;
const headerParameters : runtime.HttpHeaders = {};
headerParameters['Content-Type'] = 'application/json';
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user/createWithList`,
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'POST',
headers: headerParameters,
},
body: queryParameters || requestParameters.body?.map(UserToJSON),
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
}
return config;
}
/**
* Creates list of users with given input array
*/
export function createUsersWithListInput<T>(requestParameters: CreateUsersWithListInputRequest, requestConfig?: runtime.TypedQueryConfig<T, void>): QueryConfig<T> {
return createUsersWithListInputRaw(requestParameters, requestConfig);
}
/**
* This can only be done by the logged in user.
* Delete user
*/
function deleteUserRaw<T>(requestParameters: DeleteUserRequest, requestConfig: runtime.TypedQueryConfig<T, void> = {}): QueryConfig<T> {
if (requestParameters.username === null || requestParameters.username === undefined) {
throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.');
}
let queryParameters = null;
const headerParameters : runtime.HttpHeaders = {};
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))),
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'DELETE',
headers: headerParameters,
},
body: queryParameters,
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
}
return config;
}
/**
* This can only be done by the logged in user.
* Delete user
*/
export function deleteUser<T>(requestParameters: DeleteUserRequest, requestConfig?: runtime.TypedQueryConfig<T, void>): QueryConfig<T> {
return deleteUserRaw(requestParameters, requestConfig);
}
/**
* Get user by user name
*/
function getUserByNameRaw<T>(requestParameters: GetUserByNameRequest, requestConfig: runtime.TypedQueryConfig<T, User> = {}): QueryConfig<T> {
if (requestParameters.username === null || requestParameters.username === undefined) {
throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.');
}
let queryParameters = null;
const headerParameters : runtime.HttpHeaders = {};
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))),
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'GET',
headers: headerParameters,
},
body: queryParameters,
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
config.transform = (body: ResponseBody, text: ResponseBody) => requestTransform(UserFromJSON(body), text);
}
return config;
}
/**
* Get user by user name
*/
export function getUserByName<T>(requestParameters: GetUserByNameRequest, requestConfig?: runtime.TypedQueryConfig<T, User>): QueryConfig<T> {
return getUserByNameRaw(requestParameters, requestConfig);
}
/**
* Logs user into the system
*/
function loginUserRaw<T>(requestParameters: LoginUserRequest, requestConfig: runtime.TypedQueryConfig<T, string> = {}): QueryConfig<T> {
if (requestParameters.username === null || requestParameters.username === undefined) {
throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.');
}
if (requestParameters.password === null || requestParameters.password === undefined) {
throw new runtime.RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.');
}
let queryParameters = null;
queryParameters = {};
if (requestParameters.username !== undefined) {
queryParameters['username'] = requestParameters.username;
}
if (requestParameters.password !== undefined) {
queryParameters['password'] = requestParameters.password;
}
const headerParameters : runtime.HttpHeaders = {};
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user/login`,
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'GET',
headers: headerParameters,
},
body: queryParameters,
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
throw "OH NO";
}
return config;
}
/**
* Logs user into the system
*/
export function loginUser<T>(requestParameters: LoginUserRequest, requestConfig?: runtime.TypedQueryConfig<T, string>): QueryConfig<T> {
return loginUserRaw(requestParameters, requestConfig);
}
/**
* Logs out current logged in user session
*/
function logoutUserRaw<T>( requestConfig: runtime.TypedQueryConfig<T, void> = {}): QueryConfig<T> {
let queryParameters = null;
const headerParameters : runtime.HttpHeaders = {};
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user/logout`,
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'GET',
headers: headerParameters,
},
body: queryParameters,
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
}
return config;
}
/**
* Logs out current logged in user session
*/
export function logoutUser<T>( requestConfig?: runtime.TypedQueryConfig<T, void>): QueryConfig<T> {
return logoutUserRaw( requestConfig);
}
/**
* This can only be done by the logged in user.
* Updated user
*/
function updateUserRaw<T>(requestParameters: UpdateUserRequest, requestConfig: runtime.TypedQueryConfig<T, void> = {}): QueryConfig<T> {
if (requestParameters.username === null || requestParameters.username === undefined) {
throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.');
}
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.');
}
let queryParameters = null;
const headerParameters : runtime.HttpHeaders = {};
headerParameters['Content-Type'] = 'application/json';
const { meta = {} } = requestConfig;
const config: QueryConfig<T> = {
url: `${runtime.Configuration.basePath}/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))),
meta,
update: requestConfig.update,
queryKey: requestConfig.queryKey,
optimisticUpdate: requestConfig.optimisticUpdate,
force: requestConfig.force,
rollback: requestConfig.rollback,
options: {
method: 'PUT',
headers: headerParameters,
},
body: queryParameters || UserToJSON(requestParameters.body),
};
const { transform: requestTransform } = requestConfig;
if (requestTransform) {
}
return config;
}
/**
* This can only be done by the logged in user.
* Updated user
*/
export function updateUser<T>(requestParameters: UpdateUserRequest, requestConfig?: runtime.TypedQueryConfig<T, void>): QueryConfig<T> {
return updateUserRaw(requestParameters, requestConfig);
} | the_stack |
import { expect } from 'chai';
import * as chokidar from 'chokidar';
import { promises as fs } from 'fs';
import * as _ from 'lodash';
import * as path from 'path';
import { promisify } from 'util';
import { LivepushManager } from '../../../lib/utils/device/live';
import { resetDockerignoreCache } from '../../docker-build';
import { setupDockerignoreTestData } from '../../projects';
const delay = promisify(setTimeout);
const FS_WATCH_DURATION_MS = 500;
const repoPath = path.normalize(path.join(__dirname, '..', '..', '..'));
const projectsPath = path.join(repoPath, 'tests', 'test-data', 'projects');
interface ByService<T> {
[serviceName: string]: T;
}
class MockLivepushManager extends LivepushManager {
public constructor() {
super({
buildContext: '',
composition: { version: '2.1', services: {} },
buildTasks: [],
docker: {} as import('dockerode'),
api: {} as import('../../../lib/utils/device/api').DeviceAPI,
logger: {} as import('../../../lib/utils/logger'),
buildLogs: {},
deployOpts:
{} as import('../../../lib/utils/device/deploy').DeviceDeployOptions,
});
}
public testSetupFilesystemWatcher(
serviceName: string,
rootContext: string,
serviceContext: string,
changedPathHandler: (serviceName: string, changedPath: string) => void,
dockerignoreByService: ByService<import('@balena/dockerignore').Ignore>,
multiDockerignore: boolean,
): import('chokidar').FSWatcher {
return super.setupFilesystemWatcher(
serviceName,
rootContext,
serviceContext,
changedPathHandler,
dockerignoreByService,
multiDockerignore,
);
}
}
// "describeSS" stands for "describe Skip Standalone"
const describeSS =
process.env.BALENA_CLI_TEST_TYPE === 'standalone' ? describe.skip : describe;
describeSS('LivepushManager::setupFilesystemWatcher', function () {
const manager = new MockLivepushManager();
async function createMonitors(
projectPath: string,
composition: import('resin-compose-parse').Composition,
multiDockerignore: boolean,
changedPathHandler: (serviceName: string, changedPath: string) => void,
): Promise<ByService<chokidar.FSWatcher>> {
const { getServiceDirsFromComposition } = await import(
'../../../build/utils/compose_ts'
);
const { getDockerignoreByService } = await import(
'../../../build/utils/ignore'
);
const rootContext = path.resolve(projectPath);
const monitors: ByService<chokidar.FSWatcher> = {};
const serviceDirsByService = await getServiceDirsFromComposition(
projectPath,
composition,
);
const dockerignoreByService = await getDockerignoreByService(
projectPath,
multiDockerignore,
serviceDirsByService,
);
for (const serviceName of Object.keys(composition.services)) {
const service = composition.services[serviceName];
const serviceContext = path.resolve(rootContext, service.build!.context);
const monitor = manager.testSetupFilesystemWatcher(
serviceName,
rootContext,
serviceContext,
changedPathHandler,
dockerignoreByService,
multiDockerignore,
);
monitors[serviceName] = monitor;
await new Promise((resolve, reject) => {
monitor.on('error', reject);
monitor.on('ready', resolve);
});
}
return monitors;
}
this.beforeAll(async () => {
await setupDockerignoreTestData();
});
this.afterAll(async () => {
await setupDockerignoreTestData({ cleanup: true });
});
this.beforeEach(() => {
resetDockerignoreCache();
});
describe('for project no-docker-compose/basic', function () {
const projectPath = path.join(projectsPath, 'no-docker-compose', 'basic');
const composition = {
version: '2.1',
services: {
main: { build: { context: '.' } },
},
};
it('should trigger change events for paths that are not ignored', async () => {
const changedPaths: ByService<string[]> = { main: [] };
const multiDockerignore = true;
const monitors = await createMonitors(
projectPath,
composition,
multiDockerignore,
(serviceName: string, changedPath: string) => {
changedPaths[serviceName].push(changedPath);
},
);
await Promise.all([
touch(path.join(projectPath, 'Dockerfile')),
touch(path.join(projectPath, 'src', 'start.sh')),
touch(path.join(projectPath, 'src', 'windows-crlf.sh')),
]);
// wait a bit so that filesystem modifications are notified
await delay(FS_WATCH_DURATION_MS);
await Promise.all(
Object.values(monitors).map((monitor) => monitor.close()),
);
expect(changedPaths['main']).to.have.members([
'Dockerfile',
path.join('src', 'start.sh'),
path.join('src', 'windows-crlf.sh'),
]);
});
});
describe('for project no-docker-compose/dockerignore1', function () {
const projectPath = path.join(
projectsPath,
'no-docker-compose',
'dockerignore1',
);
const composition = {
version: '2.1',
services: {
main: { build: { context: '.' } },
},
};
it('should trigger change events for paths that are not ignored', async () => {
const changedPaths: ByService<string[]> = { main: [] };
const multiDockerignore = true;
const monitors = await createMonitors(
projectPath,
composition,
multiDockerignore,
(serviceName: string, changedPath: string) => {
changedPaths[serviceName].push(changedPath);
},
);
await Promise.all([
touch(path.join(projectPath, 'a.txt')),
touch(path.join(projectPath, 'b.txt')),
touch(path.join(projectPath, 'vendor', '.git', 'vendor-git-contents')),
touch(path.join(projectPath, 'src', 'src-a.txt')),
touch(path.join(projectPath, 'src', 'src-b.txt')),
]);
// wait a bit so that filesystem modifications are notified
await delay(FS_WATCH_DURATION_MS);
await Promise.all(
Object.values(monitors).map((monitor) => monitor.close()),
);
expect(changedPaths['main']).to.have.members([
'a.txt',
path.join('src', 'src-a.txt'),
path.join('vendor', '.git', 'vendor-git-contents'),
]);
});
});
describe('for project no-docker-compose/dockerignore2', function () {
const projectPath = path.join(
projectsPath,
'no-docker-compose',
'dockerignore2',
);
const composition = {
version: '2.1',
services: {
main: { build: { context: '.' } },
},
};
it('should trigger change events for paths that are not ignored', async () => {
const changedPaths: ByService<string[]> = { main: [] };
const multiDockerignore = true;
const monitors = await createMonitors(
projectPath,
composition,
multiDockerignore,
(serviceName: string, changedPath: string) => {
changedPaths[serviceName].push(changedPath);
},
);
await Promise.all([
touch(path.join(projectPath, 'a.txt')),
touch(path.join(projectPath, 'b.txt')),
touch(path.join(projectPath, 'lib', 'src-a.txt')),
touch(path.join(projectPath, 'lib', 'src-b.txt')),
touch(path.join(projectPath, 'src', 'src-a.txt')),
touch(path.join(projectPath, 'src', 'src-b.txt')),
touch(path.join(projectPath, 'symlink-a.txt')),
touch(path.join(projectPath, 'symlink-b.txt')),
]);
// wait a bit so that filesystem modifications are notified
await delay(FS_WATCH_DURATION_MS);
await Promise.all(
Object.values(monitors).map((monitor) => monitor.close()),
);
// chokidar appears to treat symbolic links differently on different
// platforms like Linux and macOS. On Linux only, change events are
// reported for symlinks when the target file they point to is changed.
// We tolerate this difference in this test case.
const expectedNoSymlink = [
'b.txt',
path.join('lib', 'src-b.txt'),
path.join('src', 'src-b.txt'),
];
const expectedWithSymlink = [...expectedNoSymlink, 'symlink-a.txt'];
expect(changedPaths['main']).to.include.members(expectedNoSymlink);
expect(expectedWithSymlink).to.include.members(changedPaths['main']);
});
});
describe('for project docker-compose/basic', function () {
const projectPath = path.join(projectsPath, 'docker-compose', 'basic');
const composition = {
version: '2.1',
services: {
service1: { build: { context: 'service1' } },
service2: { build: { context: 'service2' } },
},
};
it('should trigger change events for paths that are not ignored (docker-compose)', async () => {
const changedPaths: ByService<string[]> = {
service1: [],
service2: [],
};
const multiDockerignore = false;
const monitors = await createMonitors(
projectPath,
composition,
multiDockerignore,
(serviceName: string, changedPath: string) => {
changedPaths[serviceName].push(changedPath);
},
);
await Promise.all([
touch(path.join(projectPath, 'service1', 'test-ignore.txt')),
touch(path.join(projectPath, 'service1', 'file1.sh')),
touch(path.join(projectPath, 'service2', 'src', 'file1.sh')),
touch(path.join(projectPath, 'service2', 'file2-crlf.sh')),
]);
// wait a bit so that filesystem modifications are notified
await delay(FS_WATCH_DURATION_MS);
await Promise.all(
Object.values(monitors).map((monitor) => monitor.close()),
);
expect(changedPaths['service1']).to.have.members(['file1.sh']);
expect(changedPaths['service2']).to.have.members([
path.join('src', 'file1.sh'),
'file2-crlf.sh',
]);
});
it('should trigger change events for paths that are not ignored (docker-compose, multi-dockerignore)', async () => {
const changedPaths: ByService<string[]> = {
service1: [],
service2: [],
};
const multiDockerignore = true;
const monitors = await createMonitors(
projectPath,
composition,
multiDockerignore,
(serviceName: string, changedPath: string) => {
changedPaths[serviceName].push(changedPath);
},
);
await Promise.all([
touch(path.join(projectPath, 'service1', 'test-ignore.txt')),
touch(path.join(projectPath, 'service1', 'file1.sh')),
touch(path.join(projectPath, 'service2', 'src', 'file1.sh')),
touch(path.join(projectPath, 'service2', 'file2-crlf.sh')),
]);
// wait a bit so that filesystem modifications are notified
await delay(FS_WATCH_DURATION_MS);
await Promise.all(
Object.values(monitors).map((monitor) => monitor.close()),
);
expect(changedPaths['service1']).to.have.members([
'file1.sh',
'test-ignore.txt',
]);
expect(changedPaths['service2']).to.have.members(['file2-crlf.sh']);
});
});
});
async function touch(filePath: string) {
const time = new Date();
return fs.utimes(filePath, time, time);
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [dataexchange](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdataexchange.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Dataexchange extends PolicyStatement {
public servicePrefix = 'dataexchange';
/**
* Statement provider for service [dataexchange](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdataexchange.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);
}
/**
* Grants permissions to cancel a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-jobs.html#CancelJob
*/
public toCancelJob() {
return this.to('CancelJob');
}
/**
* Grants permission to create an asset (for example, in a Job)
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions.html#CreateAsset
*/
public toCreateAsset() {
return this.to('CreateAsset');
}
/**
* Grants permission to create a data set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets.html#CreateDataSet
*/
public toCreateDataSet() {
return this.to('CreateDataSet');
}
/**
* Grants permission to create an event action
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/api-permissions-ref.html
*/
public toCreateEventAction() {
return this.to('CreateEventAction');
}
/**
* Grants permissions to create a job to import or export assets
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-jobs.html#CreateJob
*/
public toCreateJob() {
return this.to('CreateJob');
}
/**
* Grants permission to create a revision
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions.html#CreateRevision
*/
public toCreateRevision() {
return this.to('CreateRevision');
}
/**
* Grants permissions to delete an asset
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions-revisionid-assets-assetid.html#DeleteAsset
*/
public toDeleteAsset() {
return this.to('DeleteAsset');
}
/**
* Grants permissions to delete a data set
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid.html#DeleteDataSet
*/
public toDeleteDataSet() {
return this.to('DeleteDataSet');
}
/**
* Grants permission to delete an event action
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/api-permissions-ref.html
*/
public toDeleteEventAction() {
return this.to('DeleteEventAction');
}
/**
* Grants permissions to delete a revision
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions-revisionid.html#DeleteRevision
*/
public toDeleteRevision() {
return this.to('DeleteRevision');
}
/**
* Grants permissions to get information about an asset and to export it (for example, in a Job)
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions-revisionid-assets-assetid.html#GetAsset
*/
public toGetAsset() {
return this.to('GetAsset');
}
/**
* Grants permission to get information about a data set
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid.html#GetDataSet
*/
public toGetDataSet() {
return this.to('GetDataSet');
}
/**
* Grants permission to get an event action
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/api-permissions-ref.html
*/
public toGetEventAction() {
return this.to('GetEventAction');
}
/**
* Grants permissions to get information about a job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-jobs.html#GetJob
*/
public toGetJob() {
return this.to('GetJob');
}
/**
* Grants permission to get information about a revision
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions-revisionid.html#GetRevision
*/
public toGetRevision() {
return this.to('GetRevision');
}
/**
* Grants permissions to list the revisions of a data set
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions.html#ListDataSetRevisions
*/
public toListDataSetRevisions() {
return this.to('ListDataSetRevisions');
}
/**
* Grants permission to list data sets for the account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets.html#ListDataSets
*/
public toListDataSets() {
return this.to('ListDataSets');
}
/**
* Grants permission to list event actions for the account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/api-permissions-ref.html
*/
public toListEventActions() {
return this.to('ListEventActions');
}
/**
* Grants permissions to list jobs for the account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-jobs.html#ListJobs
*/
public toListJobs() {
return this.to('ListJobs');
}
/**
* Grants permissions to get list the assets of a revision
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions-revisionid-assets.html#ListRevisionAssets
*/
public toListRevisionAssets() {
return this.to('ListRevisionAssets');
}
/**
* Grants permission to list the tags that you associated with the specified resource.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/tags-resource-arn.html#ListTagsForResource
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to publish a data set
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/api-permissions-ref.html
*/
public toPublishDataSet() {
return this.to('PublishDataSet');
}
/**
* Grants permissions to start a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-jobs.html#StartJob
*/
public toStartJob() {
return this.to('StartJob');
}
/**
* Grants permission to add one or more tags to a specified resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/tags-resource-arn.html#TagResource
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove one or more tags from a specified resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/tags-resource-arn.html#UntagResource
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permissions to get update information about an asset
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions-revisionid-assets-assetid.html#UpdateAsset
*/
public toUpdateAsset() {
return this.to('UpdateAsset');
}
/**
* Grants permissions to update information about a data set
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid.html#UpdateDataSet
*/
public toUpdateDataSet() {
return this.to('UpdateDataSet');
}
/**
* Grants permission to update information for an event action
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/api-permissions-ref.html
*/
public toUpdateEventAction() {
return this.to('UpdateEventAction');
}
/**
* Grants permissions to update information about a revision
*
* Access Level: Write
*
* https://docs.aws.amazon.com/data-exchange/latest/apireference/v1-data-sets-datasetid-revisions-revisionid.html#UpdateRevision
*/
public toUpdateRevision() {
return this.to('UpdateRevision');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CancelJob",
"CreateAsset",
"CreateDataSet",
"CreateEventAction",
"CreateJob",
"CreateRevision",
"DeleteAsset",
"DeleteDataSet",
"DeleteEventAction",
"DeleteRevision",
"PublishDataSet",
"StartJob",
"UpdateAsset",
"UpdateDataSet",
"UpdateEventAction",
"UpdateRevision"
],
"Read": [
"GetAsset",
"GetDataSet",
"GetEventAction",
"GetJob",
"GetRevision",
"ListDataSetRevisions",
"ListDataSets",
"ListEventActions",
"ListJobs",
"ListRevisionAssets",
"ListTagsForResource"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type jobs to the statement
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/jobs.html
*
* @param jobId - Identifier for the jobId.
* @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:
* - .ifJobType()
*/
public onJobs(jobId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:dataexchange:${Region}:${Account}:jobs/${JobId}';
arn = arn.replace('${JobId}', jobId);
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 data-sets to the statement
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/data-sets.html
*
* @param dataSetId - Identifier for the dataSetId.
* @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`.
*/
public onDataSets(dataSetId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:dataexchange:${Region}:${Account}:data-sets/${DataSetId}';
arn = arn.replace('${DataSetId}', dataSetId);
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 revisions to the statement
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/data-sets.html#revisions
*
* @param dataSetId - Identifier for the dataSetId.
* @param revisionId - Identifier for the revisionId.
* @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`.
*/
public onRevisions(dataSetId: string, revisionId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:dataexchange:${Region}:${Account}:data-sets/${DataSetId}/revisions/${RevisionId}';
arn = arn.replace('${DataSetId}', dataSetId);
arn = arn.replace('${RevisionId}', revisionId);
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 assets to the statement
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/data-sets.html#assets
*
* @param dataSetId - Identifier for the dataSetId.
* @param revisionId - Identifier for the revisionId.
* @param assetId - Identifier for the assetId.
* @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`.
*/
public onAssets(dataSetId: string, revisionId: string, assetId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:dataexchange:${Region}:${Account}:data-sets/${DataSetId}/revisions/${RevisionId}/assets/${AssetId}';
arn = arn.replace('${DataSetId}', dataSetId);
arn = arn.replace('${RevisionId}', revisionId);
arn = arn.replace('${AssetId}', assetId);
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 event-actions to the statement
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/data-sets.html
*
* @param eventActionId - Identifier for the eventActionId.
* @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`.
*/
public onEventActions(eventActionId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:dataexchange:${Region}:${Account}:event-actions/${EventActionId}';
arn = arn.replace('${EventActionId}', eventActionId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by the specified job type
*
* https://docs.aws.amazon.com/data-exchange/latest/userguide/access-control.html
*
* Applies to resource types:
* - jobs
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifJobType(value: string | string[], operator?: Operator | string) {
return this.if(`JobType`, value, operator || 'StringLike');
}
} | the_stack |
import React, { useState, useEffect, useRef, ReactNode } from 'react'
import { applyDragForce, applyBoundForce } from './force'
import getBoundaries from './getBoundaries'
import { roundNum, isMouseEvent } from './utils'
type draggerRefParams = {
setPosition: (position: number, instant: boolean) => void
outerWidth: number
innerWidth: number
}
export type OnFrameType = {
x: number
outerWidth: number
innerWidth: number
progress: number
}
type TProps = {
friction?: number
disabled?: boolean
setCursorStyles?: boolean
draggerRef?: (args: draggerRefParams) => void
onFrame?: (args: OnFrameType) => void
onStaticClick?: (e: EventTarget) => void
onDown?: () => void
onUp?: () => void
style?: React.CSSProperties
innerStyle?: React.CSSProperties
className?: string
children: ReactNode
ResizeObserverPolyfill?: Function
}
export default function Dragger({
friction = 0.95,
disabled = false,
setCursorStyles = true,
onFrame,
onUp,
onDown,
onStaticClick,
draggerRef,
style,
innerStyle,
className,
children,
ResizeObserverPolyfill,
}: TProps) {
// DOM element refs
const outerEl = useRef<HTMLDivElement>(null)
const innerEl = useRef<HTMLDivElement>(null)
// Dimensions
const outerWidth = useRef(0)
const innerWidth = useRef(0)
const leftBound = useRef(0)
const rightBound = useRef(0)
// User input states
const isDragging = useRef(false) // doesn't update render
const [isDraggingStyle, setIsDraggingStyle] = useState(false) // does update render
// Dragging state
const restPositionX = useRef(0)
const velocityX = useRef(0)
const downX = useRef(0)
const dragStartPosition = useRef(0)
const nativePosition = useRef(0) // starting position
const dragPosition = useRef(nativePosition.current)
const rafId = useRef<number | null>(null)
const docStyle = typeof window !== 'undefined' ? document.documentElement.style : { cursor: '', userSelect: '' }
const mouseCursorStyle = setCursorStyles && isDraggingStyle ? 'grabbing' : setCursorStyles ? 'grab' : undefined
// componentDidMount
useEffect(() => {
outerWidth.current = outerEl.current!.scrollWidth
innerWidth.current = innerEl.current!.scrollWidth
const { left, right } = getBoundaries({
outerWidth: outerWidth.current,
innerWidth: innerWidth.current,
elClientLeft: (outerEl.current && outerEl.current.clientLeft) || 0
})
leftBound.current = left
rightBound.current = right
// Update the edge boundaries when the outer element is resized
// Update the inner width when the children change size
// Check if ResizeObserver is available on the window, and if no polyfill is supplied by the user via props
if (!(window as any).ResizeObserver && !ResizeObserverPolyfill) {
throw new Error('No ResizeObserver is available. Please check the docs for instructions on how to add a polyfill.')
}
const Ro = (window as any).ResizeObserver || ResizeObserverPolyfill
// address the 'any' typing of entries
const observer = new Ro((entries: any[]) => {
// use the elements data-id to determine whether the inner or the outer has been observed
const id = entries[0].target.dataset.id
if (id === 'dragger-inner') innerWidth.current = entries[0].contentRect.width
if (id === 'dragger-outer') outerWidth.current = entries[0].contentRect.width
const { left, right }: { left: number; right: number } = getBoundaries({
outerWidth: outerWidth.current,
innerWidth: innerWidth.current,
elClientLeft: (outerEl.current && outerEl.current.clientLeft) || 0,
})
leftBound.current = left
rightBound.current = right
// broadcast onFrame event on component mount, as well as when the inner or outer elements change size
if (onFrame) {
onFrame({
x: roundNum(nativePosition.current),
outerWidth: outerWidth.current,
innerWidth: innerWidth.current,
progress: roundNum(nativePosition.current / (outerWidth.current - innerWidth.current)),
})
}
// if a draggerRef has been provided, broadcast changes to it as well
// and make the setPosition function available
if (draggerRef) {
draggerRef({
setPosition,
outerWidth: outerWidth.current,
innerWidth: innerWidth.current,
})
}
})
observer.observe(outerEl.current)
observer.observe(innerEl.current)
return () => {
observer.disconnect()
}
}, [])
// setPosition is exposed via ref
function setPosition(position: number, instant: boolean) {
if (disabled) return
const finalPosition = Math.min(Math.max(leftBound.current, position), rightBound.current)
// jump instantly to position, without animation
if (instant) {
window.cancelAnimationFrame(rafId.current!) // cancel any existing loop
if (innerEl.current) {
nativePosition.current = finalPosition
restPositionX.current = finalPosition
innerEl.current.style.transform = `translate3d(${roundNum(finalPosition)}px,0,0)`
if (onFrame) {
onFrame({
x: roundNum(nativePosition.current),
outerWidth: outerWidth.current,
innerWidth: innerWidth.current,
progress: roundNum(nativePosition.current / (outerWidth.current - innerWidth.current))
})
}
}
} else {
window.cancelAnimationFrame(rafId.current!) // cancel any existing loop
rafId.current = window.requestAnimationFrame(() => updateLoop(finalPosition)) // kick off a new loop
}
}
function updateLoop(optionalFinalPosition: null | number) {
// bail out of the loop if the component has been unmounted
if (!outerEl.current) {
window.cancelAnimationFrame(rafId.current!)
return
}
velocityX.current *= friction // apply friction to velocity, therefore slowing it down
// if a number is provided as a param (optionalFinalPosition), move to that position
if (optionalFinalPosition !== null) {
const distance = optionalFinalPosition - nativePosition.current
const force = distance * (1 - friction) - velocityX.current
velocityX.current = velocityX.current + force // apply force
} else {
if (!isDragging.current && nativePosition.current < leftBound.current) {
velocityX.current = applyBoundForce({
bound: leftBound.current,
edge: 'left',
nativePosition: nativePosition.current,
friction: friction,
velocityX: velocityX.current,
})
}
if (!isDragging.current && nativePosition.current > rightBound.current) {
velocityX.current = applyBoundForce({
bound: rightBound.current,
edge: 'right',
nativePosition: nativePosition.current,
friction: friction,
velocityX: velocityX.current,
})
}
}
velocityX.current = applyDragForce({
isDragging: isDragging.current,
dragPosition: dragPosition.current,
nativePosition: nativePosition.current,
velocityX: velocityX.current,
})
nativePosition.current += velocityX.current
const isInfinitesimal: boolean = roundNum(Math.abs(velocityX.current)) < 0.001
if (!isDragging.current && isInfinitesimal) {
// no longer dragging and inertia has stopped
window.cancelAnimationFrame(rafId.current!)
restPositionX.current = roundNum(nativePosition.current)
} else {
// bypass Reacts render method during animation, similar to react-spring
if (innerEl.current) {
innerEl.current.style.transform = `translate3d(${roundNum(nativePosition.current)}px,0,0)`
rafId.current = window.requestAnimationFrame(() => updateLoop(null))
}
}
// optional callback function prop
if (onFrame) {
onFrame({
x: roundNum(nativePosition.current),
outerWidth: outerWidth.current,
innerWidth: innerWidth.current,
progress: roundNum(nativePosition.current / (outerWidth.current - innerWidth.current))
})
}
}
function onMouseMove(e: any) {
const x = e.pageX
onMove(x)
}
function onTouchMove(e: any) {
const x = e.touches[0].pageX
onMove(x)
}
function onMove(x: number) {
// gradually increase friction as the dragger is pulled beyond bounds
// credit: https://github.com/metafizzy/flickity/blob/master/dist/flickity.pkgd.js#L2894
const moveVector = x - downX.current
let dragX = dragStartPosition.current + moveVector
const originBound = Math.max(rightBound.current, dragStartPosition.current)
if (dragX > originBound) {
dragX = (dragX + originBound) * 0.5
}
const endBound = Math.min(leftBound.current, dragStartPosition.current)
if (dragX < endBound) {
dragX = (dragX + endBound) * 0.5
}
dragPosition.current = dragX
}
function onRelease(e: any) {
isDragging.current = false
setIsDraggingStyle(false)
if (onUp) onUp() // optional props
// if the slider hasn't dragged sufficiently treat it as a static click
const moveVector = Math.abs(downX.current - e.pageX)
if (moveVector < 20 && onStaticClick) {
onStaticClick(e.target)
}
// Update html element styles
if (setCursorStyles) {
docStyle.cursor = ''
docStyle.userSelect = ''
}
if (isMouseEvent(e)) {
window.removeEventListener('mousemove', onMouseMove)
window.removeEventListener('mouseup', onRelease)
} else {
window.removeEventListener('touchmove', onTouchMove)
window.removeEventListener('touchend', onRelease)
}
}
function onMouseStart(e: React.MouseEvent) {
if (disabled) return
// dismiss clicks from right or middle buttons
// (credit: https://github.com/metafizzy/flickity/blob/e2706840532c0ce9c4fc25832e810ad4f9823b61/dist/flickity.pkgd.js#L2176)
const mouseButton = e.button
if (mouseButton && mouseButton !== 0 && mouseButton !== 1) return
isDragging.current = true
setIsDraggingStyle(true)
if (onDown) onDown() // Optional Prop
// Update <html> element styles
if (setCursorStyles) {
docStyle.cursor = 'grabbing'
docStyle.userSelect = 'none'
}
window.cancelAnimationFrame(rafId.current!) // cancel any existing loop
rafId.current = window.requestAnimationFrame(() => updateLoop(null)) // kick off a new loop
downX.current = e.pageX
dragStartPosition.current = nativePosition.current
onMouseMove(e) // initial onMove needed to set the starting mouse position
window.addEventListener('mousemove', onMouseMove)
window.addEventListener('mouseup', onRelease)
}
function onTouchStart(e: React.TouchEvent) {
if (disabled) return
isDragging.current = true
if (onDown) onDown() // Optional Prop
window.cancelAnimationFrame(rafId.current!) // cancel any existing loop
rafId.current = window.requestAnimationFrame(() => updateLoop(null)) // kick off a new loop
downX.current = e.touches[0].pageX
dragStartPosition.current = nativePosition.current
onTouchMove(e)
window.addEventListener('touchmove', onTouchMove)
window.addEventListener('touchend', onRelease)
}
function onBlur() {
// reset the browsers automatic container scrolling, caused by tabbing
outerEl.current!.scrollTo(0, 0)
}
return (
<div
data-id='dragger-outer'
ref={outerEl}
className={[
disabled ? ' is-disabled' : null,
className,
].join(' ')}
onTouchStart={onTouchStart}
onMouseDown={onMouseStart}
onBlur={onBlur}
style={{
cursor: mouseCursorStyle,
...style,
}}
>
<div
data-id='dragger-inner'
ref={innerEl}
className='dragger-inner'
style={{
transform: `translateX(${restPositionX.current}px)`,
whiteSpace: 'nowrap',
userSelect: 'none',
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
display: 'inline-block',
...innerStyle
}}
>
{children}
</div>
</div>
)
} | the_stack |
import * as assert from 'assert';
import {describe, it, afterEach} from 'mocha';
import * as qs from 'querystring';
import * as nock from 'nock';
import {createCrypto} from '../src/crypto/crypto';
import {
StsCredentials,
StsCredentialsOptions,
StsSuccessfulResponse,
} from '../src/auth/stscredentials';
import {
ClientAuthentication,
OAuthErrorResponse,
getErrorFromOAuthErrorResponse,
} from '../src/auth/oauth2common';
nock.disableNetConnect();
describe('StsCredentials', () => {
const crypto = createCrypto();
const baseUrl = 'https://example.com';
const path = '/token.oauth2';
const tokenExchangeEndpoint = `${baseUrl}${path}`;
const basicAuth: ClientAuthentication = {
confidentialClientType: 'basic',
clientId: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
};
const requestBodyAuth: ClientAuthentication = {
confidentialClientType: 'request-body',
clientId: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
};
// Full STS credentials options, useful to test that all supported
// parameters are handled correctly.
const stsCredentialsOptions: StsCredentialsOptions = {
grantType: 'urn:ietf:params:oauth:grant-type:token-exchange',
resource: 'https://api.example.com/',
audience: 'urn:example:cooperation-context',
scope: ['scope1', 'scope2'],
requestedTokenType: 'urn:ietf:params:oauth:token-type:access_token',
subjectToken: 'HEADER.SUBJECT_TOKEN_PAYLOAD.SIGNATURE',
subjectTokenType: 'urn:ietf:params:oauth:token-type:jwt',
actingParty: {
actorToken: 'HEADER.ACTOR_TOKEN_PAYLOAD.SIGNATURE',
actorTokenType: 'urn:ietf:params:oauth:token-type:jwt',
},
};
// Partial STS credentials options, useful to test that optional unspecified
// parameters are handled correctly.
const partialStsCredentialsOptions: StsCredentialsOptions = {
grantType: 'urn:ietf:params:oauth:grant-type:token-exchange',
audience: 'urn:example:cooperation-context',
requestedTokenType: 'urn:ietf:params:oauth:token-type:access_token',
subjectToken: 'HEADER.SUBJECT_TOKEN_PAYLOAD.SIGNATURE',
subjectTokenType: 'urn:ietf:params:oauth:token-type:jwt',
};
const stsSuccessfulResponse: StsSuccessfulResponse = {
access_token: 'ACCESS_TOKEN',
issued_token_type: 'urn:ietf:params:oauth:token-type:access_token',
token_type: 'Bearer',
expires_in: 3600,
scope: 'scope1 scope2',
};
const errorResponse: OAuthErrorResponse = {
error: 'invalid_request',
error_description: 'Invalid subject token',
error_uri: 'https://tools.ietf.org/html/rfc6749#section-5.2',
};
function assertGaxiosResponsePresent(resp: StsSuccessfulResponse) {
const gaxiosResponse = resp.res || {};
assert('data' in gaxiosResponse && 'status' in gaxiosResponse);
}
function mockStsTokenExchange(
statusCode = 200,
response: StsSuccessfulResponse | OAuthErrorResponse,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
request: {[key: string]: any},
additionalHeaders?: {[key: string]: string}
): nock.Scope {
const headers = Object.assign(
{
'content-type': 'application/x-www-form-urlencoded',
},
additionalHeaders || {}
);
return nock(baseUrl)
.post(path, qs.stringify(request), {
reqheaders: headers,
})
.reply(statusCode, response);
}
afterEach(() => {
nock.cleanAll();
});
describe('exchangeToken()', () => {
const additionalHeaders = {
'x-client-version': '0.1.2',
};
const options = {
additional: {
'non-standard': ['options'],
other: 'some-value',
},
};
const expectedRequest = {
grant_type: stsCredentialsOptions.grantType,
resource: stsCredentialsOptions.resource,
audience: stsCredentialsOptions.audience,
scope: stsCredentialsOptions.scope?.join(' '),
requested_token_type: stsCredentialsOptions.requestedTokenType,
subject_token: stsCredentialsOptions.subjectToken,
subject_token_type: stsCredentialsOptions.subjectTokenType,
actor_token: stsCredentialsOptions.actingParty?.actorToken,
actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,
options: JSON.stringify(options),
};
const expectedPartialRequest = {
grant_type: stsCredentialsOptions.grantType,
audience: stsCredentialsOptions.audience,
requested_token_type: stsCredentialsOptions.requestedTokenType,
subject_token: stsCredentialsOptions.subjectToken,
subject_token_type: stsCredentialsOptions.subjectTokenType,
};
const expectedRequestWithCreds = Object.assign({}, expectedRequest, {
client_id: requestBodyAuth.clientId,
client_secret: requestBodyAuth.clientSecret,
});
const expectedPartialRequestWithCreds = Object.assign(
{},
expectedPartialRequest,
{
client_id: requestBodyAuth.clientId,
client_secret: requestBodyAuth.clientSecret,
}
);
describe('without client authentication', () => {
it('should handle successful full request', async () => {
const scope = mockStsTokenExchange(
200,
stsSuccessfulResponse,
expectedRequest,
additionalHeaders
);
const stsCredentials = new StsCredentials(tokenExchangeEndpoint);
const resp = await stsCredentials.exchangeToken(
stsCredentialsOptions,
additionalHeaders,
options
);
// Confirm raw GaxiosResponse appended to response.
assertGaxiosResponsePresent(resp);
delete resp.res;
assert.deepStrictEqual(resp, stsSuccessfulResponse);
scope.done();
});
it('should handle successful partial request', async () => {
const scope = mockStsTokenExchange(
200,
stsSuccessfulResponse,
expectedPartialRequest
);
const stsCredentials = new StsCredentials(tokenExchangeEndpoint);
const resp = await stsCredentials.exchangeToken(
partialStsCredentialsOptions
);
// Confirm raw GaxiosResponse appended to response.
assertGaxiosResponsePresent(resp);
delete resp.res;
assert.deepStrictEqual(resp, stsSuccessfulResponse);
scope.done();
});
it('should handle non-200 response', async () => {
const scope = mockStsTokenExchange(
400,
errorResponse,
expectedRequest,
additionalHeaders
);
const expectedError = getErrorFromOAuthErrorResponse(errorResponse);
const stsCredentials = new StsCredentials(tokenExchangeEndpoint);
await assert.rejects(
stsCredentials.exchangeToken(
stsCredentialsOptions,
additionalHeaders,
options
),
expectedError
);
scope.done();
});
it('should handle request timeout', async () => {
const scope = nock(baseUrl)
.post(path, qs.stringify(expectedRequest), {
reqheaders: {
'content-type': 'application/x-www-form-urlencoded',
},
})
.replyWithError({code: 'ETIMEDOUT'});
const stsCredentials = new StsCredentials(tokenExchangeEndpoint);
await assert.rejects(
stsCredentials.exchangeToken(
stsCredentialsOptions,
additionalHeaders,
options
),
{
code: 'ETIMEDOUT',
}
);
scope.done();
});
});
describe('with basic client authentication', () => {
const creds = `${basicAuth.clientId}:${basicAuth.clientSecret}`;
it('should handle successful full request', async () => {
const scope = mockStsTokenExchange(
200,
stsSuccessfulResponse,
expectedRequest,
Object.assign(
{
Authorization: `Basic ${crypto.encodeBase64StringUtf8(creds)}`,
},
additionalHeaders
)
);
const stsCredentials = new StsCredentials(
tokenExchangeEndpoint,
basicAuth
);
const resp = await stsCredentials.exchangeToken(
stsCredentialsOptions,
additionalHeaders,
options
);
// Confirm raw GaxiosResponse appended to response.
assertGaxiosResponsePresent(resp);
delete resp.res;
assert.deepStrictEqual(resp, stsSuccessfulResponse);
scope.done();
});
it('should handle successful partial request', async () => {
const scope = mockStsTokenExchange(
200,
stsSuccessfulResponse,
expectedPartialRequest,
{
Authorization: `Basic ${crypto.encodeBase64StringUtf8(creds)}`,
}
);
const stsCredentials = new StsCredentials(
tokenExchangeEndpoint,
basicAuth
);
const resp = await stsCredentials.exchangeToken(
partialStsCredentialsOptions
);
// Confirm raw GaxiosResponse appended to response.
assertGaxiosResponsePresent(resp);
delete resp.res;
assert.deepStrictEqual(resp, stsSuccessfulResponse);
scope.done();
});
it('should handle non-200 response', async () => {
const expectedError = getErrorFromOAuthErrorResponse(errorResponse);
const scope = mockStsTokenExchange(
400,
errorResponse,
expectedRequest,
Object.assign(
{
Authorization: `Basic ${crypto.encodeBase64StringUtf8(creds)}`,
},
additionalHeaders
)
);
const stsCredentials = new StsCredentials(
tokenExchangeEndpoint,
basicAuth
);
await assert.rejects(
stsCredentials.exchangeToken(
stsCredentialsOptions,
additionalHeaders,
options
),
expectedError
);
scope.done();
});
});
describe('with request-body client authentication', () => {
it('should handle successful full request', async () => {
const scope = mockStsTokenExchange(
200,
stsSuccessfulResponse,
expectedRequestWithCreds,
additionalHeaders
);
const stsCredentials = new StsCredentials(
tokenExchangeEndpoint,
requestBodyAuth
);
const resp = await stsCredentials.exchangeToken(
stsCredentialsOptions,
additionalHeaders,
options
);
// Confirm raw GaxiosResponse appended to response.
assertGaxiosResponsePresent(resp);
delete resp.res;
assert.deepStrictEqual(resp, stsSuccessfulResponse);
scope.done();
});
it('should handle successful partial request', async () => {
const scope = mockStsTokenExchange(
200,
stsSuccessfulResponse,
expectedPartialRequestWithCreds
);
const stsCredentials = new StsCredentials(
tokenExchangeEndpoint,
requestBodyAuth
);
const resp = await stsCredentials.exchangeToken(
partialStsCredentialsOptions
);
// Confirm raw GaxiosResponse appended to response.
assertGaxiosResponsePresent(resp);
delete resp.res;
assert.deepStrictEqual(resp, stsSuccessfulResponse);
scope.done();
});
it('should handle non-200 response', async () => {
const expectedError = getErrorFromOAuthErrorResponse(errorResponse);
const scope = mockStsTokenExchange(
400,
errorResponse,
expectedRequestWithCreds,
additionalHeaders
);
const stsCredentials = new StsCredentials(
tokenExchangeEndpoint,
requestBodyAuth
);
await assert.rejects(
stsCredentials.exchangeToken(
stsCredentialsOptions,
additionalHeaders,
options
),
expectedError
);
scope.done();
});
});
});
}); | the_stack |
import * as test from 'tape';
import {NoteSequence} from '../protobuf/index';
import {Performance, PerformanceEvent} from './performance';
test('From NoteSequence', (t: test.Test) => {
const noteSequence = NoteSequence.create({
quantizationInfo: {stepsPerSecond: 10},
notes: [
{pitch: 60, velocity: 127, quantizedStartStep: 0, quantizedEndStep: 40},
{pitch: 64, velocity: 127, quantizedStartStep: 0, quantizedEndStep: 30},
{pitch: 67, velocity: 127, quantizedStartStep: 10, quantizedEndStep: 20},
],
totalQuantizedSteps: 40
});
const performance = Performance.fromNoteSequence(noteSequence, 10, 0);
const expectedEvents: PerformanceEvent[] = [
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-on', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
];
t.deepEqual(performance.events, expectedEvents);
t.end();
});
test('From NoteSequence With Velocity', (t: test.Test) => {
const noteSequence = NoteSequence.create({
quantizationInfo: {stepsPerSecond: 10},
notes: [
{pitch: 60, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 40},
{pitch: 64, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 30},
{pitch: 67, velocity: 127, quantizedStartStep: 10, quantizedEndStep: 20},
],
totalQuantizedSteps: 40
});
const performance = Performance.fromNoteSequence(noteSequence, 10, 127);
const expectedEvents: PerformanceEvent[] = [
{type: 'velocity-change', velocityBin: 100},
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'velocity-change', velocityBin: 127},
{type: 'note-on', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
];
t.deepEqual(performance.events, expectedEvents);
t.end();
});
test('From NoteSequence With Quantized Velocity', (t: test.Test) => {
const noteSequence = NoteSequence.create({
quantizationInfo: {stepsPerSecond: 10},
notes: [
{pitch: 60, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 40},
{pitch: 64, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 30},
{pitch: 67, velocity: 127, quantizedStartStep: 10, quantizedEndStep: 20},
],
totalQuantizedSteps: 40
});
const performance = Performance.fromNoteSequence(noteSequence, 10, 16);
const expectedEvents: PerformanceEvent[] = [
{type: 'velocity-change', velocityBin: 13},
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'velocity-change', velocityBin: 16},
{type: 'note-on', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
];
t.deepEqual(performance.events, expectedEvents);
t.end();
});
test('From NoteSequence (Program and Drum Status)', (t: test.Test) => {
const noteSequence = NoteSequence.create({
quantizationInfo: {stepsPerSecond: 10},
notes: [
{pitch: 60, quantizedEndStep: 40, instrument: 0, program: 1},
{pitch: 64, quantizedEndStep: 30, instrument: 0, program: 1},
{pitch: 67, quantizedEndStep: 20, instrument: 0, program: 1},
{pitch: 36, quantizedEndStep: 40, instrument: 1, program: 2},
{pitch: 48, quantizedEndStep: 40, instrument: 1, program: 2},
{pitch: 57, quantizedEndStep: 1, instrument: 2, program: 0, isDrum: true},
],
totalQuantizedSteps: 40
});
const performance = Performance.fromNoteSequence(noteSequence, 10, 0);
const performance0 = Performance.fromNoteSequence(noteSequence, 10, 0, 0);
const performance1 = Performance.fromNoteSequence(noteSequence, 10, 0, 1);
const performance2 = Performance.fromNoteSequence(noteSequence, 10, 0, 2);
t.equal(performance.program, undefined);
t.equal(performance.isDrum, undefined);
t.equal(performance0.program, 1);
t.equal(performance0.isDrum, false);
t.equal(performance1.program, 2);
t.equal(performance1.isDrum, false);
t.equal(performance2.program, undefined);
t.equal(performance2.isDrum, true);
t.end();
});
test('Add Steps', (t: test.Test) => {
const performance = new Performance([], 10, 0);
performance.setNumSteps(5);
t.equal(performance.getNumSteps(), 5);
t.deepEqual(performance.events, [{type: 'time-shift', steps: 5}]);
performance.setNumSteps(15);
t.equal(performance.getNumSteps(), 15);
t.deepEqual(
performance.events,
[{type: 'time-shift', steps: 10}, {type: 'time-shift', steps: 5}]);
performance.setNumSteps(20);
t.equal(performance.getNumSteps(), 20);
t.deepEqual(
performance.events,
[{type: 'time-shift', steps: 10}, {type: 'time-shift', steps: 10}]);
t.end();
});
test('Remove Steps', (t: test.Test) => {
const events: PerformanceEvent[] = [
{type: 'note-on', pitch: 60},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'note-on', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 67},
];
const performance = new Performance(events, 10, 0);
performance.setNumSteps(20);
const expectedEvents: PerformanceEvent[] = [
{type: 'note-on', pitch: 60},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'note-on', pitch: 67},
];
t.equal(performance.getNumSteps(), 20);
t.deepEqual(performance.events, expectedEvents);
performance.setNumSteps(5);
t.equal(performance.getNumSteps(), 5);
t.deepEqual(
performance.events,
[{type: 'note-on', pitch: 60}, {type: 'time-shift', steps: 5}]);
t.end();
});
test('To NoteSequence', (t: test.Test) => {
const events: PerformanceEvent[] = [
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-on', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
];
const performance = new Performance(events, 10, 0);
const noteSequence = performance.toNoteSequence();
const expectedNoteSequence = NoteSequence.create({
notes: [
{pitch: 67, quantizedStartStep: 10, quantizedEndStep: 20},
{pitch: 64, quantizedStartStep: 0, quantizedEndStep: 30},
{pitch: 60, quantizedStartStep: 0, quantizedEndStep: 40},
],
totalQuantizedSteps: 40
});
t.deepEqual(noteSequence, expectedNoteSequence);
t.end();
});
test('To NoteSequence With Velocity', (t: test.Test) => {
const events: PerformanceEvent[] = [
{type: 'velocity-change', velocityBin: 100},
{type: 'note-on', pitch: 60},
{type: 'velocity-change', velocityBin: 115},
{type: 'note-on', pitch: 64},
{type: 'velocity-change', velocityBin: 127},
{type: 'time-shift', steps: 10},
{type: 'note-on', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
];
const performance = new Performance(events, 10, 127);
const noteSequence = performance.toNoteSequence();
const expectedNoteSequence = NoteSequence.create({
notes: [
{pitch: 67, velocity: 127, quantizedStartStep: 10, quantizedEndStep: 20},
{pitch: 64, velocity: 115, quantizedStartStep: 0, quantizedEndStep: 30},
{pitch: 60, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 40},
],
totalQuantizedSteps: 40
});
t.deepEqual(noteSequence, expectedNoteSequence);
t.end();
});
test('To NoteSequence With Quantized Velocity', (t: test.Test) => {
const events: PerformanceEvent[] = [
{type: 'velocity-change', velocityBin: 13},
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'velocity-change', velocityBin: 16},
{type: 'time-shift', steps: 10},
{type: 'note-on', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 67},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-off', pitch: 60},
];
const performance = new Performance(events, 10, 16);
const noteSequence = performance.toNoteSequence();
const expectedNoteSequence = NoteSequence.create({
notes: [
{pitch: 67, velocity: 121, quantizedStartStep: 10, quantizedEndStep: 20},
{pitch: 64, velocity: 97, quantizedStartStep: 0, quantizedEndStep: 30},
{pitch: 60, velocity: 97, quantizedStartStep: 0, quantizedEndStep: 40},
],
totalQuantizedSteps: 40
});
t.deepEqual(noteSequence, expectedNoteSequence);
t.end();
});
test('To NoteSequence With Unmatched Note-Offs', (t: test.Test) => {
const events: PerformanceEvent[] = [
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 5},
{type: 'note-off', pitch: 60},
{type: 'note-off', pitch: 64},
{type: 'note-off', pitch: 67},
];
const performance = new Performance(events, 10, 0);
const noteSequence = performance.toNoteSequence();
const expectedNoteSequence = NoteSequence.create({
notes: [
{pitch: 60, quantizedStartStep: 0, quantizedEndStep: 5},
{pitch: 64, quantizedStartStep: 0, quantizedEndStep: 5},
],
totalQuantizedSteps: 5
});
t.deepEqual(noteSequence, expectedNoteSequence);
t.end();
});
test('To NoteSequence With Unmatched Note-Ons', (t: test.Test) => {
const events: PerformanceEvent[] = [
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
];
const performance = new Performance(events, 10, 0);
const noteSequence = performance.toNoteSequence();
const expectedNoteSequence = NoteSequence.create({
notes: [
{pitch: 60, quantizedStartStep: 0, quantizedEndStep: 10},
{pitch: 64, quantizedStartStep: 0, quantizedEndStep: 10},
],
totalQuantizedSteps: 10
});
t.deepEqual(noteSequence, expectedNoteSequence);
t.end();
});
test('To NoteSequence With Repeated Notes', (t: test.Test) => {
const events: PerformanceEvent[] = [
{type: 'note-on', pitch: 60},
{type: 'note-on', pitch: 64},
{type: 'time-shift', steps: 10},
{type: 'note-on', pitch: 60},
{type: 'time-shift', steps: 10},
];
const performance = new Performance(events, 10, 0);
const noteSequence = performance.toNoteSequence();
const expectedNoteSequence = NoteSequence.create({
notes: [
{pitch: 60, quantizedStartStep: 0, quantizedEndStep: 20},
{pitch: 60, quantizedStartStep: 10, quantizedEndStep: 20},
{pitch: 64, quantizedStartStep: 0, quantizedEndStep: 20},
],
totalQuantizedSteps: 20
});
t.deepEqual(noteSequence, expectedNoteSequence);
t.end();
}); | the_stack |
type ErrorWithCode = Error & { code: number };
type MaybeErrorWithCode = ErrorWithCode | null | undefined;
const createErrorFromCodeLookup: Map<number, () => ErrorWithCode> = new Map();
const createErrorFromNameLookup: Map<string, () => ErrorWithCode> = new Map();
/**
* InstructionUnpackError: 'Failed to unpack instruction data'
*
* @category Errors
* @category generated
*/
export class InstructionUnpackErrorError extends Error {
readonly code: number = 0x0;
readonly name: string = 'InstructionUnpackError';
constructor() {
super('Failed to unpack instruction data');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InstructionUnpackErrorError);
}
}
}
createErrorFromCodeLookup.set(0x0, () => new InstructionUnpackErrorError());
createErrorFromNameLookup.set('InstructionUnpackError', () => new InstructionUnpackErrorError());
/**
* NotRentExempt: 'Lamport balance below rent-exempt threshold'
*
* @category Errors
* @category generated
*/
export class NotRentExemptError extends Error {
readonly code: number = 0x1;
readonly name: string = 'NotRentExempt';
constructor() {
super('Lamport balance below rent-exempt threshold');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotRentExemptError);
}
}
}
createErrorFromCodeLookup.set(0x1, () => new NotRentExemptError());
createErrorFromNameLookup.set('NotRentExempt', () => new NotRentExemptError());
/**
* AlreadyInitialized: 'Already initialized'
*
* @category Errors
* @category generated
*/
export class AlreadyInitializedError extends Error {
readonly code: number = 0x2;
readonly name: string = 'AlreadyInitialized';
constructor() {
super('Already initialized');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, AlreadyInitializedError);
}
}
}
createErrorFromCodeLookup.set(0x2, () => new AlreadyInitializedError());
createErrorFromNameLookup.set('AlreadyInitialized', () => new AlreadyInitializedError());
/**
* Uninitialized: 'Uninitialized'
*
* @category Errors
* @category generated
*/
export class UninitializedError extends Error {
readonly code: number = 0x3;
readonly name: string = 'Uninitialized';
constructor() {
super('Uninitialized');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UninitializedError);
}
}
}
createErrorFromCodeLookup.set(0x3, () => new UninitializedError());
createErrorFromNameLookup.set('Uninitialized', () => new UninitializedError());
/**
* IncorrectOwner: 'Account does not have correct owner'
*
* @category Errors
* @category generated
*/
export class IncorrectOwnerError extends Error {
readonly code: number = 0x4;
readonly name: string = 'IncorrectOwner';
constructor() {
super('Account does not have correct owner');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, IncorrectOwnerError);
}
}
}
createErrorFromCodeLookup.set(0x4, () => new IncorrectOwnerError());
createErrorFromNameLookup.set('IncorrectOwner', () => new IncorrectOwnerError());
/**
* NumericalOverflowError: 'NumericalOverflowError'
*
* @category Errors
* @category generated
*/
export class NumericalOverflowErrorError extends Error {
readonly code: number = 0x5;
readonly name: string = 'NumericalOverflowError';
constructor() {
super('NumericalOverflowError');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NumericalOverflowErrorError);
}
}
}
createErrorFromCodeLookup.set(0x5, () => new NumericalOverflowErrorError());
createErrorFromNameLookup.set('NumericalOverflowError', () => new NumericalOverflowErrorError());
/**
* TokenAccountContainsNoTokens: 'Provided token account contains no tokens'
*
* @category Errors
* @category generated
*/
export class TokenAccountContainsNoTokensError extends Error {
readonly code: number = 0x6;
readonly name: string = 'TokenAccountContainsNoTokens';
constructor() {
super('Provided token account contains no tokens');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenAccountContainsNoTokensError);
}
}
}
createErrorFromCodeLookup.set(0x6, () => new TokenAccountContainsNoTokensError());
createErrorFromNameLookup.set(
'TokenAccountContainsNoTokens',
() => new TokenAccountContainsNoTokensError(),
);
/**
* TokenAccountAmountLessThanAmountSpecified: 'Provided token account cannot provide amount specified'
*
* @category Errors
* @category generated
*/
export class TokenAccountAmountLessThanAmountSpecifiedError extends Error {
readonly code: number = 0x7;
readonly name: string = 'TokenAccountAmountLessThanAmountSpecified';
constructor() {
super('Provided token account cannot provide amount specified');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenAccountAmountLessThanAmountSpecifiedError);
}
}
}
createErrorFromCodeLookup.set(0x7, () => new TokenAccountAmountLessThanAmountSpecifiedError());
createErrorFromNameLookup.set(
'TokenAccountAmountLessThanAmountSpecified',
() => new TokenAccountAmountLessThanAmountSpecifiedError(),
);
/**
* VaultAccountIsNotEmpty: 'Provided vault account contains is not empty'
*
* @category Errors
* @category generated
*/
export class VaultAccountIsNotEmptyError extends Error {
readonly code: number = 0x8;
readonly name: string = 'VaultAccountIsNotEmpty';
constructor() {
super('Provided vault account contains is not empty');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultAccountIsNotEmptyError);
}
}
}
createErrorFromCodeLookup.set(0x8, () => new VaultAccountIsNotEmptyError());
createErrorFromNameLookup.set('VaultAccountIsNotEmpty', () => new VaultAccountIsNotEmptyError());
/**
* VaultAccountIsNotOwnedByProgram: 'Provided vault account is not owned by program derived address with seed of prefix and program id'
*
* @category Errors
* @category generated
*/
export class VaultAccountIsNotOwnedByProgramError extends Error {
readonly code: number = 0x9;
readonly name: string = 'VaultAccountIsNotOwnedByProgram';
constructor() {
super(
'Provided vault account is not owned by program derived address with seed of prefix and program id',
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultAccountIsNotOwnedByProgramError);
}
}
}
createErrorFromCodeLookup.set(0x9, () => new VaultAccountIsNotOwnedByProgramError());
createErrorFromNameLookup.set(
'VaultAccountIsNotOwnedByProgram',
() => new VaultAccountIsNotOwnedByProgramError(),
);
/**
* SafetyDepositAddressInvalid: 'The provided safety deposit account address does not match the expected program derived address'
*
* @category Errors
* @category generated
*/
export class SafetyDepositAddressInvalidError extends Error {
readonly code: number = 0xa;
readonly name: string = 'SafetyDepositAddressInvalid';
constructor() {
super(
'The provided safety deposit account address does not match the expected program derived address',
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SafetyDepositAddressInvalidError);
}
}
}
createErrorFromCodeLookup.set(0xa, () => new SafetyDepositAddressInvalidError());
createErrorFromNameLookup.set(
'SafetyDepositAddressInvalid',
() => new SafetyDepositAddressInvalidError(),
);
/**
* TokenTransferFailed: 'Token transfer failed'
*
* @category Errors
* @category generated
*/
export class TokenTransferFailedError extends Error {
readonly code: number = 0xb;
readonly name: string = 'TokenTransferFailed';
constructor() {
super('Token transfer failed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenTransferFailedError);
}
}
}
createErrorFromCodeLookup.set(0xb, () => new TokenTransferFailedError());
createErrorFromNameLookup.set('TokenTransferFailed', () => new TokenTransferFailedError());
/**
* TokenMintToFailed: 'Token mint to failed'
*
* @category Errors
* @category generated
*/
export class TokenMintToFailedError extends Error {
readonly code: number = 0xc;
readonly name: string = 'TokenMintToFailed';
constructor() {
super('Token mint to failed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenMintToFailedError);
}
}
}
createErrorFromCodeLookup.set(0xc, () => new TokenMintToFailedError());
createErrorFromNameLookup.set('TokenMintToFailed', () => new TokenMintToFailedError());
/**
* TokenBurnFailed: 'Token burn failed'
*
* @category Errors
* @category generated
*/
export class TokenBurnFailedError extends Error {
readonly code: number = 0xd;
readonly name: string = 'TokenBurnFailed';
constructor() {
super('Token burn failed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenBurnFailedError);
}
}
}
createErrorFromCodeLookup.set(0xd, () => new TokenBurnFailedError());
createErrorFromNameLookup.set('TokenBurnFailed', () => new TokenBurnFailedError());
/**
* VaultMintNotEmpty: 'Vault mint not empty on init'
*
* @category Errors
* @category generated
*/
export class VaultMintNotEmptyError extends Error {
readonly code: number = 0xe;
readonly name: string = 'VaultMintNotEmpty';
constructor() {
super('Vault mint not empty on init');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultMintNotEmptyError);
}
}
}
createErrorFromCodeLookup.set(0xe, () => new VaultMintNotEmptyError());
createErrorFromNameLookup.set('VaultMintNotEmpty', () => new VaultMintNotEmptyError());
/**
* VaultAuthorityNotProgram: 'Vault mint's authority not set to program PDA with seed of prefix and program id'
*
* @category Errors
* @category generated
*/
export class VaultAuthorityNotProgramError extends Error {
readonly code: number = 0xf;
readonly name: string = 'VaultAuthorityNotProgram';
constructor() {
super("Vault mint's authority not set to program PDA with seed of prefix and program id");
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultAuthorityNotProgramError);
}
}
}
createErrorFromCodeLookup.set(0xf, () => new VaultAuthorityNotProgramError());
createErrorFromNameLookup.set(
'VaultAuthorityNotProgram',
() => new VaultAuthorityNotProgramError(),
);
/**
* TreasuryNotEmpty: 'Vault treasury not empty on init'
*
* @category Errors
* @category generated
*/
export class TreasuryNotEmptyError extends Error {
readonly code: number = 0x10;
readonly name: string = 'TreasuryNotEmpty';
constructor() {
super('Vault treasury not empty on init');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TreasuryNotEmptyError);
}
}
}
createErrorFromCodeLookup.set(0x10, () => new TreasuryNotEmptyError());
createErrorFromNameLookup.set('TreasuryNotEmpty', () => new TreasuryNotEmptyError());
/**
* TreasuryOwnerNotProgram: 'Vault treasury's owner not set to program pda with seed of prefix and program id'
*
* @category Errors
* @category generated
*/
export class TreasuryOwnerNotProgramError extends Error {
readonly code: number = 0x11;
readonly name: string = 'TreasuryOwnerNotProgram';
constructor() {
super("Vault treasury's owner not set to program pda with seed of prefix and program id");
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TreasuryOwnerNotProgramError);
}
}
}
createErrorFromCodeLookup.set(0x11, () => new TreasuryOwnerNotProgramError());
createErrorFromNameLookup.set('TreasuryOwnerNotProgram', () => new TreasuryOwnerNotProgramError());
/**
* VaultShouldBeInactive: 'Vault should be inactive'
*
* @category Errors
* @category generated
*/
export class VaultShouldBeInactiveError extends Error {
readonly code: number = 0x12;
readonly name: string = 'VaultShouldBeInactive';
constructor() {
super('Vault should be inactive');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultShouldBeInactiveError);
}
}
}
createErrorFromCodeLookup.set(0x12, () => new VaultShouldBeInactiveError());
createErrorFromNameLookup.set('VaultShouldBeInactive', () => new VaultShouldBeInactiveError());
/**
* VaultShouldBeActive: 'Vault should be active'
*
* @category Errors
* @category generated
*/
export class VaultShouldBeActiveError extends Error {
readonly code: number = 0x13;
readonly name: string = 'VaultShouldBeActive';
constructor() {
super('Vault should be active');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultShouldBeActiveError);
}
}
}
createErrorFromCodeLookup.set(0x13, () => new VaultShouldBeActiveError());
createErrorFromNameLookup.set('VaultShouldBeActive', () => new VaultShouldBeActiveError());
/**
* VaultShouldBeCombined: 'Vault should be combined'
*
* @category Errors
* @category generated
*/
export class VaultShouldBeCombinedError extends Error {
readonly code: number = 0x14;
readonly name: string = 'VaultShouldBeCombined';
constructor() {
super('Vault should be combined');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultShouldBeCombinedError);
}
}
}
createErrorFromCodeLookup.set(0x14, () => new VaultShouldBeCombinedError());
createErrorFromNameLookup.set('VaultShouldBeCombined', () => new VaultShouldBeCombinedError());
/**
* VaultTreasuryMintDoesNotMatchVaultMint: 'Vault treasury needs to match fraction mint'
*
* @category Errors
* @category generated
*/
export class VaultTreasuryMintDoesNotMatchVaultMintError extends Error {
readonly code: number = 0x15;
readonly name: string = 'VaultTreasuryMintDoesNotMatchVaultMint';
constructor() {
super('Vault treasury needs to match fraction mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultTreasuryMintDoesNotMatchVaultMintError);
}
}
}
createErrorFromCodeLookup.set(0x15, () => new VaultTreasuryMintDoesNotMatchVaultMintError());
createErrorFromNameLookup.set(
'VaultTreasuryMintDoesNotMatchVaultMint',
() => new VaultTreasuryMintDoesNotMatchVaultMintError(),
);
/**
* RedeemTreasuryCantShareSameMintAsFraction: 'Redeem Treasury cannot be same mint as fraction'
*
* @category Errors
* @category generated
*/
export class RedeemTreasuryCantShareSameMintAsFractionError extends Error {
readonly code: number = 0x16;
readonly name: string = 'RedeemTreasuryCantShareSameMintAsFraction';
constructor() {
super('Redeem Treasury cannot be same mint as fraction');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, RedeemTreasuryCantShareSameMintAsFractionError);
}
}
}
createErrorFromCodeLookup.set(0x16, () => new RedeemTreasuryCantShareSameMintAsFractionError());
createErrorFromNameLookup.set(
'RedeemTreasuryCantShareSameMintAsFraction',
() => new RedeemTreasuryCantShareSameMintAsFractionError(),
);
/**
* InvalidAuthority: 'Invalid program authority provided'
*
* @category Errors
* @category generated
*/
export class InvalidAuthorityError extends Error {
readonly code: number = 0x17;
readonly name: string = 'InvalidAuthority';
constructor() {
super('Invalid program authority provided');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidAuthorityError);
}
}
}
createErrorFromCodeLookup.set(0x17, () => new InvalidAuthorityError());
createErrorFromNameLookup.set('InvalidAuthority', () => new InvalidAuthorityError());
/**
* RedeemTreasuryMintMustMatchLookupMint: 'Redeem treasury mint must match lookup mint'
*
* @category Errors
* @category generated
*/
export class RedeemTreasuryMintMustMatchLookupMintError extends Error {
readonly code: number = 0x18;
readonly name: string = 'RedeemTreasuryMintMustMatchLookupMint';
constructor() {
super('Redeem treasury mint must match lookup mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, RedeemTreasuryMintMustMatchLookupMintError);
}
}
}
createErrorFromCodeLookup.set(0x18, () => new RedeemTreasuryMintMustMatchLookupMintError());
createErrorFromNameLookup.set(
'RedeemTreasuryMintMustMatchLookupMint',
() => new RedeemTreasuryMintMustMatchLookupMintError(),
);
/**
* PaymentMintShouldMatchPricingMint: 'You must pay with the same mint as the external pricing oracle'
*
* @category Errors
* @category generated
*/
export class PaymentMintShouldMatchPricingMintError extends Error {
readonly code: number = 0x19;
readonly name: string = 'PaymentMintShouldMatchPricingMint';
constructor() {
super('You must pay with the same mint as the external pricing oracle');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PaymentMintShouldMatchPricingMintError);
}
}
}
createErrorFromCodeLookup.set(0x19, () => new PaymentMintShouldMatchPricingMintError());
createErrorFromNameLookup.set(
'PaymentMintShouldMatchPricingMint',
() => new PaymentMintShouldMatchPricingMintError(),
);
/**
* ShareMintShouldMatchFractionalMint: 'Your share account should match the mint of the fractional mint'
*
* @category Errors
* @category generated
*/
export class ShareMintShouldMatchFractionalMintError extends Error {
readonly code: number = 0x1a;
readonly name: string = 'ShareMintShouldMatchFractionalMint';
constructor() {
super('Your share account should match the mint of the fractional mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ShareMintShouldMatchFractionalMintError);
}
}
}
createErrorFromCodeLookup.set(0x1a, () => new ShareMintShouldMatchFractionalMintError());
createErrorFromNameLookup.set(
'ShareMintShouldMatchFractionalMint',
() => new ShareMintShouldMatchFractionalMintError(),
);
/**
* VaultMintNeedsToMatchVault: 'Vault mint provided does not match that on the token vault'
*
* @category Errors
* @category generated
*/
export class VaultMintNeedsToMatchVaultError extends Error {
readonly code: number = 0x1b;
readonly name: string = 'VaultMintNeedsToMatchVault';
constructor() {
super('Vault mint provided does not match that on the token vault');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultMintNeedsToMatchVaultError);
}
}
}
createErrorFromCodeLookup.set(0x1b, () => new VaultMintNeedsToMatchVaultError());
createErrorFromNameLookup.set(
'VaultMintNeedsToMatchVault',
() => new VaultMintNeedsToMatchVaultError(),
);
/**
* RedeemTreasuryNeedsToMatchVault: 'Redeem treasury provided does not match that on the token vault'
*
* @category Errors
* @category generated
*/
export class RedeemTreasuryNeedsToMatchVaultError extends Error {
readonly code: number = 0x1c;
readonly name: string = 'RedeemTreasuryNeedsToMatchVault';
constructor() {
super('Redeem treasury provided does not match that on the token vault');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, RedeemTreasuryNeedsToMatchVaultError);
}
}
}
createErrorFromCodeLookup.set(0x1c, () => new RedeemTreasuryNeedsToMatchVaultError());
createErrorFromNameLookup.set(
'RedeemTreasuryNeedsToMatchVault',
() => new RedeemTreasuryNeedsToMatchVaultError(),
);
/**
* FractionTreasuryNeedsToMatchVault: 'Fraction treasury provided does not match that on the token vault'
*
* @category Errors
* @category generated
*/
export class FractionTreasuryNeedsToMatchVaultError extends Error {
readonly code: number = 0x1d;
readonly name: string = 'FractionTreasuryNeedsToMatchVault';
constructor() {
super('Fraction treasury provided does not match that on the token vault');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, FractionTreasuryNeedsToMatchVaultError);
}
}
}
createErrorFromCodeLookup.set(0x1d, () => new FractionTreasuryNeedsToMatchVaultError());
createErrorFromNameLookup.set(
'FractionTreasuryNeedsToMatchVault',
() => new FractionTreasuryNeedsToMatchVaultError(),
);
/**
* NotAllowedToCombine: 'Not allowed to combine at this time'
*
* @category Errors
* @category generated
*/
export class NotAllowedToCombineError extends Error {
readonly code: number = 0x1e;
readonly name: string = 'NotAllowedToCombine';
constructor() {
super('Not allowed to combine at this time');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotAllowedToCombineError);
}
}
}
createErrorFromCodeLookup.set(0x1e, () => new NotAllowedToCombineError());
createErrorFromNameLookup.set('NotAllowedToCombine', () => new NotAllowedToCombineError());
/**
* CannotAffordToCombineThisVault: 'You cannot afford to combine this vault'
*
* @category Errors
* @category generated
*/
export class CannotAffordToCombineThisVaultError extends Error {
readonly code: number = 0x1f;
readonly name: string = 'CannotAffordToCombineThisVault';
constructor() {
super('You cannot afford to combine this vault');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CannotAffordToCombineThisVaultError);
}
}
}
createErrorFromCodeLookup.set(0x1f, () => new CannotAffordToCombineThisVaultError());
createErrorFromNameLookup.set(
'CannotAffordToCombineThisVault',
() => new CannotAffordToCombineThisVaultError(),
);
/**
* NoShares: 'You have no shares to redeem'
*
* @category Errors
* @category generated
*/
export class NoSharesError extends Error {
readonly code: number = 0x20;
readonly name: string = 'NoShares';
constructor() {
super('You have no shares to redeem');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NoSharesError);
}
}
}
createErrorFromCodeLookup.set(0x20, () => new NoSharesError());
createErrorFromNameLookup.set('NoShares', () => new NoSharesError());
/**
* OutstandingShareAccountNeedsToMatchFractionalMint: 'Your outstanding share account is the incorrect mint'
*
* @category Errors
* @category generated
*/
export class OutstandingShareAccountNeedsToMatchFractionalMintError extends Error {
readonly code: number = 0x21;
readonly name: string = 'OutstandingShareAccountNeedsToMatchFractionalMint';
constructor() {
super('Your outstanding share account is the incorrect mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, OutstandingShareAccountNeedsToMatchFractionalMintError);
}
}
}
createErrorFromCodeLookup.set(
0x21,
() => new OutstandingShareAccountNeedsToMatchFractionalMintError(),
);
createErrorFromNameLookup.set(
'OutstandingShareAccountNeedsToMatchFractionalMint',
() => new OutstandingShareAccountNeedsToMatchFractionalMintError(),
);
/**
* DestinationAccountNeedsToMatchRedeemMint: 'Your destination account is the incorrect mint'
*
* @category Errors
* @category generated
*/
export class DestinationAccountNeedsToMatchRedeemMintError extends Error {
readonly code: number = 0x22;
readonly name: string = 'DestinationAccountNeedsToMatchRedeemMint';
constructor() {
super('Your destination account is the incorrect mint');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DestinationAccountNeedsToMatchRedeemMintError);
}
}
}
createErrorFromCodeLookup.set(0x22, () => new DestinationAccountNeedsToMatchRedeemMintError());
createErrorFromNameLookup.set(
'DestinationAccountNeedsToMatchRedeemMint',
() => new DestinationAccountNeedsToMatchRedeemMintError(),
);
/**
* FractionSupplyEmpty: 'Fractional mint is empty'
*
* @category Errors
* @category generated
*/
export class FractionSupplyEmptyError extends Error {
readonly code: number = 0x23;
readonly name: string = 'FractionSupplyEmpty';
constructor() {
super('Fractional mint is empty');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, FractionSupplyEmptyError);
}
}
}
createErrorFromCodeLookup.set(0x23, () => new FractionSupplyEmptyError());
createErrorFromNameLookup.set('FractionSupplyEmpty', () => new FractionSupplyEmptyError());
/**
* TokenProgramProvidedDoesNotMatchVault: 'Token Program Provided Needs To Match Vault'
*
* @category Errors
* @category generated
*/
export class TokenProgramProvidedDoesNotMatchVaultError extends Error {
readonly code: number = 0x24;
readonly name: string = 'TokenProgramProvidedDoesNotMatchVault';
constructor() {
super('Token Program Provided Needs To Match Vault');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TokenProgramProvidedDoesNotMatchVaultError);
}
}
}
createErrorFromCodeLookup.set(0x24, () => new TokenProgramProvidedDoesNotMatchVaultError());
createErrorFromNameLookup.set(
'TokenProgramProvidedDoesNotMatchVault',
() => new TokenProgramProvidedDoesNotMatchVaultError(),
);
/**
* AuthorityIsNotSigner: 'Authority of vault needs to be signer for this action'
*
* @category Errors
* @category generated
*/
export class AuthorityIsNotSignerError extends Error {
readonly code: number = 0x25;
readonly name: string = 'AuthorityIsNotSigner';
constructor() {
super('Authority of vault needs to be signer for this action');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, AuthorityIsNotSignerError);
}
}
}
createErrorFromCodeLookup.set(0x25, () => new AuthorityIsNotSignerError());
createErrorFromNameLookup.set('AuthorityIsNotSigner', () => new AuthorityIsNotSignerError());
/**
* AuthorityDoesNotMatch: 'Authority of vault does not match authority provided'
*
* @category Errors
* @category generated
*/
export class AuthorityDoesNotMatchError extends Error {
readonly code: number = 0x26;
readonly name: string = 'AuthorityDoesNotMatch';
constructor() {
super('Authority of vault does not match authority provided');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, AuthorityDoesNotMatchError);
}
}
}
createErrorFromCodeLookup.set(0x26, () => new AuthorityDoesNotMatchError());
createErrorFromNameLookup.set('AuthorityDoesNotMatch', () => new AuthorityDoesNotMatchError());
/**
* SafetyDepositBoxVaultMismatch: 'This safety deposit box does not belong to this vault!'
*
* @category Errors
* @category generated
*/
export class SafetyDepositBoxVaultMismatchError extends Error {
readonly code: number = 0x27;
readonly name: string = 'SafetyDepositBoxVaultMismatch';
constructor() {
super('This safety deposit box does not belong to this vault!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SafetyDepositBoxVaultMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x27, () => new SafetyDepositBoxVaultMismatchError());
createErrorFromNameLookup.set(
'SafetyDepositBoxVaultMismatch',
() => new SafetyDepositBoxVaultMismatchError(),
);
/**
* StoreDoesNotMatchSafetyDepositBox: 'The store provided does not match the store key on the safety deposit box!'
*
* @category Errors
* @category generated
*/
export class StoreDoesNotMatchSafetyDepositBoxError extends Error {
readonly code: number = 0x28;
readonly name: string = 'StoreDoesNotMatchSafetyDepositBox';
constructor() {
super('The store provided does not match the store key on the safety deposit box!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, StoreDoesNotMatchSafetyDepositBoxError);
}
}
}
createErrorFromCodeLookup.set(0x28, () => new StoreDoesNotMatchSafetyDepositBoxError());
createErrorFromNameLookup.set(
'StoreDoesNotMatchSafetyDepositBox',
() => new StoreDoesNotMatchSafetyDepositBoxError(),
);
/**
* StoreEmpty: 'This safety deposit box is empty!'
*
* @category Errors
* @category generated
*/
export class StoreEmptyError extends Error {
readonly code: number = 0x29;
readonly name: string = 'StoreEmpty';
constructor() {
super('This safety deposit box is empty!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, StoreEmptyError);
}
}
}
createErrorFromCodeLookup.set(0x29, () => new StoreEmptyError());
createErrorFromNameLookup.set('StoreEmpty', () => new StoreEmptyError());
/**
* DestinationAccountNeedsToMatchTokenMint: 'The destination account to receive your token needs to be the same mint as the token's mint'
*
* @category Errors
* @category generated
*/
export class DestinationAccountNeedsToMatchTokenMintError extends Error {
readonly code: number = 0x2a;
readonly name: string = 'DestinationAccountNeedsToMatchTokenMint';
constructor() {
super(
"The destination account to receive your token needs to be the same mint as the token's mint",
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DestinationAccountNeedsToMatchTokenMintError);
}
}
}
createErrorFromCodeLookup.set(0x2a, () => new DestinationAccountNeedsToMatchTokenMintError());
createErrorFromNameLookup.set(
'DestinationAccountNeedsToMatchTokenMint',
() => new DestinationAccountNeedsToMatchTokenMintError(),
);
/**
* DestinationAccountNeedsToMatchFractionMint: 'The destination account to receive your shares needs to be the same mint as the vault's fraction mint'
*
* @category Errors
* @category generated
*/
export class DestinationAccountNeedsToMatchFractionMintError extends Error {
readonly code: number = 0x2b;
readonly name: string = 'DestinationAccountNeedsToMatchFractionMint';
constructor() {
super(
"The destination account to receive your shares needs to be the same mint as the vault's fraction mint",
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DestinationAccountNeedsToMatchFractionMintError);
}
}
}
createErrorFromCodeLookup.set(0x2b, () => new DestinationAccountNeedsToMatchFractionMintError());
createErrorFromNameLookup.set(
'DestinationAccountNeedsToMatchFractionMint',
() => new DestinationAccountNeedsToMatchFractionMintError(),
);
/**
* SourceAccountNeedsToMatchFractionMint: 'The source account to send your shares from needs to be the same mint as the vault's fraction mint'
*
* @category Errors
* @category generated
*/
export class SourceAccountNeedsToMatchFractionMintError extends Error {
readonly code: number = 0x2c;
readonly name: string = 'SourceAccountNeedsToMatchFractionMint';
constructor() {
super(
"The source account to send your shares from needs to be the same mint as the vault's fraction mint",
);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SourceAccountNeedsToMatchFractionMintError);
}
}
}
createErrorFromCodeLookup.set(0x2c, () => new SourceAccountNeedsToMatchFractionMintError());
createErrorFromNameLookup.set(
'SourceAccountNeedsToMatchFractionMint',
() => new SourceAccountNeedsToMatchFractionMintError(),
);
/**
* VaultDoesNotAllowNewShareMinting: 'This vault does not allow the minting of new shares!'
*
* @category Errors
* @category generated
*/
export class VaultDoesNotAllowNewShareMintingError extends Error {
readonly code: number = 0x2d;
readonly name: string = 'VaultDoesNotAllowNewShareMinting';
constructor() {
super('This vault does not allow the minting of new shares!');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, VaultDoesNotAllowNewShareMintingError);
}
}
}
createErrorFromCodeLookup.set(0x2d, () => new VaultDoesNotAllowNewShareMintingError());
createErrorFromNameLookup.set(
'VaultDoesNotAllowNewShareMinting',
() => new VaultDoesNotAllowNewShareMintingError(),
);
/**
* NotEnoughShares: 'There are not enough shares'
*
* @category Errors
* @category generated
*/
export class NotEnoughSharesError extends Error {
readonly code: number = 0x2e;
readonly name: string = 'NotEnoughShares';
constructor() {
super('There are not enough shares');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NotEnoughSharesError);
}
}
}
createErrorFromCodeLookup.set(0x2e, () => new NotEnoughSharesError());
createErrorFromNameLookup.set('NotEnoughShares', () => new NotEnoughSharesError());
/**
* ExternalPriceAccountMustBeSigner: 'External price account must be signer'
*
* @category Errors
* @category generated
*/
export class ExternalPriceAccountMustBeSignerError extends Error {
readonly code: number = 0x2f;
readonly name: string = 'ExternalPriceAccountMustBeSigner';
constructor() {
super('External price account must be signer');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ExternalPriceAccountMustBeSignerError);
}
}
}
createErrorFromCodeLookup.set(0x2f, () => new ExternalPriceAccountMustBeSignerError());
createErrorFromNameLookup.set(
'ExternalPriceAccountMustBeSigner',
() => new ExternalPriceAccountMustBeSignerError(),
);
/**
* RedeemTreasuryMintShouldMatchPricingMint: 'Very bad, someone changed external account's price mint after vault creation!'
*
* @category Errors
* @category generated
*/
export class RedeemTreasuryMintShouldMatchPricingMintError extends Error {
readonly code: number = 0x30;
readonly name: string = 'RedeemTreasuryMintShouldMatchPricingMint';
constructor() {
super("Very bad, someone changed external account's price mint after vault creation!");
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, RedeemTreasuryMintShouldMatchPricingMintError);
}
}
}
createErrorFromCodeLookup.set(0x30, () => new RedeemTreasuryMintShouldMatchPricingMintError());
createErrorFromNameLookup.set(
'RedeemTreasuryMintShouldMatchPricingMint',
() => new RedeemTreasuryMintShouldMatchPricingMintError(),
);
/**
* StoreLessThanAmount: 'Store has less than amount desired'
*
* @category Errors
* @category generated
*/
export class StoreLessThanAmountError extends Error {
readonly code: number = 0x31;
readonly name: string = 'StoreLessThanAmount';
constructor() {
super('Store has less than amount desired');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, StoreLessThanAmountError);
}
}
}
createErrorFromCodeLookup.set(0x31, () => new StoreLessThanAmountError());
createErrorFromNameLookup.set('StoreLessThanAmount', () => new StoreLessThanAmountError());
/**
* InvalidTokenProgram: 'Invalid token program'
*
* @category Errors
* @category generated
*/
export class InvalidTokenProgramError extends Error {
readonly code: number = 0x32;
readonly name: string = 'InvalidTokenProgram';
constructor() {
super('Invalid token program');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidTokenProgramError);
}
}
}
createErrorFromCodeLookup.set(0x32, () => new InvalidTokenProgramError());
createErrorFromNameLookup.set('InvalidTokenProgram', () => new InvalidTokenProgramError());
/**
* DataTypeMismatch: 'Data type mismatch'
*
* @category Errors
* @category generated
*/
export class DataTypeMismatchError extends Error {
readonly code: number = 0x33;
readonly name: string = 'DataTypeMismatch';
constructor() {
super('Data type mismatch');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DataTypeMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x33, () => new DataTypeMismatchError());
createErrorFromNameLookup.set('DataTypeMismatch', () => new DataTypeMismatchError());
/**
* DelegateShouldBeNone: 'Accept payment delegate should be none'
*
* @category Errors
* @category generated
*/
export class DelegateShouldBeNoneError extends Error {
readonly code: number = 0x34;
readonly name: string = 'DelegateShouldBeNone';
constructor() {
super('Accept payment delegate should be none');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DelegateShouldBeNoneError);
}
}
}
createErrorFromCodeLookup.set(0x34, () => new DelegateShouldBeNoneError());
createErrorFromNameLookup.set('DelegateShouldBeNone', () => new DelegateShouldBeNoneError());
/**
* CloseAuthorityShouldBeNone: 'Accept payment close authority should be none'
*
* @category Errors
* @category generated
*/
export class CloseAuthorityShouldBeNoneError extends Error {
readonly code: number = 0x35;
readonly name: string = 'CloseAuthorityShouldBeNone';
constructor() {
super('Accept payment close authority should be none');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CloseAuthorityShouldBeNoneError);
}
}
}
createErrorFromCodeLookup.set(0x35, () => new CloseAuthorityShouldBeNoneError());
createErrorFromNameLookup.set(
'CloseAuthorityShouldBeNone',
() => new CloseAuthorityShouldBeNoneError(),
);
/**
* DerivedKeyInvalid: 'Derived key invalid'
*
* @category Errors
* @category generated
*/
export class DerivedKeyInvalidError extends Error {
readonly code: number = 0x36;
readonly name: string = 'DerivedKeyInvalid';
constructor() {
super('Derived key invalid');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DerivedKeyInvalidError);
}
}
}
createErrorFromCodeLookup.set(0x36, () => new DerivedKeyInvalidError());
createErrorFromNameLookup.set('DerivedKeyInvalid', () => new DerivedKeyInvalidError());
/**
* Attempts to resolve a custom program error from the provided error code.
* @category Errors
* @category generated
*/
export function errorFromCode(code: number): MaybeErrorWithCode {
const createError = createErrorFromCodeLookup.get(code);
return createError != null ? createError() : null;
}
/**
* Attempts to resolve a custom program error from the provided error name, i.e. 'Unauthorized'.
* @category Errors
* @category generated
*/
export function errorFromName(name: string): MaybeErrorWithCode {
const createError = createErrorFromNameLookup.get(name);
return createError != null ? createError() : null;
} | the_stack |
import * as KissFFT from 'kissfft-js';
import * as DCT from 'dct';
const SR = 44100;
let melFilterbank = null;
let context = null;
export default class AudioUtils {
static loadExampleBuffer() {
return AudioUtils.loadBuffer('assets/spoken_command_example.wav');
}
static loadSineBuffer() {
return AudioUtils.loadBuffer('assets/sine_100ms_example.wav');
}
static loadBuffer(url: string) {
if (!context) {
context = new AudioContext();
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
// Load an example of speech being spoken.
xhr.open('GET', url);
xhr.onload = () => {
context.decodeAudioData(xhr.response, buffer => {
resolve(buffer);
})
};
xhr.responseType = 'arraybuffer';
xhr.onerror = (err) => reject(err);
xhr.send();
});
}
static async loadBufferOffline(url: string) {
const offlineCtx = new OfflineAudioContext(1, 16000, 16000);
return fetch(url).then(body => body.arrayBuffer())
.then(buffer => offlineCtx.decodeAudioData(buffer));
}
/**
* Calculates the FFT for an array buffer. Output is an array.
*/
static fft(y: Float32Array) {
const fftr = new KissFFT.FFTR(y.length);
const transform = fftr.forward(y);
fftr.dispose();
return transform;
}
static dct(y: Float32Array) {
return DCT(y);
}
/**
* Calculates the STFT, given a fft size, and a hop size. For example, if fft
* size is 2048 and hop size is 1024, there will be 50% overlap. Given those
* params, if the input sample has 4096 values, there would be 3 analysis
* frames: [0, 2048], [1024, 3072], [2048, 4096].
*/
static stft(y: Float32Array, fftSize=2048, hopSize=fftSize) {
// Split the input buffer into sub-buffers of size fftSize.
const bufferCount = Math.floor((y.length - fftSize) / hopSize) + 1;
let matrix = range(bufferCount).map(x => new Float32Array(fftSize));
for (let i = 0; i < bufferCount; i++) {
const ind = i * hopSize;
const buffer = y.slice(ind, ind + fftSize);
// In the end, we will likely have an incomplete buffer, which we should
// just ignore.
if (buffer.length != fftSize) {
continue;
}
const win = AudioUtils.hannWindow(buffer.length);
const winBuffer = AudioUtils.applyWindow(buffer, win);
const fft = AudioUtils.fft(winBuffer);
// TODO: Understand why fft output is 2 larger than expected (eg. 1026
// rather than 1024).
matrix[i].set(fft.slice(0, fftSize));
}
return matrix;
}
/**
* Given STFT energies, calculates the mel spectrogram.
*/
static melSpectrogram(stftEnergies: Float32Array[],
melCount=20, lowHz=300, highHz=8000, sr=SR) {
this.lazyCreateMelFilterbank(stftEnergies[0].length, melCount, lowHz, highHz, sr);
// For each fft slice, calculate the corresponding mel values.
const out = [];
for (let i = 0; i < stftEnergies.length; i++) {
out[i] = AudioUtils.applyFilterbank(stftEnergies[i], melFilterbank);
}
return out;
}
/**
* Given STFT energies, calculates the MFCC spectrogram.
*/
static mfccSpectrogram(stftEnergies: Float32Array[], melCount=20) {
// For each fft slice, calculate the corresponding MFCC values.
const out = [];
for (let i = 0; i < stftEnergies.length; i++) {
out[i] = this.mfcc(stftEnergies[i], melCount);
}
return out;
}
static lazyCreateMelFilterbank(length: number, melCount=20, lowHz=300, highHz=8000, sr=SR) {
// Lazy-create a Mel filterbank.
if (!melFilterbank || melFilterbank.length != length) {
melFilterbank = this.createMelFilterbank(length, melCount, lowHz, highHz, sr);
}
}
/**
* Given an interlaced complex array (y_i is real, y_(i+1) is imaginary),
* calculates the magnitudes. Output is half the size.
*/
static fftMags(y: Float32Array) {
let out = new Float32Array(y.length / 2);
for (let i = 0; i < y.length / 2; i++) {
out[i] = Math.hypot(y[i*2], y[i*2 + 1]);
}
return out;
}
/**
* Given an interlaced complex array (y_i is real, y_(i+1) is imaginary),
* calculates the energies. Output is half the size.
*/
static fftEnergies(y: Float32Array) {
let out = new Float32Array(y.length / 2);
for (let i = 0; i < y.length / 2; i++) {
out[i] = y[i*2]*y[i*2] + y[i*2 + 1]*y[i*2 + 1];
}
return out;
}
/**
* Generates a Hann window of a given length.
*/
static hannWindow(length: number) {
let win = new Float32Array(length);
for (let i = 0; i < length; i++) {
win[i] = 0.5 * (1 - Math.cos(2 * Math.PI * i / (length - 1)));
}
return win;
}
/**
* Applies a window to a buffer (point-wise multiplication).
*/
static applyWindow(buffer, win) {
if (buffer.length != win.length) {
console.error(`Buffer length ${buffer.length} != window length
${win.length}.`);
return;
}
let out = new Float32Array(buffer.length);
for (let i = 0; i < buffer.length; i++) {
out[i] = win[i] * buffer[i];
}
return out;
}
static pointWiseMultiply(out: Float32Array,
array1: Float32Array, array2: Float32Array) {
if (out.length != array1.length || array1.length != array2.length) {
console.error(`Output length ${out.length} != array1 length
${array1.length} != array2 length ${array2.length}.`);
return;
}
for (let i = 0; i < out.length; i++) {
out[i] = array1[i] * array2[i];
}
return out;
}
static createMelFilterbank(fftSize, melCount=20, lowHz=300, highHz=8000, sr=SR) {
const lowMel = this.hzToMel(lowHz);
const highMel = this.hzToMel(highHz);
// Construct linearly spaced array of melCount intervals, between lowMel and
// highMel.
const mels = linearSpace(lowMel, highMel, melCount + 2);
// Convert from mels to hz.
const hzs = mels.map(mel => this.melToHz(mel));
// Go from hz to the corresponding bin in the FFT.
const bins = hzs.map(hz => this.freqToBin(hz, fftSize));
// Now that we have the start and end frequencies, create each triangular
// window (each value in [0, 1]) that we will apply to an FFT later. These
// are mostly sparse, except for the values of the triangle
const length = bins.length - 2;
const filters = [];
for (let i = 0; i < length; i++) {
// Now generate the triangles themselves.
filters[i] = this.triangleWindow(fftSize, bins[i], bins[i+1], bins[i+2]);
}
return filters;
}
/**
* Given an array of FFT magnitudes, apply a filterbank. Output should be an
* array with size |filterbank|.
*/
static applyFilterbank(fftEnergies: Float32Array, filterbank: Float32Array[])
: Float32Array {
if (fftEnergies.length != filterbank[0].length) {
console.error(`Each entry in filterbank should have dimensions matching
FFT. |FFT| = ${fftEnergies.length}, |filterbank[0]| = ${filterbank[0].length}.`);
return;
}
// Apply each filter to the whole FFT signal to get one value.
let out = new Float32Array(filterbank.length);
for (let i = 0; i < filterbank.length; i++) {
// To calculate filterbank energies we multiply each filterbank with the
// power spectrum.
const win = AudioUtils.applyWindow(fftEnergies, filterbank[i]);
// Then add up the coefficents, and take the log.
out[i] = logGtZero(sum(win));
}
return out;
}
static hzToMel(hz) {
return 1125 * Math.log(1 + hz/700);
}
static melToHz(mel) {
return 700 * (Math.exp(mel/1125) - 1);
}
static freqToBin(freq, fftSize, sr=SR) {
return Math.floor((fftSize+1) * freq / (sr/2));
}
/**
* Creates a triangular window.
*/
static triangleWindow(length, startIndex, peakIndex, endIndex) {
const win = new Float32Array(length);
const deltaUp = 1.0 / (peakIndex - startIndex);
for (let i = startIndex; i < peakIndex; i++) {
// Linear ramp up between start and peak index (values from 0 to 1).
win[i] = (i - startIndex) * deltaUp;
}
const deltaDown = 1.0 / (endIndex - peakIndex);
for (let i = peakIndex; i < endIndex; i++) {
// Linear ramp down between peak and end index (values from 1 to 0).
win[i] = 1 - (i - peakIndex) * deltaDown;
}
return win;
}
static cepstrumFromEnergySpectrum(melEnergies: Float32Array) {
return this.dct(melEnergies);
}
/**
* Calculate MFC coefficients from FFT energies.
*/
static mfcc(fftEnergies: Float32Array, melCount=20, lowHz=300, highHz=8000, sr=SR) {
this.lazyCreateMelFilterbank(fftEnergies.length, melCount, lowHz, highHz, sr);
// Apply the mel filterbank to the FFT magnitudes.
const melEnergies = this.applyFilterbank(fftEnergies, melFilterbank);
// Go from mel coefficients to MFCC.
return this.cepstrumFromEnergySpectrum(melEnergies);
}
static normalizeSpecInPlace(spec, normMin=0, normMax=1) {
let min = Infinity;
let max = -Infinity;
const times = spec.length;
const freqs = spec[0].length;
for (let i = 0; i < times; i++) {
for (let j = 0; j < freqs; j++) {
const val = spec[i][j];
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
}
const scale = (normMax - normMin) / (max - min);
const offset = normMin - min;
for (let i = 0; i < times; i++) {
for (let j = 0; j < freqs; j++) {
// Get a normalized value in [0, 1].
const norm = (spec[i][j] - min) / (max - min);
// Then convert it to the desired range.
spec[i][j] = normMin + norm * (normMax - normMin);
}
}
}
static playbackArrayBuffer(buffer: Float32Array, sampleRate?: number) {
if (!context) {
context = new AudioContext();
}
if (!sampleRate) {
sampleRate = context.sampleRate;
}
const audioBuffer = context.createBuffer(1, buffer.length, sampleRate);
const audioBufferData = audioBuffer.getChannelData(0);
audioBufferData.set(buffer);
const source = context.createBufferSource();
source.buffer = audioBuffer;
source.connect(context.destination);
source.start();
}
}
function linearSpace(start, end, count) {
const delta = (end - start) / (count + 1);
let out = [];
for (let i = 0; i < count; i++) {
out[i] = start + delta * i;
}
return out;
}
function sum(array) {
return array.reduce(function(a, b) { return a + b; });
}
function range(count) : number[] {
let out = [];
for (let i = 0; i < count; i++) {
out.push(i);
}
return out;
}
// Use a lower minimum value for energy.
const MIN_VAL = -10;
function logGtZero(val) {
// Ensure that the log argument is nonnegative.
const offset = Math.exp(MIN_VAL);
return Math.log(val + offset);
} | the_stack |
type ErrorWithCode = Error & { code: number };
type MaybeErrorWithCode = ErrorWithCode | null | undefined;
const createErrorFromCodeLookup: Map<number, () => ErrorWithCode> = new Map();
const createErrorFromNameLookup: Map<string, () => ErrorWithCode> = new Map();
/**
* NoValidSignerPresent: 'No valid signer present'
*/
export class NoValidSignerPresentError extends Error {
readonly code: number = 0x1770;
readonly name: string = 'NoValidSignerPresent';
constructor() {
super('No valid signer present');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NoValidSignerPresentError);
}
}
}
createErrorFromCodeLookup.set(0x1770, () => new NoValidSignerPresentError());
createErrorFromNameLookup.set('NoValidSignerPresent', () => new NoValidSignerPresentError());
/**
* StringIsTooLong: 'Some string variable is longer than allowed'
*/
export class StringIsTooLongError extends Error {
readonly code: number = 0x1771;
readonly name: string = 'StringIsTooLong';
constructor() {
super('Some string variable is longer than allowed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, StringIsTooLongError);
}
}
}
createErrorFromCodeLookup.set(0x1771, () => new StringIsTooLongError());
createErrorFromNameLookup.set('StringIsTooLong', () => new StringIsTooLongError());
/**
* NameIsTooLong: 'Name string variable is longer than allowed'
*/
export class NameIsTooLongError extends Error {
readonly code: number = 0x1772;
readonly name: string = 'NameIsTooLong';
constructor() {
super('Name string variable is longer than allowed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, NameIsTooLongError);
}
}
}
createErrorFromCodeLookup.set(0x1772, () => new NameIsTooLongError());
createErrorFromNameLookup.set('NameIsTooLong', () => new NameIsTooLongError());
/**
* DescriptionIsTooLong: 'Description string variable is longer than allowed'
*/
export class DescriptionIsTooLongError extends Error {
readonly code: number = 0x1773;
readonly name: string = 'DescriptionIsTooLong';
constructor() {
super('Description string variable is longer than allowed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DescriptionIsTooLongError);
}
}
}
createErrorFromCodeLookup.set(0x1773, () => new DescriptionIsTooLongError());
createErrorFromNameLookup.set('DescriptionIsTooLong', () => new DescriptionIsTooLongError());
/**
* SupplyIsGtThanAvailable: 'Provided supply is gt than available'
*/
export class SupplyIsGtThanAvailableError extends Error {
readonly code: number = 0x1774;
readonly name: string = 'SupplyIsGtThanAvailable';
constructor() {
super('Provided supply is gt than available');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SupplyIsGtThanAvailableError);
}
}
}
createErrorFromCodeLookup.set(0x1774, () => new SupplyIsGtThanAvailableError());
createErrorFromNameLookup.set('SupplyIsGtThanAvailable', () => new SupplyIsGtThanAvailableError());
/**
* SupplyIsNotProvided: 'Supply is not provided'
*/
export class SupplyIsNotProvidedError extends Error {
readonly code: number = 0x1775;
readonly name: string = 'SupplyIsNotProvided';
constructor() {
super('Supply is not provided');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SupplyIsNotProvidedError);
}
}
}
createErrorFromCodeLookup.set(0x1775, () => new SupplyIsNotProvidedError());
createErrorFromNameLookup.set('SupplyIsNotProvided', () => new SupplyIsNotProvidedError());
/**
* DerivedKeyInvalid: 'Derived key invalid'
*/
export class DerivedKeyInvalidError extends Error {
readonly code: number = 0x1776;
readonly name: string = 'DerivedKeyInvalid';
constructor() {
super('Derived key invalid');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DerivedKeyInvalidError);
}
}
}
createErrorFromCodeLookup.set(0x1776, () => new DerivedKeyInvalidError());
createErrorFromNameLookup.set('DerivedKeyInvalid', () => new DerivedKeyInvalidError());
/**
* SellingResourceOwnerInvalid: 'Invalid selling resource owner provided'
*/
export class SellingResourceOwnerInvalidError extends Error {
readonly code: number = 0x1777;
readonly name: string = 'SellingResourceOwnerInvalid';
constructor() {
super('Invalid selling resource owner provided');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SellingResourceOwnerInvalidError);
}
}
}
createErrorFromCodeLookup.set(0x1777, () => new SellingResourceOwnerInvalidError());
createErrorFromNameLookup.set(
'SellingResourceOwnerInvalid',
() => new SellingResourceOwnerInvalidError(),
);
/**
* PublicKeyMismatch: 'PublicKeyMismatch'
*/
export class PublicKeyMismatchError extends Error {
readonly code: number = 0x1778;
readonly name: string = 'PublicKeyMismatch';
constructor() {
super('PublicKeyMismatch');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PublicKeyMismatchError);
}
}
}
createErrorFromCodeLookup.set(0x1778, () => new PublicKeyMismatchError());
createErrorFromNameLookup.set('PublicKeyMismatch', () => new PublicKeyMismatchError());
/**
* PiecesInOneWalletIsTooMuch: 'Pieces in one wallet cannot be greater than Max Supply value'
*/
export class PiecesInOneWalletIsTooMuchError extends Error {
readonly code: number = 0x1779;
readonly name: string = 'PiecesInOneWalletIsTooMuch';
constructor() {
super('Pieces in one wallet cannot be greater than Max Supply value');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PiecesInOneWalletIsTooMuchError);
}
}
}
createErrorFromCodeLookup.set(0x1779, () => new PiecesInOneWalletIsTooMuchError());
createErrorFromNameLookup.set(
'PiecesInOneWalletIsTooMuch',
() => new PiecesInOneWalletIsTooMuchError(),
);
/**
* StartDateIsInPast: 'StartDate cannot be in the past'
*/
export class StartDateIsInPastError extends Error {
readonly code: number = 0x177a;
readonly name: string = 'StartDateIsInPast';
constructor() {
super('StartDate cannot be in the past');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, StartDateIsInPastError);
}
}
}
createErrorFromCodeLookup.set(0x177a, () => new StartDateIsInPastError());
createErrorFromNameLookup.set('StartDateIsInPast', () => new StartDateIsInPastError());
/**
* EndDateIsEarlierThanBeginDate: 'EndDate should not be earlier than StartDate'
*/
export class EndDateIsEarlierThanBeginDateError extends Error {
readonly code: number = 0x177b;
readonly name: string = 'EndDateIsEarlierThanBeginDate';
constructor() {
super('EndDate should not be earlier than StartDate');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, EndDateIsEarlierThanBeginDateError);
}
}
}
createErrorFromCodeLookup.set(0x177b, () => new EndDateIsEarlierThanBeginDateError());
createErrorFromNameLookup.set(
'EndDateIsEarlierThanBeginDate',
() => new EndDateIsEarlierThanBeginDateError(),
);
/**
* IncorrectOwner: 'Incorrect account owner'
*/
export class IncorrectOwnerError extends Error {
readonly code: number = 0x177c;
readonly name: string = 'IncorrectOwner';
constructor() {
super('Incorrect account owner');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, IncorrectOwnerError);
}
}
}
createErrorFromCodeLookup.set(0x177c, () => new IncorrectOwnerError());
createErrorFromNameLookup.set('IncorrectOwner', () => new IncorrectOwnerError());
/**
* MarketIsNotStarted: 'Market is not started'
*/
export class MarketIsNotStartedError extends Error {
readonly code: number = 0x177d;
readonly name: string = 'MarketIsNotStarted';
constructor() {
super('Market is not started');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MarketIsNotStartedError);
}
}
}
createErrorFromCodeLookup.set(0x177d, () => new MarketIsNotStartedError());
createErrorFromNameLookup.set('MarketIsNotStarted', () => new MarketIsNotStartedError());
/**
* MarketIsEnded: 'Market is ended'
*/
export class MarketIsEndedError extends Error {
readonly code: number = 0x177e;
readonly name: string = 'MarketIsEnded';
constructor() {
super('Market is ended');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MarketIsEndedError);
}
}
}
createErrorFromCodeLookup.set(0x177e, () => new MarketIsEndedError());
createErrorFromNameLookup.set('MarketIsEnded', () => new MarketIsEndedError());
/**
* UserReachBuyLimit: 'User reach buy limit'
*/
export class UserReachBuyLimitError extends Error {
readonly code: number = 0x177f;
readonly name: string = 'UserReachBuyLimit';
constructor() {
super('User reach buy limit');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UserReachBuyLimitError);
}
}
}
createErrorFromCodeLookup.set(0x177f, () => new UserReachBuyLimitError());
createErrorFromNameLookup.set('UserReachBuyLimit', () => new UserReachBuyLimitError());
/**
* MathOverflow: 'Math overflow'
*/
export class MathOverflowError extends Error {
readonly code: number = 0x1780;
readonly name: string = 'MathOverflow';
constructor() {
super('Math overflow');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MathOverflowError);
}
}
}
createErrorFromCodeLookup.set(0x1780, () => new MathOverflowError());
createErrorFromNameLookup.set('MathOverflow', () => new MathOverflowError());
/**
* SupplyIsGtThanMaxSupply: 'Supply is gt than max supply'
*/
export class SupplyIsGtThanMaxSupplyError extends Error {
readonly code: number = 0x1781;
readonly name: string = 'SupplyIsGtThanMaxSupply';
constructor() {
super('Supply is gt than max supply');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SupplyIsGtThanMaxSupplyError);
}
}
}
createErrorFromCodeLookup.set(0x1781, () => new SupplyIsGtThanMaxSupplyError());
createErrorFromNameLookup.set('SupplyIsGtThanMaxSupply', () => new SupplyIsGtThanMaxSupplyError());
/**
* MarketDurationIsNotUnlimited: 'Market duration is not unlimited'
*/
export class MarketDurationIsNotUnlimitedError extends Error {
readonly code: number = 0x1782;
readonly name: string = 'MarketDurationIsNotUnlimited';
constructor() {
super('Market duration is not unlimited');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MarketDurationIsNotUnlimitedError);
}
}
}
createErrorFromCodeLookup.set(0x1782, () => new MarketDurationIsNotUnlimitedError());
createErrorFromNameLookup.set(
'MarketDurationIsNotUnlimited',
() => new MarketDurationIsNotUnlimitedError(),
);
/**
* MarketIsSuspended: 'Market is suspended'
*/
export class MarketIsSuspendedError extends Error {
readonly code: number = 0x1783;
readonly name: string = 'MarketIsSuspended';
constructor() {
super('Market is suspended');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MarketIsSuspendedError);
}
}
}
createErrorFromCodeLookup.set(0x1783, () => new MarketIsSuspendedError());
createErrorFromNameLookup.set('MarketIsSuspended', () => new MarketIsSuspendedError());
/**
* MarketIsImmutable: 'Market is immutable'
*/
export class MarketIsImmutableError extends Error {
readonly code: number = 0x1784;
readonly name: string = 'MarketIsImmutable';
constructor() {
super('Market is immutable');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MarketIsImmutableError);
}
}
}
createErrorFromCodeLookup.set(0x1784, () => new MarketIsImmutableError());
createErrorFromNameLookup.set('MarketIsImmutable', () => new MarketIsImmutableError());
/**
* MarketInInvalidState: 'Market in invalid state'
*/
export class MarketInInvalidStateError extends Error {
readonly code: number = 0x1785;
readonly name: string = 'MarketInInvalidState';
constructor() {
super('Market in invalid state');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MarketInInvalidStateError);
}
}
}
createErrorFromCodeLookup.set(0x1785, () => new MarketInInvalidStateError());
createErrorFromNameLookup.set('MarketInInvalidState', () => new MarketInInvalidStateError());
/**
* PriceIsZero: 'Price is zero'
*/
export class PriceIsZeroError extends Error {
readonly code: number = 0x1786;
readonly name: string = 'PriceIsZero';
constructor() {
super('Price is zero');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PriceIsZeroError);
}
}
}
createErrorFromCodeLookup.set(0x1786, () => new PriceIsZeroError());
createErrorFromNameLookup.set('PriceIsZero', () => new PriceIsZeroError());
/**
* FunderIsInvalid: 'Funder is invalid'
*/
export class FunderIsInvalidError extends Error {
readonly code: number = 0x1787;
readonly name: string = 'FunderIsInvalid';
constructor() {
super('Funder is invalid');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, FunderIsInvalidError);
}
}
}
createErrorFromCodeLookup.set(0x1787, () => new FunderIsInvalidError());
createErrorFromNameLookup.set('FunderIsInvalid', () => new FunderIsInvalidError());
/**
* PayoutTicketExists: 'Payout ticket exists'
*/
export class PayoutTicketExistsError extends Error {
readonly code: number = 0x1788;
readonly name: string = 'PayoutTicketExists';
constructor() {
super('Payout ticket exists');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PayoutTicketExistsError);
}
}
}
createErrorFromCodeLookup.set(0x1788, () => new PayoutTicketExistsError());
createErrorFromNameLookup.set('PayoutTicketExists', () => new PayoutTicketExistsError());
/**
* InvalidFunderDestination: 'Funder provide invalid destination'
*/
export class InvalidFunderDestinationError extends Error {
readonly code: number = 0x1789;
readonly name: string = 'InvalidFunderDestination';
constructor() {
super('Funder provide invalid destination');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, InvalidFunderDestinationError);
}
}
}
createErrorFromCodeLookup.set(0x1789, () => new InvalidFunderDestinationError());
createErrorFromNameLookup.set(
'InvalidFunderDestination',
() => new InvalidFunderDestinationError(),
);
/**
* TreasuryIsNotEmpty: 'Treasury is not empty'
*/
export class TreasuryIsNotEmptyError extends Error {
readonly code: number = 0x178a;
readonly name: string = 'TreasuryIsNotEmpty';
constructor() {
super('Treasury is not empty');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, TreasuryIsNotEmptyError);
}
}
}
createErrorFromCodeLookup.set(0x178a, () => new TreasuryIsNotEmptyError());
createErrorFromNameLookup.set('TreasuryIsNotEmpty', () => new TreasuryIsNotEmptyError());
/**
* SellingResourceInInvalidState: 'Selling resource in invalid state'
*/
export class SellingResourceInInvalidStateError extends Error {
readonly code: number = 0x178b;
readonly name: string = 'SellingResourceInInvalidState';
constructor() {
super('Selling resource in invalid state');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, SellingResourceInInvalidStateError);
}
}
}
createErrorFromCodeLookup.set(0x178b, () => new SellingResourceInInvalidStateError());
createErrorFromNameLookup.set(
'SellingResourceInInvalidState',
() => new SellingResourceInInvalidStateError(),
);
/**
* MetadataCreatorsIsEmpty: 'Metadata creators is empty'
*/
export class MetadataCreatorsIsEmptyError extends Error {
readonly code: number = 0x178c;
readonly name: string = 'MetadataCreatorsIsEmpty';
constructor() {
super('Metadata creators is empty');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MetadataCreatorsIsEmptyError);
}
}
}
createErrorFromCodeLookup.set(0x178c, () => new MetadataCreatorsIsEmptyError());
createErrorFromNameLookup.set('MetadataCreatorsIsEmpty', () => new MetadataCreatorsIsEmptyError());
/**
* UserWalletMustMatchUserTokenAccount: 'User wallet must match user token account'
*/
export class UserWalletMustMatchUserTokenAccountError extends Error {
readonly code: number = 0x178d;
readonly name: string = 'UserWalletMustMatchUserTokenAccount';
constructor() {
super('User wallet must match user token account');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, UserWalletMustMatchUserTokenAccountError);
}
}
}
createErrorFromCodeLookup.set(0x178d, () => new UserWalletMustMatchUserTokenAccountError());
createErrorFromNameLookup.set(
'UserWalletMustMatchUserTokenAccount',
() => new UserWalletMustMatchUserTokenAccountError(),
);
/**
* MetadataShouldBeMutable: 'Metadata should be mutable'
*/
export class MetadataShouldBeMutableError extends Error {
readonly code: number = 0x178e;
readonly name: string = 'MetadataShouldBeMutable';
constructor() {
super('Metadata should be mutable');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, MetadataShouldBeMutableError);
}
}
}
createErrorFromCodeLookup.set(0x178e, () => new MetadataShouldBeMutableError());
createErrorFromNameLookup.set('MetadataShouldBeMutable', () => new MetadataShouldBeMutableError());
/**
* PrimarySaleIsNotAllowed: 'Primary sale is not allowed'
*/
export class PrimarySaleIsNotAllowedError extends Error {
readonly code: number = 0x178f;
readonly name: string = 'PrimarySaleIsNotAllowed';
constructor() {
super('Primary sale is not allowed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, PrimarySaleIsNotAllowedError);
}
}
}
createErrorFromCodeLookup.set(0x178f, () => new PrimarySaleIsNotAllowedError());
createErrorFromNameLookup.set('PrimarySaleIsNotAllowed', () => new PrimarySaleIsNotAllowedError());
/**
* CreatorsIsGtThanAvailable: 'Creators is gt than allowed'
*/
export class CreatorsIsGtThanAvailableError extends Error {
readonly code: number = 0x1790;
readonly name: string = 'CreatorsIsGtThanAvailable';
constructor() {
super('Creators is gt than allowed');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CreatorsIsGtThanAvailableError);
}
}
}
createErrorFromCodeLookup.set(0x1790, () => new CreatorsIsGtThanAvailableError());
createErrorFromNameLookup.set(
'CreatorsIsGtThanAvailable',
() => new CreatorsIsGtThanAvailableError(),
);
/**
* CreatorsIsEmpty: 'Creators is empty'
*/
export class CreatorsIsEmptyError extends Error {
readonly code: number = 0x1791;
readonly name: string = 'CreatorsIsEmpty';
constructor() {
super('Creators is empty');
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, CreatorsIsEmptyError);
}
}
}
createErrorFromCodeLookup.set(0x1791, () => new CreatorsIsEmptyError());
createErrorFromNameLookup.set('CreatorsIsEmpty', () => new CreatorsIsEmptyError());
/**
* Attempts to resolve a custom program error from the provided error code.
*/
export function errorFromCode(code: number): MaybeErrorWithCode {
const createError = createErrorFromCodeLookup.get(code);
return createError != null ? createError() : null;
}
/**
* Attempts to resolve a custom program error from the provided error name, i.e. 'Unauthorized'.
*/
export function errorFromName(name: string): MaybeErrorWithCode {
const createError = createErrorFromNameLookup.get(name);
return createError != null ? createError() : null;
} | the_stack |
import React, {ChangeEvent} from "react";
import {OutputField, TypingField} from "../../generic/core";
import {Button, Container, Row, Col} from "helpers/reactstrap";
import ScanPresets from "./ScanPresets";
import {subscribe} from "helpers/pubsub";
import {FaSyncAlt} from "react-icons/fa";
import useLocalStorage from "helpers/hooks/useLocalStorage";
import {
Sensors,
Simulator,
SensorScan,
useSensorsSubscription,
useSensorsProbeDataMutation,
useSensorsProcessedDataMutation,
useSensorScanResultMutation,
useSensorsProbesQuery,
useSensorsSetHistoryMutation,
useSensorScanResponseMutation,
} from "generated/graphql";
import {ProcessedData} from "./";
interface SensorsCoreProps {
simulator: Simulator;
}
const SensorsCore: React.FC<SensorsCoreProps> = ({simulator}) => {
const [dataField, setDataField] = React.useState("");
const [selectedScan, setSelectedScan] = React.useState<string | null>(null);
const [processedDataHistory, setProcessedDataHistory] = React.useState(false);
const [domain, setDomain] = useLocalStorage("sensorCore-domain", "external");
React.useEffect(() => {
const unSub = subscribe("sensorData", (data: string) => {
setDataField(data);
});
return () => unSub();
}, []);
const [sendProbeData] = useSensorsProbeDataMutation();
const [sendProcessedDataMutation] = useSensorsProcessedDataMutation();
const [sendScanResultMutation] = useSensorScanResultMutation();
const [setScanHistory] = useSensorsSetHistoryMutation();
const [sensorScanResponseMutation] = useSensorScanResponseMutation();
const {loading, data} = useSensorsSubscription({
variables: {simulatorId: simulator.id},
});
const {data: probeQueryData} = useSensorsProbesQuery({
variables: {simulatorId: simulator.id},
});
if (loading || !data) return null;
const external = data.sensorsUpdate?.find(s => s.domain === "external");
const internal = data.sensorsUpdate?.find(s => s.domain === "internal");
const sensor = domain === "external" ? external : internal;
const probesId = probeQueryData?.probes?.[0]?.id;
if (!sensor) return <p>No Sensors</p>;
const scan = sensor.scans?.find(s => s?.id === selectedScan);
// componentDidUpdate(prevProps) {
// if (
// prevProps.data.loading ||
// this.props.data.loading ||
// !this.props.data.sensors
// )
// return;
// const external = this.props.data.sensors.find(s => s.domain === "external");
// const internal = this.props.data.sensors.find(s => s.domain === "internal");
// const sensor = this.state.domain === "external" ? external : internal;
// const oldExternal = prevProps.data.sensors.find(
// s => s.domain === "external",
// );
// const oldInternal = prevProps.data.sensors.find(
// s => s.domain === "internal",
// );
// const oldSensor =
// this.state.domain === "external" ? oldExternal : oldInternal;
// if (sensor.scanResults !== oldSensor.scanResults)
// this.setState({
// dataField: sensor.scanResults,
// });
// }
const sendScanResult = (sensors: Sensors) => {
if (sensors.history && selectedScan !== "basic-scan") {
if (!selectedScan) return;
sensorScanResponseMutation({
variables: {
id: sensors.id,
scan: {
id: selectedScan,
response: dataField,
},
},
});
return;
} else {
sendScanResultMutation({
variables: {
id: sensors.id,
result: dataField,
},
});
}
};
const sendProcessedData = (sensors: Sensors, flash: boolean = false) => {
sendProcessedDataMutation({
variables: {
id: sensors.id,
data: dataField,
flash,
},
});
};
const probeData = (flash: boolean = false) => {
probesId &&
sendProbeData({
variables: {
id: probesId,
data: dataField,
flash,
},
});
};
const setSensorsDomain = (which: string) => {
setDomain(which);
setSelectedScan(null);
};
const setSensorsHistory = (e: ChangeEvent<HTMLInputElement>) => {
setScanHistory({
variables: {
id: sensor.id,
history: e.target.checked,
},
});
};
const selectScan = ({id, response}: SensorScan) => {
setSelectedScan(id);
setDataField(response || "");
};
if (!sensor) return null;
if (processedDataHistory && external) {
return (
<Container className="sensor-core" style={{height: "100%"}}>
<Button
color="danger"
size="sm"
onClick={() => setProcessedDataHistory(false)}
>
Close
</Button>
<ProcessedData sensors={external} core={true} />
</Container>
);
}
return (
<Container className="sensor-core" style={{height: "100%"}}>
<Row>
<Button
size="sm"
className={`${domain === "external" ? "active" : ""} ${
external?.scanning ? "btn-danger" : ""
}`}
onClick={() => setSensorsDomain("external")}
>
External
</Button>
<Button
size="sm"
className={`${domain === "internal" ? "active" : ""} ${
internal?.scanning ? "btn-danger" : ""
}`}
onClick={() => setSensorsDomain("internal")}
>
Internal
</Button>
<label>
<input
type="checkbox"
checked={sensor.history || false}
onChange={setSensorsHistory}
/>
Scan History
</label>
{external && (
<Button
size="sm"
color="warning"
onClick={() => setProcessedDataHistory(true)}
>
Processed Data History
</Button>
)}
</Row>
<div className="scan-input-field">
<Row style={{flex: 1}}>
{sensor.history && (
<Col sm={4} style={{height: "100%"}}>
<div className="scan-list">
{sensor.scanning && (
<p
className={`${
selectedScan === "basic-scan" ? "selected" : ""
}`}
onClick={() =>
selectScan({
id: "basic-scan",
request: sensor.scanRequest || "",
})
}
>
{sensor.scanRequest?.substr(0, 15)}
... <FaSyncAlt className="fa-spin" />
</p>
)}
{sensor.scans
?.concat()
.reverse()
.map(s => (
<p
key={s?.id}
className={`${s?.cancelled ? "text-danger" : ""} ${
selectedScan === s?.id ? "selected" : ""
} ${!s?.cancelled && !s?.scanning ? "text-success" : ""}`}
onClick={() => s && selectScan(s)}
>
{s?.request?.substr(0, 15)}
... {s?.scanning && <FaSyncAlt className="fa-spin" />}
</p>
))}
</div>
</Col>
)}
<Col
sm={sensor.history ? 8 : 12}
style={{
height: "100%",
display: "flex",
flexDirection: "column",
}}
>
<OutputField
style={{
flexGrow: 2,
minHeight: "44px",
whiteSpace: "pre-line",
overflowY: "auto",
}}
alert={
(sensor.history
? (scan && scan.scanning) ||
(selectedScan === "basic-scan" && sensor.scanning)
: sensor.scanning) || false
}
>
{(() => {
if (sensor.history && selectedScan !== "basic-scan") {
if (scan) {
const date = new Date(scan?.timestamp || "");
return (
`${date.toLocaleTimeString()} - ${scan.mode}${
scan.location && " - " + scan.location
}` +
"\n" +
scan.request
);
}
return "";
}
return sensor.scanRequest;
})()}
</OutputField>
<TypingField
style={{flexGrow: 6, minHeight: "44px"}}
controlled
onChange={(
e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => setDataField(e.target.value)}
value={dataField}
/>
</Col>
</Row>
<div style={{display: "flex"}}>
<Button
onClick={() => sendScanResult(sensor)}
style={{flexGrow: 2}}
size={"sm"}
color="primary"
>
Send
</Button>
{/*<Button
onClick={this.flash.bind(this)}
style={{ flexGrow: 1 }}
size={"sm"}
>
Flash
</Button>*/}
<ScanPresets
domain={domain}
style={{flexGrow: 4, maxWidth: 100}}
onChange={(e: string) => setDataField(e)}
/>
<select
onChange={e => setDataField(e.target.value)}
value={"answers"}
style={{flexGrow: 4, maxWidth: 50}}
>
<option disabled value={"answers"}>
Info
</option>
{sensor?.presetAnswers?.map(p =>
p ? (
<option key={`${p.label}-${p.value}`} value={p.value}>
{p.label || ""}
</option>
) : null,
)}
</select>
<Button
onClick={() => external && sendProcessedData(external, true)}
style={{flexGrow: 2}}
size={"sm"}
color="warning"
>
F&S
</Button>
<Button
onClick={() => external && sendProcessedData(external)}
style={{flexGrow: 4}}
size={"sm"}
color="success"
>
Data
</Button>
</div>
<div style={{display: "flex"}}>
<Button onClick={() => probeData()} style={{flexGrow: 2}} size={"sm"}>
Probe Data
</Button>
<Button
onClick={() => probeData(true)}
style={{flexGrow: 2}}
color="warning"
size={"sm"}
>
Flash & Send Probe Data
</Button>
</div>
</div>
</Container>
);
};
export default SensorsCore; | the_stack |
import { isString, Message } from "../interfaces.js";
import {
Binding,
BindingObserver,
ExecutionContext,
Observable,
ObservationRecord,
} from "../observation/observable.js";
import { FAST } from "../platform.js";
import { DOM } from "./dom.js";
import {
AddViewBehaviorFactory,
Aspect,
Aspected,
HTMLDirective,
ViewBehavior,
ViewBehaviorFactory,
ViewBehaviorTargets,
} from "./html-directive.js";
import { Markup } from "./markup.js";
import type { CaptureType } from "./template.js";
import type { SyntheticView } from "./view.js";
declare class TrustedHTML {}
const createInnerHTMLBinding = globalThis.TrustedHTML
? (binding: Binding) => (s, c) => {
const value = binding(s, c);
if (value instanceof TrustedHTML) {
return value;
}
throw FAST.error(Message.bindingInnerHTMLRequiresTrustedTypes);
}
: (binding: Binding) => binding;
/**
* Describes how aspects of an HTML element will be affected by bindings.
* @public
*/
export type BindingMode = Record<
Aspect,
(directive: HTMLBindingDirective) => Pick<ViewBehaviorFactory, "createBehavior">
>;
/**
* Describes how aspects of an HTML element will be affected by bindings.
* @public
*/
export const BindingMode = Object.freeze({
/**
* Creates a binding mode based on the supplied behavior types.
* @param UpdateType - The base behavior type used to update aspects.
* @param EventType - The base behavior type used to respond to events.
* @returns A new binding mode.
*/
define(
UpdateType: typeof UpdateBinding,
EventType: typeof EventBinding = EventBinding
): BindingMode {
return Object.freeze({
[1]: d => new UpdateType(d, DOM.setAttribute),
[2]: d => new UpdateType(d, DOM.setBooleanAttribute),
[3]: d => new UpdateType(d, (t, a, v) => (t[a] = v)),
[4]: d => new (createContentBinding(UpdateType))(d, updateContentTarget),
[5]: d => new UpdateType(d, updateTokenListTarget),
[6]: d => new EventType(d),
});
},
});
/**
* Describes the configuration for a binding expression.
* @public
*/
export interface BindingConfig<T = any> {
/**
* The binding mode to configure the binding with.
*/
mode: BindingMode;
/**
* Options to be supplied to the binding behaviors.
*/
options: T;
}
/**
* Creates a new binding configuration based on the supplied options.
* @public
*/
export type BindingConfigResolver<T> = (options: T) => BindingConfig<T>;
/**
* Describes the configuration for a binding expression.
* @public
*/
export const BindingConfig = Object.freeze({
/**
* Creates a binding configuration based on the provided mode and options.
* @param mode - The mode to use for the configuration.
* @param defaultOptions - The default options to use for the configuration.
* @returns A new binding configuration.
*/
define<T>(
mode: BindingMode,
defaultOptions: T
): BindingConfig<T> & BindingConfigResolver<T> {
const config: BindingConfig<T> & BindingConfigResolver<T> = (
options: T
): BindingConfig<T> => {
return {
mode: config.mode,
options: Object.assign({}, defaultOptions, options),
};
};
config.options = defaultOptions;
config.mode = mode;
return config;
},
});
/**
* The "this" context for an update target function.
* @public
*/
export interface UpdateTargetThis {
/**
* The directive configuration for the update.
*/
directive: HTMLBindingDirective;
}
/**
* A target update function.
* @param this - The "this" context for the update.
* @param target - The node that is targeted by the update.
* @param aspect - The aspect of the node that is being targeted.
* @param value - The value to assign to the aspect.
* @param source - The source object that the value was derived from.
* @param context - The execution context that the binding is being run under.
* @public
*/
export type UpdateTarget = (
this: UpdateTargetThis,
target: Node,
aspect: string,
value: any,
source: any,
context: ExecutionContext
) => void;
/**
* A base binding behavior for DOM updates.
* @public
*/
export class UpdateBinding implements ViewBehavior {
/**
* Creates an instance of UpdateBinding.
* @param directive - The directive that has the configuration for this behavior.
* @param updateTarget - The function used to update the target with the latest value.
*/
constructor(
public readonly directive: HTMLBindingDirective,
protected updateTarget: UpdateTarget
) {}
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
bind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {}
/**
* Unbinds this behavior from the source.
* @param source - The source to unbind from.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
unbind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {}
/**
* Creates a behavior.
* @param targets - The targets available for behaviors to be attached to.
*/
createBehavior(targets: ViewBehaviorTargets): ViewBehavior {
return this;
}
}
function createContentBinding(Type: typeof UpdateBinding): typeof UpdateBinding {
return class extends Type {
unbind(
source: any,
context: ExecutionContext,
targets: ViewBehaviorTargets
): void {
super.unbind(source, context, targets);
const target = targets[this.directive.nodeId] as ContentTarget;
const view = target.$fastView as ComposableView;
if (view !== void 0 && view.isComposed) {
view.unbind();
view.needsBindOnly = true;
}
}
};
}
type ComposableView = SyntheticView & {
isComposed?: boolean;
needsBindOnly?: boolean;
};
type ContentTarget = Node & {
$fastView?: ComposableView;
$fastTemplate?: { create(): SyntheticView };
};
function updateContentTarget(
target: ContentTarget,
aspect: string,
value: any,
source: any,
context: ExecutionContext
): void {
// If there's no actual value, then this equates to the
// empty string for the purposes of content bindings.
if (value === null || value === undefined) {
value = "";
}
// If the value has a "create" method, then it's a template-like.
if (value.create) {
target.textContent = "";
let view = target.$fastView as ComposableView;
// If there's no previous view that we might be able to
// reuse then create a new view from the template.
if (view === void 0) {
view = value.create() as SyntheticView;
} else {
// If there is a previous view, but it wasn't created
// from the same template as the new value, then we
// need to remove the old view if it's still in the DOM
// and create a new view from the template.
if (target.$fastTemplate !== value) {
if (view.isComposed) {
view.remove();
view.unbind();
}
view = value.create() as SyntheticView;
}
}
// It's possible that the value is the same as the previous template
// and that there's actually no need to compose it.
if (!view.isComposed) {
view.isComposed = true;
view.bind(source, context!);
view.insertBefore(target);
target.$fastView = view;
target.$fastTemplate = value;
} else if (view.needsBindOnly) {
view.needsBindOnly = false;
view.bind(source, context!);
}
} else {
const view = target.$fastView as ComposableView;
// If there is a view and it's currently composed into
// the DOM, then we need to remove it.
if (view !== void 0 && view.isComposed) {
view.isComposed = false;
view.remove();
if (view.needsBindOnly) {
view.needsBindOnly = false;
} else {
view.unbind();
}
}
target.textContent = value;
}
}
interface TokenListState {
v: {};
c: number;
}
function updateTokenListTarget(
this: UpdateTargetThis,
target: Element,
aspect: string,
value: any
): void {
const directive = this.directive;
const lookup = `${directive.id}-t`;
const state: TokenListState =
target[lookup] ?? (target[lookup] = { c: 0, v: Object.create(null) });
const versions = state.v;
let currentVersion = state.c;
const tokenList = target[aspect] as DOMTokenList;
// Add the classes, tracking the version at which they were added.
if (value !== null && value !== undefined && value.length) {
const names = value.split(/\s+/);
for (let i = 0, ii = names.length; i < ii; ++i) {
const currentName = names[i];
if (currentName === "") {
continue;
}
versions[currentName] = currentVersion;
tokenList.add(currentName);
}
}
state.v = currentVersion + 1;
// If this is the first call to add classes, there's no need to remove old ones.
if (currentVersion === 0) {
return;
}
// Remove classes from the previous version.
currentVersion -= 1;
for (const name in versions) {
if (versions[name] === currentVersion) {
tokenList.remove(name);
}
}
}
/**
* A binding behavior for one-time bindings.
* @public
*/
export class OneTimeBinding extends UpdateBinding {
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
bind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
const directive = this.directive;
this.updateTarget(
targets[directive.nodeId],
directive.targetAspect,
directive.binding(source, context),
source,
context
);
}
}
const signals: Record<string, undefined | Function | Function[]> = Object.create(null);
/**
* A binding behavior for signal bindings.
* @public
*/
export class SignalBinding extends UpdateBinding {
private handlerProperty = `${this.directive.id}-h`;
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
bind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
const directive = this.directive;
const target = targets[directive.nodeId];
const signal = this.getSignal(source, context);
const handler = (target[this.handlerProperty] = () => {
this.updateTarget(
target,
directive.targetAspect!,
directive.binding(source, context),
source,
context
);
});
handler();
const found = signals[signal];
if (found) {
Array.isArray(found)
? found.push(handler)
: (signals[signal] = [found, handler]);
} else {
signals[signal] = handler;
}
}
/**
* Unbinds this behavior from the source.
* @param source - The source to unbind from.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
unbind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
const signal = this.getSignal(source, context);
const found = signals[signal];
if (found && Array.isArray(found)) {
const directive = this.directive;
const target = targets[directive.nodeId];
const handler = target[this.handlerProperty];
const index = found.indexOf(handler);
if (index !== -1) {
found.splice(index, 1);
}
} else {
signals[signal] = void 0;
}
}
private getSignal(source: any, context: ExecutionContext): string {
const options = this.directive.options;
return isString(options) ? options : options(source, context);
}
/**
* Sends the specified signal to signaled bindings.
* @param signal - The signal to send.
* @public
*/
public static send(signal: string): void {
const found = signals[signal];
if (found) {
Array.isArray(found) ? found.forEach(x => x()) : found();
}
}
}
/**
* A binding behavior for bindings that change.
* @public
*/
export class ChangeBinding extends UpdateBinding {
private isBindingVolatile: boolean;
private observerProperty: string;
/**
* Creates an instance of ChangeBinding.
* @param directive - The directive that has the configuration for this behavior.
* @param updateTarget - The function used to update the target with the latest value.
*/
constructor(directive: HTMLBindingDirective, updateTarget: UpdateTarget) {
super(directive, updateTarget);
this.isBindingVolatile = Observable.isVolatileBinding(directive.binding);
this.observerProperty = `${directive.id}-o`;
}
/**
* Returns the binding observer used to update the node.
* @param target - The target node.
* @returns A BindingObserver.
*/
protected getObserver(target: Node): BindingObserver {
return (
target[this.observerProperty] ??
(target[this.observerProperty] = Observable.binding(
this.directive.binding,
this,
this.isBindingVolatile
))
);
}
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
bind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
const directive = this.directive;
const target = targets[directive.nodeId];
const observer = this.getObserver(target);
(observer as any).target = target;
(observer as any).source = source;
(observer as any).context = context;
this.updateTarget(
target,
directive.targetAspect,
observer.observe(source, context),
source,
context
);
}
/**
* Unbinds this behavior from the source.
* @param source - The source to unbind from.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
unbind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
const target = targets[this.directive.nodeId];
const observer = this.getObserver(target);
observer.dispose();
(observer as any).target = null;
(observer as any).source = null;
(observer as any).context = null;
}
/** @internal */
public handleChange(binding: Binding, observer: BindingObserver): void {
const target = (observer as any).target;
const source = (observer as any).source;
const context = (observer as any).context;
this.updateTarget(
target,
this.directive.targetAspect,
observer.observe(source, context!),
source,
context
);
}
}
/**
* A binding behavior for handling events.
* @public
*/
export class EventBinding {
private contextProperty: string;
private sourceProperty: string;
/**
* Creates an instance of EventBinding.
* @param directive - The directive that has the configuration for this behavior.
*/
constructor(public readonly directive: HTMLBindingDirective) {
this.sourceProperty = `${directive.id}-s`;
this.contextProperty = `${directive.id}-c`;
}
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
bind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
const directive = this.directive;
const target = targets[directive.nodeId];
target[this.sourceProperty] = source;
target[this.contextProperty] = context;
target.addEventListener(directive.targetAspect, this, directive.options);
}
/**
* Unbinds this behavior from the source.
* @param source - The source to unbind from.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
unbind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
const directive = this.directive;
const target = targets[directive.nodeId];
target[this.sourceProperty] = target[this.contextProperty] = null;
target.removeEventListener(directive.targetAspect, this, directive.options);
}
/**
* Creates a behavior.
* @param targets - The targets available for behaviors to be attached to.
*/
createBehavior(targets: ViewBehaviorTargets): ViewBehavior {
return this;
}
/**
* @internal
*/
handleEvent(event: Event): void {
const target = event.currentTarget!;
ExecutionContext.setEvent(event);
const result = this.directive.binding(
target[this.sourceProperty],
target[this.contextProperty]
);
ExecutionContext.setEvent(null);
if (result !== true) {
event.preventDefault();
}
}
}
/**
* The settings required to enable two-way binding.
* @public
*/
export interface TwoWaySettings {
/**
* Determines which event to listen to, to detect changes in the view.
* @param directive - The directive to determine the change event for.
* @param target - The target element to determine the change event for.
*/
determineChangeEvent(directive: HTMLBindingDirective, target: HTMLElement): string;
}
let twoWaySettings: TwoWaySettings = {
determineChangeEvent() {
return "change";
},
};
/**
* A binding behavior for bindings that update in two directions.
* @public
*/
export class TwoWayBinding extends ChangeBinding {
private changeEvent: string;
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
bind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
super.bind(source, context, targets);
const directive = this.directive;
const target = targets[directive.nodeId] as HTMLElement;
if (!this.changeEvent) {
this.changeEvent =
directive.options.changeEvent ??
twoWaySettings.determineChangeEvent(directive, target);
}
target.addEventListener(this.changeEvent, this);
}
/**
* Unbinds this behavior from the source.
* @param source - The source to unbind from.
* @param context - The execution context that the binding is operating within.
* @param targets - The targets that behaviors in a view can attach to.
*/
unbind(source: any, context: ExecutionContext, targets: ViewBehaviorTargets): void {
super.unbind(source, context, targets);
(targets[this.directive.nodeId] as HTMLElement).removeEventListener(
this.changeEvent,
this
);
}
/** @internal */
public handleEvent(event: Event): void {
const directive = this.directive;
const target = event.currentTarget as HTMLElement;
let value;
switch (directive.aspectType) {
case 1:
value = target.getAttribute(directive.targetAspect);
break;
case 2:
value = target.hasAttribute(directive.targetAspect);
break;
case 4:
value = target.innerText;
break;
default:
value = target[directive.targetAspect];
break;
}
const observer = this.getObserver(target);
const last = (observer as any).last as ObservationRecord; // using internal API!!!
last.propertySource[last.propertyName] = directive.options.fromView(value);
}
/**
* Configures two-way binding.
* @param settings - The settings to use for the two-way binding system.
*/
public static configure(settings: TwoWaySettings) {
twoWaySettings = settings;
}
}
/**
* The default binding options.
* @public
*/
export type DefaultBindingOptions = AddEventListenerOptions;
/**
* The default onChange binding configuration.
* @public
*/
export const onChange = BindingConfig.define(
BindingMode.define(ChangeBinding),
{} as DefaultBindingOptions
);
/**
* The default twoWay binding options.
* @public
*/
export type DefaultTwoWayBindingOptions = DefaultBindingOptions & {
changeEvent?: string;
fromView?: (value: any) => any;
};
/**
* The default twoWay binding configuration.
* @public
*/
export const twoWay = BindingConfig.define(BindingMode.define(TwoWayBinding), {
fromView: v => v,
} as DefaultTwoWayBindingOptions);
/**
* The default onTime binding configuration.
* @public
*/
export const oneTime = BindingConfig.define(BindingMode.define(OneTimeBinding), {
once: true,
} as DefaultBindingOptions);
const signalMode: BindingMode = BindingMode.define(SignalBinding);
/**
* Creates a signal binding configuration with the supplied options.
* @param options - The signal name or a binding to use to retrieve the signal name.
* @returns A binding configuration.
* @public
*/
export const signal = <T = any>(
options: string | Binding<T>
): BindingConfig<string | Binding<T>> => {
return { mode: signalMode, options };
};
/**
* A directive that applies bindings.
* @public
*/
export class HTMLBindingDirective
implements HTMLDirective, ViewBehaviorFactory, Aspected {
private factory: Pick<ViewBehaviorFactory, "createBehavior"> | null = null;
/**
* The unique id of the factory.
*/
id: string;
/**
* The structural id of the DOM node to which the created behavior will apply.
*/
nodeId: string;
/**
* The original source aspect exactly as represented in markup.
*/
sourceAspect: string;
/**
* The evaluated target aspect, determined after processing the source.
*/
targetAspect: string;
/**
* The type of aspect to target.
*/
aspectType: Aspect = Aspect.content;
/**
* Creates an instance of HTMLBindingDirective.
* @param binding - The binding to apply.
* @param mode - The binding mode to use when applying the binding.
* @param options - The options to configure the binding with.
*/
constructor(public binding: Binding, public mode: BindingMode, public options: any) {}
/**
* Creates HTML to be used within a template.
* @param add - Can be used to add behavior factories to a template.
*/
createHTML(add: AddViewBehaviorFactory): string {
return Markup.interpolation(add(this));
}
/**
* Creates a behavior.
* @param targets - The targets available for behaviors to be attached to.
*/
createBehavior(targets: ViewBehaviorTargets): ViewBehavior {
if (this.factory == null) {
if (this.targetAspect === "innerHTML") {
this.binding = createInnerHTMLBinding(this.binding);
}
this.factory = this.mode[this.aspectType](this);
}
return this.factory.createBehavior(targets);
}
}
HTMLDirective.define(HTMLBindingDirective, { aspected: true });
/**
* Creates a binding directive with the specified configuration.
* @param binding - The binding expression.
* @param config - The binding configuration.
* @returns A binding directive.
* @public
*/
export function bind<T = any>(
binding: Binding<T>,
config: BindingConfig | DefaultBindingOptions = onChange
): CaptureType<T> {
if (!("mode" in config)) {
config = onChange(config);
}
return new HTMLBindingDirective(binding, config.mode, config.options);
} | the_stack |
import {
CassettePlayer,
Trs80
} from "trs80-emulator";
import {
CanvasScreen,
ControlPanel,
DriveIndicators, flashNode,
PanelType, ProgressBar,
SettingsPanel, WebKeyboard
} from "trs80-emulator-web";
import firebase from 'firebase/app';
// These imports load individual services into the firebase namespace.
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/analytics';
import * as firebaseui from "firebaseui";
import {makeIcon, makeIconButton, makeTextButton} from "./Utils";
import {PanelManager} from "./PanelManager";
import {LibraryPanel} from "./LibraryPanel";
import {Context} from "./Context";
import {Library} from "./Library";
import {FileBuilder} from "./File";
import {DialogBox} from "./DialogBox";
import {AuthUser} from "./User";
import {Database} from "./Database";
import {File} from "./File";
import {Editor} from "trs80-emulator-web";
import {isRegisterSetField, toHexWord} from "z80-base";
import {disasmForTrs80} from "trs80-disasm";
import {Cassette, CassetteSpeed} from "trs80-base";
import {
concatAudio,
encodeHighSpeed,
encodeLowSpeed,
frameToTimestamp, totalAudioSamples,
wrapHighSpeed,
wrapLowSpeed
} from "trs80-cassette";
import {WebSoundPlayer} from "../../trs80-emulator-web/dist/WebSoundPlayer";
/**
* A cassette player based on a CAS file.
*/
export class CasFileCassettePlayer extends CassettePlayer {
private samples: Int16Array = new Int16Array(0);
private frame: number = 0;
private progressBar: ProgressBar | undefined;
private motorOn = false;
private rewinding = false;
/**
* Create the audio for the cassette file.
*
* @param casFile cassette file to convert to audio.
* @param skip position the tape after the first "skip" files.
*/
public setCasFile(casFile: Cassette, skip: number): void {
// Make audio for each file at the appropriate speed.
const samplesList: Int16Array[] = [];
this.frame = 0;
for (const cassetteFile of casFile.files) {
let samples: Int16Array;
switch (cassetteFile.speed) {
case CassetteSpeed.LOW_SPEED:
samples = encodeLowSpeed(wrapLowSpeed(cassetteFile.file.binary), this.samplesPerSecond, 500);
break;
case CassetteSpeed.HIGH_SPEED:
samples = encodeHighSpeed(wrapHighSpeed(cassetteFile.file.binary), this.samplesPerSecond);
break;
}
// Skip to this file.
if (skip === 0) {
this.frame = totalAudioSamples(samplesList);
}
skip -= 1;
samplesList.push(samples);
// Silence between files.
samplesList.push(new Int16Array(this.samplesPerSecond));
}
this.samples = concatAudio(samplesList);
this.progressBar?.setMaxValue(this.samples.length);
}
public rewind(): void {
if (this.progressBar === undefined) {
this.frame = 0;
} else {
this.rewinding = true;
this.updateProgressBarVisibility();
const updateRewind = () => {
if (this.frame > 0) {
this.frame = Math.max(0, Math.round(this.frame - this.samples.length/30));
this.progressBar?.setValue(this.frame);
window.requestAnimationFrame(updateRewind);
} else {
this.rewinding = false;
this.updateProgressBarVisibility();
}
};
// Wait for progress bar to become visible.
setTimeout(updateRewind, 150);
}
}
public setProgressBar(progressBar: ProgressBar): void {
this.progressBar = progressBar;
this.progressBar.setMaxValue(this.samples.length);
}
public onMotorStart(): void {
this.motorOn = true;
this.updateProgressBarVisibility();
}
public readSample(): number {
if (this.rewinding) {
// Can't read while rewinding.
return 0;
} else {
if (this.frame % this.samplesPerSecond === 0) {
console.log("Reading tape at " + frameToTimestamp(this.frame, this.samplesPerSecond));
}
if (this.progressBar !== undefined &&
(this.frame % Math.floor(this.samplesPerSecond / 10) === 0 ||
this.frame == this.samples.length - 1)) {
this.progressBar.setValue(this.frame);
}
return this.frame < this.samples.length ? this.samples[this.frame++] / 32768 : 0;
}
}
public onMotorStop(): void {
this.motorOn = false;
this.updateProgressBarVisibility();
}
private updateProgressBarVisibility() {
if (this.progressBar !== undefined) {
if (this.motorOn || this.rewinding) {
this.progressBar.show();
} else {
this.progressBar.hide();
}
}
}
}
function createNavbar(openLibrary: () => void, signIn: () => void, signOut: () => void): HTMLElement {
const body = document.querySelector("body") as HTMLElement;
const navbar = document.createElement("div");
navbar.classList.add("navbar");
const title = document.createElement("a");
title.classList.add("home-button");
title.textContent = "My TRS-80";
title.href = "/";
navbar.append(title);
const libraryButton = makeIconButton(makeIcon("folder_open"), "Open library (Ctrl-L)", openLibrary);
libraryButton.classList.add("library-button");
navbar.append(libraryButton);
const themeButton = makeIconButton(makeIcon("brightness_medium"), "Toggle theme", () => {
body.classList.toggle("light-mode");
body.classList.toggle("dark-mode");
});
themeButton.classList.add("theme-button");
navbar.append(themeButton);
const signInButton = makeTextButton("Sign In", "person", "sign-in-button", signIn);
const signOutButton = makeTextButton("Sign Out", "person", "sign-out-button", signOut);
navbar.append(signInButton, signOutButton);
return navbar;
}
const FLAG_STRING = "CNP3H5ZS"; // From LSB to MSB.
/**
* Convert an 8-bit flag byte to a debug string.
* TODO: Move this to z80-base.
*/
function makeFlagString(f: number): string {
let flagString = "";
for (let i = 0; i < 8; i++) {
flagString += (f & 0x01) !== 0 ? FLAG_STRING[i] : "-";
f >>= 1;
}
return flagString;
}
export function main() {
const args = Context.parseFragment(window.location.hash);
const runFileId = args.get("runFile")?.[0];
const userId = args.get("user")?.[0];
const body = document.querySelector("body") as HTMLElement;
body.classList.add("signed-out");
// Configuration for Firebase.
firebase.initializeApp({
apiKey: "AIzaSyAfGZY9BaDUmy4qNtg11JHd_kLd1JmgdBI",
authDomain: "my-trs-80.firebaseapp.com",
projectId: "my-trs-80",
storageBucket: "my-trs-80.appspot.com",
messagingSenderId: "438103442091",
appId: "1:438103442091:web:0fe42c43917ba1add52dee"
});
firebase.analytics();
// Configuration for Firebase sign-in screen.
const uiConfig = {
signInSuccessUrl: '/',
signInOptions: [
// Leave the lines as is for the providers you want to offer your users.
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
// firebase.auth.FacebookAuthProvider.PROVIDER_ID,
// firebase.auth.TwitterAuthProvider.PROVIDER_ID,
// firebase.auth.GithubAuthProvider.PROVIDER_ID,
// firebase.auth.EmailAuthProvider.PROVIDER_ID,
// firebase.auth.PhoneAuthProvider.PROVIDER_ID,
// firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
],
// Pop up a browser window for the actual sign-in page:
signInFlow: "popup",
callbacks: {
signInSuccessWithAuthResult: (authResult: any): boolean => {
// Don't use stuff here, the user will get passed to onAuthStateChanged().
// I don't see much else useful in authResult.
// console.log(authResult);
// Don't redirect, we've taken care of it.
return false;
},
},
};
let firebaseAuth = firebase.auth();
const firebaseAuthUi = new firebaseui.auth.AuthUI(firebaseAuth);
const signInDiv = document.createElement("div");
const signInInstructions = document.createElement("div");
signInInstructions.classList.add("sign-in-instructions");
signInInstructions.innerText = "Sign in to My TRS-80 to have a persistent place to store your files.";
const signInFirebase = document.createElement("div");
signInDiv.append(signInInstructions, signInFirebase);
let signInDialog: DialogBox | undefined = undefined;
const db = new Database(firebase.firestore());
firebaseAuth.onAuthStateChanged(firebaseUser => {
if (firebaseUser !== null) {
//console.log(firebaseUser);
const authUser = AuthUser.fromFirebaseUser(firebaseUser);
db.userFromAuthUser(authUser)
.then(user => context.user = user)
.catch(error => {
// TODO.
console.error(error);
});
if (signInDialog !== undefined) {
signInDialog.close();
signInDialog = undefined;
}
} else {
// No user signed in, render sign-in UI.
firebaseAuthUi.reset();
firebaseAuthUi.start(signInFirebase, uiConfig);
context.user = undefined;
}
});
const panelManager = new PanelManager();
const library = new Library();
const navbar = createNavbar(
() => panelManager.open(),
() => {
if (signInDialog !== undefined) {
signInDialog.close();
}
signInDialog = new DialogBox("Sign In", signInDiv, "sign-in-dialog-box");
},
() => firebase.auth().signOut());
const screenDiv = document.createElement("div");
screenDiv.classList.add("main-computer-screen");
const screen = new CanvasScreen(1.5);
const keyboard = new WebKeyboard();
const cassettePlayer = new CasFileCassettePlayer();
const soundPlayer = new WebSoundPlayer();
const progressBar = new ProgressBar(screen.getNode());
cassettePlayer.setProgressBar(progressBar);
const trs80 = new Trs80(screen, keyboard, cassettePlayer, soundPlayer);
keyboard.configureKeyboard();
const editor = new Editor(trs80, screen);
screenDiv.append(editor.node);
const reboot = () => {
trs80.reset();
trs80.start();
};
const hardwareSettingsPanel = new SettingsPanel(screen.getNode(), trs80, PanelType.HARDWARE);
const viewPanel = new SettingsPanel(screen.getNode(), trs80, PanelType.VIEW);
const controlPanel = new ControlPanel(screen.getNode());
controlPanel.addResetButton(reboot);
controlPanel.addTapeRewindButton(() => {
cassettePlayer.rewind();
});
controlPanel.addSettingsButton(hardwareSettingsPanel);
controlPanel.addSettingsButton(viewPanel);
// const progressBar = new ProgressBar(screen.getNode());
// cassette.setProgressBar(progressBar);
controlPanel.addMuteButton(soundPlayer);
const driveIndicators = new DriveIndicators(screen.getNode(), trs80.getMaxDrives());
trs80.onMotorOn.subscribe(drive => driveIndicators.setActiveDrive(drive));
body.append(navbar);
body.append(screenDiv);
let createdLibraryPanel = false;
let wasTrs80Started = false;
panelManager.onOpenClose.subscribe(isOpen => {
if (isOpen && !createdLibraryPanel) {
panelManager.pushPanel(new LibraryPanel(context));
createdLibraryPanel = true;
}
if (isOpen) {
wasTrs80Started = trs80.stop();
} else {
if (wasTrs80Started) {
trs80.start();
}
}
});
reboot();
const context = new Context(library, trs80, cassettePlayer, db, panelManager);
const screenshotButton = controlPanel.addScreenshotButton(() => {
if (context.runningFile !== undefined) {
let file = context.runningFile;
const screenshot = trs80.getScreenshot();
flashNode(screen.getNode());
const screenshots = [...file.screenshots, screenshot]; // Don't modify original array.
file = file.builder()
.withScreenshots(screenshots)
.withModifiedAt(new Date())
.build();
context.db.updateFile(context.runningFile, file)
.then(() => context.library.modifyFile(file))
.catch(error => {
// TODO.
console.error(error);
});
}
});
// Start hidden, since the user isn't signed in until later.
screenshotButton.classList.add("hidden");
controlPanel.addEditorButton(() => editor.startEdit());
let logging = false;
const logs: string[] = [];
const MAX_LOGS = 16*1024;
const disasm = disasmForTrs80();
const readMemory = (address: number): number => trs80.readMemory(address);
let stepPc = 0;
trs80.onPreStep.subscribe(() => {
stepPc = trs80.z80.regs.pc;
});
trs80.onPostStep.subscribe(() => {
if (logging) {
const instruction = disasm.disassembleTrace(stepPc, readMemory);
const values: string[] = [];
for (const arg of instruction.args) {
for (const reg of arg.split(/[^a-zA-Z']+/)) {
const regExpanded = reg.replace("'", "Prime");
if (isRegisterSetField(regExpanded)) {
const value = trs80.z80.regs.getValue(regExpanded);
values.push(reg + "=" + toHexWord(value));
}
}
}
const line = toHexWord(stepPc) + " " +
instruction.binText().padEnd(11) + " " +
instruction.toText().padEnd(20) + " " +
makeFlagString(trs80.z80.regs.f) + " " +
values.join(", ");
logs.push(line.trimEnd());
if (logs.length > MAX_LOGS) {
logs.splice(0, logs.length - MAX_LOGS);
}
}
});
/*
controlPanel.addResetButton(() => {
if (logging) {
const dump = logs.join("\n");
const blob = new Blob([dump], {type: "text/plain"});
const a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "trace.lst";
a.click();
logging = false;
} else {
logs.splice(0, logs.length);
logging = true;
}
});
*/
/**
* Update whether the user can take a screenshot of the running program.
*/
function updateScreenshotButtonVisibility() {
const canSaveScreenshot = context.runningFile !== undefined &&
context.user !== undefined &&
context.runningFile.uid === context.user.uid;
screenshotButton.classList.toggle("hidden", !canSaveScreenshot);
}
context.onRunningFile.subscribe(() => {
window.location.hash = context.getFragment();
updateScreenshotButtonVisibility();
});
context.onUser.subscribe(user => {
body.classList.toggle("signed-in", user !== undefined);
body.classList.toggle("signed-out", user === undefined);
updateScreenshotButtonVisibility();
library.removeAll();
if (user !== undefined) {
// Fetch all files.
context.db.getAllFiles(userId ?? user.uid)
.then((querySnapshot) => {
// Sort files before adding them to the library so that they show up in the UI in order
// and the screenshots get loaded with the visible ones first.
const files: File[] = [];
for (const doc of querySnapshot.docs) {
files.push(FileBuilder.fromDoc(doc).build());
}
files.sort(File.compare);
for (const file of files) {
library.addFile(file);
// Update hash if necessary.
if (file.binary.length !== 0 && file.isOldHash()) {
// This updates the hash.
const newFile = file.builder().withBinary(file.binary).build();
console.log("Hash for " + file.name + " has been recomputed");
context.db.updateFile(file, newFile)
.then(() => {
library.modifyFile(newFile);
});
}
}
// We should now be in sync with the cloud database.
library.setInSync(true);
})
.catch(error => {
// TODO
console.error(error);
if (error.name === "FirebaseError") {
// code can be "permission-denied".
console.error(error.code, error.message);
}
});
}
});
// See if we should run an app right away.
context.onUserResolved.subscribe(() => {
// We're signed in, or not, and can now read the database.
if (runFileId !== undefined) {
db.getFile(runFileId)
.then(file => {
context.runProgram(file);
})
.catch(() => {
// TODO Should probably display error message.
});
}
});
} | the_stack |
import _ from 'lodash';
import moment from 'moment';
import * as dateMath from 'app/core/utils/datemath';
import * as Druid from 'druid.d'
const DRUID_DATASOURCE_PATH = '/druid/v2/datasources';
export default class DruidDatasource {
id: number;
name: string;
url: string;
q: any;
backendSrv: any;
templateSrv: any;
basicAuth: any;
supportMetrics: any;
periodGranularity: any;
GRANULARITIES = [
['second', moment.duration(1, 'second')],
['minute', moment.duration(1, 'minute')],
['fifteen_minute', moment.duration(15, 'minute')],
['thirty_minute', moment.duration(30, 'minute')],
['hour', moment.duration(1, 'hour')],
['day', moment.duration(1, 'day')],
['week', moment.duration(1, 'week')],
['month', moment.duration(1, 'month')],
['quarter', moment.duration(1, 'quarter')],
['year', moment.duration(1, 'year')]
];
filterTemplateExpanders = {
"selector": ['value'],
"regex": ['pattern'],
"javascript": ['function'],
"search": []
};
/** @ngInject */
constructor(instanceSettings, $q, backendSrv, templateSrv) {
this.name = instanceSettings.name;
this.id = instanceSettings.id;
this.url = instanceSettings.url;
this.backendSrv = backendSrv;
this.q = $q;
this.templateSrv = templateSrv;
this.basicAuth = instanceSettings.basicAuth;
instanceSettings.jsonData = instanceSettings.jsonData || {};
this.supportMetrics = true;
this.periodGranularity = instanceSettings.jsonData.periodGranularity;
}
query(options) {
const from = this.dateToMoment(options.range.from, false);
const to = this.dateToMoment(options.range.to, true);
let promises = options.targets.map(target => {
if (target.hide === true || _.isEmpty(target.druidDS) || (_.isEmpty(target.aggregators) && target.queryType !== "select")) {
const d = this.q.defer();
d.resolve([]);
return d.promise;
}
const maxDataPointsByResolution = options.maxDataPoints;
const maxDataPointsByConfig = target.maxDataPoints ? target.maxDataPoints : Number.MAX_VALUE;
const maxDataPoints = Math.min(maxDataPointsByResolution, maxDataPointsByConfig);
let granularity = target.shouldOverrideGranularity ? this.templateSrv.replace(target.customGranularity) : this.computeGranularity(from, to, maxDataPoints);
//Round up to start of an interval
//Width of bar chars in Grafana is determined by size of the smallest interval
const roundedFrom = granularity === "all" ? from : this.roundUpStartTime(from, granularity);
if (this.periodGranularity != "") {
if (granularity === 'day') {
granularity = { "type": "period", "period": "P1D", "timeZone": this.periodGranularity }
}
}
return this.doQuery(roundedFrom, to, granularity, target);
});
return this.q.all(promises).then(results => {
return { data: _.flatten(results) };
});
}
doQuery(from, to, granularity, target) {
let datasource = target.druidDS;
let filters = target.filters;
let aggregators = target.aggregators.map(this.splitCardinalityFields);
let postAggregators = target.postAggregators;
let groupBy = _.map(target.groupBy, (e) => { return this.templateSrv.replace(e) });
let limitSpec = null;
let metricNames = this.getMetricNames(aggregators, postAggregators);
let intervals = this.getQueryIntervals(from, to);
let promise = null;
let selectMetrics = target.selectMetrics;
let selectDimensions = target.selectDimensions;
let selectThreshold = target.selectThreshold;
if (!selectThreshold) {
selectThreshold = 5;
}
if (target.queryType === 'topN') {
let threshold = target.limit;
let metric = target.druidMetric;
let dimension = this.templateSrv.replace(target.dimension);
promise = this.topNQuery(datasource, intervals, granularity, filters, aggregators, postAggregators, threshold, metric, dimension)
.then(response => {
return this.convertTopNData(response.data, dimension, metric);
});
}
else if (target.queryType === 'groupBy') {
limitSpec = this.getLimitSpec(target.limit, target.orderBy);
promise = this.groupByQuery(datasource, intervals, granularity, filters, aggregators, postAggregators, groupBy, limitSpec)
.then(response => {
return this.convertGroupByData(response.data, groupBy, metricNames);
});
}
else if (target.queryType === 'select') {
promise = this.selectQuery(datasource, intervals, granularity, selectDimensions, selectMetrics, filters, selectThreshold);
return promise.then(response => {
return this.convertSelectData(response.data);
});
}
else {
promise = this.timeSeriesQuery(datasource, intervals, granularity, filters, aggregators, postAggregators)
.then(response => {
return this.convertTimeSeriesData(response.data, metricNames);
});
}
/*
At this point the promise will return an list of time series of this form
[
{
target: <metric name>,
datapoints: [
[<metric value>, <timestamp in ms>],
...
]
},
...
]
Druid calculates metrics based on the intervals specified in the query but returns a timestamp rounded down.
We need to adjust the first timestamp in each time series
*/
return promise.then(metrics => {
let fromMs = this.formatTimestamp(from);
metrics.forEach(metric => {
if (!_.isEmpty(metric.datapoints[0]) && metric.datapoints[0][1] < fromMs) {
metric.datapoints[0][1] = fromMs;
}
});
return metrics;
});
};
splitCardinalityFields(aggregator) {
if (aggregator.type === 'cardinality' && typeof aggregator.fieldNames === 'string') {
aggregator.fieldNames = aggregator.fieldNames.split(',')
}
return aggregator;
}
selectQuery(datasource: string, intervals: Array<string>, granularity: Druid.Granularity,
dimensions: Array<string | Object>, metric: Array<string | Object>, filters: Array<Druid.DruidFilter>,
selectThreshold: Object) {
let query: Druid.DruidSelectQuery = {
"queryType": "select",
"dataSource": datasource,
"granularity": granularity,
"pagingSpec": { "pagingIdentifiers": {}, "threshold": selectThreshold },
"dimensions": dimensions,
"metrics": metric,
"intervals": intervals
};
if (filters && filters.length > 0) {
query.filter = this.buildFilterTree(filters);
}
return this.druidQuery(query);
};
timeSeriesQuery(datasource: string, intervals: Array<string>, granularity: Druid.Granularity,
filters: Array<Druid.DruidFilter>, aggregators: Object, postAggregators: Object) {
let query: Druid.DruidTimeSeriesQuery = {
queryType: "timeseries",
dataSource: datasource,
granularity: granularity,
aggregations: aggregators,
postAggregations: postAggregators,
intervals: intervals
};
if (filters && filters.length > 0) {
query.filter = this.buildFilterTree(filters);
}
return this.druidQuery(query);
};
topNQuery(datasource: string, intervals: Array<string>, granularity: Druid.Granularity,
filters: Array<Druid.DruidFilter>, aggregators: Object, postAggregators: Object,
threshold: number, metric: string | Object, dimension: string | Object) {
const query: Druid.DruidTopNQuery = {
queryType: "topN",
dataSource: datasource,
granularity: granularity,
threshold: threshold,
dimension: dimension,
metric: metric,
aggregations: aggregators,
postAggregations: postAggregators,
intervals: intervals
};
if (filters && filters.length > 0) {
query.filter = this.buildFilterTree(filters);
}
return this.druidQuery(query);
};
groupByQuery(datasource: string, intervals: Array<string>, granularity: Druid.Granularity,
filters: Array<Druid.DruidFilter>, aggregators: Object, postAggregators: Object, groupBy: Array<string>,
limitSpec: Druid.LimitSpec) {
const query: Druid.DruidGroupByQuery = {
queryType: "groupBy",
dataSource: datasource,
granularity: granularity,
dimensions: groupBy,
aggregations: aggregators,
postAggregations: postAggregators,
intervals: intervals,
limitSpec: limitSpec,
};
if (filters && filters.length > 0) {
query.filter = this.buildFilterTree(filters);
}
return this.druidQuery(query);
};
druidQuery(query: Druid.AbstractDruidQuery) {
const options = {
method: 'POST',
url: this.url + '/druid/v2/',
data: query
};
return this.backendSrv.datasourceRequest(options);
};
getLimitSpec(limitNum, orderBy) {
return {
"type": "default",
"limit": limitNum,
"columns": !orderBy ? null : orderBy.map(col => {
return { "dimension": col, "direction": "DESCENDING" };
})
};
}
testDatasource() {
return this.get(DRUID_DATASOURCE_PATH).then(() => {
return { status: "success", message: "Druid Data source is working", title: "Success" };
});
}
//Get list of available datasources
getDataSources() {
return this.get(DRUID_DATASOURCE_PATH).then(response => {
return response.data;
});
};
getDimensionsAndMetrics(datasource) {
return this.get(DRUID_DATASOURCE_PATH + datasource).then(response => {
return response.data;
});
};
getFilterValues(target, panelRange, query) {
const topNquery: any = {
"queryType": "topN",
"dataSource": target.druidDS,
"granularity": 'all',
"threshold": 10,
"dimension": target.currentFilter.dimension,
"metric": "count",
"aggregations": [{ "type": "count", "name": "count" }],
"intervals": this.getQueryIntervals(panelRange.from, panelRange.to)
};
let filters = [];
if (target.filters) {
filters =
filters = _.cloneDeep(target.filters);
}
filters.push({
"type": "search",
"dimension": target.currentFilter.dimension,
"query": {
"type": "insensitive_contains",
"value": query
}
});
topNquery.filter = this.buildFilterTree(filters);
return this.druidQuery(topNquery);
};
get(relativeUrl, params?) {
return this.backendSrv.datasourceRequest({
method: 'GET',
url: this.url + relativeUrl,
params: params,
});
};
buildFilterTree(filters): Druid.DruidFilter {
//Do template variable replacement
const replacedFilters = filters.map(filter => {
return this.replaceTemplateValues(filter, this.filterTemplateExpanders[filter.type]);
})
.map(filter => {
const finalFilter = _.omit(filter, 'negate');
if (filter.negate) {
return { "type": "not", "field": finalFilter };
}
return finalFilter;
});
if (replacedFilters) {
if (replacedFilters.length === 1) {
return replacedFilters[0];
}
return {
"type": "and",
"fields": replacedFilters
};
}
return null;
}
getQueryIntervals(from, to) {
return [from.toISOString() + '/' + to.toISOString()];
}
getMetricNames(aggregators, postAggregators) {
const displayAggs = _.filter(aggregators, agg => {
return agg.type !== 'approxHistogramFold' && agg.hidden != true;
});
return _.union(_.map(displayAggs, 'name'), _.map(postAggregators, 'name'));
}
formatTimestamp(ts) {
return moment(ts).format('X') * 1000;
}
convertTimeSeriesData(md, metrics) {
return metrics.map(metric => {
return {
target: metric,
datapoints: md.map(item => {
return [
item.result[metric],
this.formatTimestamp(item.timestamp)
];
})
};
});
}
getGroupName(groupBy, metric) {
return groupBy.map(dim => {
return metric.event[dim];
})
.join("-");
}
convertTopNData(md, dimension, metric) {
/*
Druid topN results look like this:
[
{
"timestamp": "ts1",
"result": [
{"<dim>": d1, "<metric>": mv1},
{"<dim>": d2, "<metric>": mv2}
]
},
{
"timestamp": "ts2",
"result": [
{"<dim>": d1, "<metric>": mv3},
{"<dim>": d2, "<metric>": mv4}
]
},
...
]
*/
/*
First, we need make sure that the result for each
timestamp contains entries for all distinct dimension values
in the entire list of results.
Otherwise, if we do a stacked bar chart, Grafana doesn't sum
the metrics correctly.
*/
//Get the list of all distinct dimension values for the entire result set
const dVals = md.reduce((dValsSoFar, tsItem) => {
const dValsForTs = _.map(tsItem.result, dimension);
return _.union(dValsSoFar, dValsForTs);
}, {});
//Add null for the metric for any missing dimension values per timestamp result
md.forEach(tsItem => {
const dValsPresent = _.map(tsItem.result, dimension);
const dValsMissing = _.difference(dVals, dValsPresent);
dValsMissing.forEach(dVal => {
const nullPoint = {};
nullPoint[dimension] = dVal;
nullPoint[metric] = null;
tsItem.result.push(nullPoint);
});
return tsItem;
});
//Re-index the results by dimension value instead of time interval
const mergedData = md.map(item => {
/*
This first map() transforms this into a list of objects
where the keys are dimension values
and the values are [metricValue, unixTime] so that we get this:
[
{
"d1": [mv1, ts1],
"d2": [mv2, ts1]
},
{
"d1": [mv3, ts2],
"d2": [mv4, ts2]
},
...
]
*/
const timestamp = this.formatTimestamp(item.timestamp);
const keys = _.map(item.result, dimension);
const vals = _.map(item.result, metric).map(val => { return [val, timestamp]; });
return _.zipObject(keys, vals);
})
.reduce((prev, curr) => {
/*
Reduce() collapses all of the mapped objects into a single
object. The keys are dimension values
and the values are arrays of all the values for the same key.
The _.assign() function merges objects together and it's callback
gets invoked for every key,value pair in the source (2nd argument).
Since our initial value for reduce() is an empty object,
the _.assign() callback will get called for every new val
that we add to the final object.
*/
return _.assignWith(prev, curr, (pVal, cVal) => {
if (pVal) {
pVal.push(cVal);
return pVal;
}
return [cVal];
});
}, {});
//Convert object keyed by dimension values into an array
//of objects {target: <dimVal>, datapoints: <metric time series>}
return _.map(mergedData, (vals, key) => {
return {
target: key,
datapoints: vals
};
});
}
convertGroupByData(md, groupBy, metrics) {
const mergedData = md.map(item => {
/*
The first map() transforms the list Druid events into a list of objects
with keys of the form "<groupName>:<metric>" and values
of the form [metricValue, unixTime]
*/
const groupName = this.getGroupName(groupBy, item);
const keys = metrics.map(metric => {
return groupName + ":" + metric;
});
const vals = metrics.map(metric => {
return [
item.event[metric],
this.formatTimestamp(item.timestamp)
];
});
return _.zipObject(keys, vals);
})
.reduce((prev, curr) => {
/*
Reduce() collapses all of the mapped objects into a single
object. The keys are still of the form "<groupName>:<metric>"
and the values are arrays of all the values for the same key.
The _.assign() function merges objects together and it's callback
gets invoked for every key,value pair in the source (2nd argument).
Since our initial value for reduce() is an empty object,
the _.assign() callback will get called for every new val
that we add to the final object.
*/
return _.assignWith(prev, curr, (pVal, cVal) => {
if (pVal) {
pVal.push(cVal);
return pVal;
}
return [cVal];
});
}, {});
return _.map(mergedData, (vals, key) => {
/*
Second map converts the aggregated object into an array
*/
return {
target: key,
datapoints: vals
};
});
}
convertSelectData(data) {
const resultList = _.map(data, "result");
const eventsList = _.map(resultList, "events");
const eventList = _.flatten(eventsList);
const result = {};
for (let i = 0; i < eventList.length; i++) {
const event = eventList[i].event;
const timestamp = event.timestamp;
if (_.isEmpty(timestamp)) {
continue;
}
for (const key in event) {
if (key !== "timestamp") {
if (!result[key]) {
result[key] = { "target": key, "datapoints": [] };
}
result[key].datapoints.push([event[key], timestamp]);
}
}
}
return _.values(result);
}
dateToMoment(date, roundUp) {
if (date === 'now') {
return moment();
}
date = dateMath.parse(date, roundUp);
return moment(date.valueOf());
}
computeGranularity(from, to, maxDataPoints) {
const intervalSecs = to.unix() - from.unix();
/*
Find the smallest granularity for which there
will be fewer than maxDataPoints
*/
const granularityEntry = _.find(this.GRANULARITIES, gEntry => {
return Math.ceil(intervalSecs / gEntry[1].asSeconds()) <= maxDataPoints;
});
return granularityEntry[0];
}
roundUpStartTime(from, granularity) {
const duration = _.find(this.GRANULARITIES, gEntry => {
return gEntry[0] === granularity;
})[1];
let rounded = null;
if (granularity === 'day') {
rounded = moment(+from).startOf('day');
} else {
rounded = moment(Math.ceil((+from) / (+duration)) * (+duration));
}
return rounded;
}
replaceTemplateValues(obj, attrList) {
const substitutedVals = attrList.map(attr => {
return this.templateSrv.replace(obj[attr]);
});
return _.assign(_.clone(obj, true), _.zipObject(attrList, substitutedVals));
}
} | the_stack |
function stringPingLineByLine(str: string, cb: (str: string) => void): void {
// console.log(
// `004 ${`\u001b[${33}m${`█`}\u001b[${39}m`} stringPingLineByLine() called!`
// );
let start = null;
for (let i = 0, len = str.length; i < len; i++) {
if (["\n", "\r"].includes(str[i])) {
if (start !== null) {
console.log(
`012 ${`\u001b[${33}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`PING`}\u001b[${39}m`} "${`\u001b[${36}m${str.slice(
start,
i
)}\u001b[${39}m`}"`
);
cb(str.slice(start, i));
start = null;
// console.log(
// `020 ${`\u001b[${33}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} start = null`
// );
}
}
// not a linebreak character
else if (start === null) {
start = i;
// console.log(
// `028 ${`\u001b[${33}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} start = ${start}`
// );
}
// if an end is reached, ping the remainder
if (start !== null && !str[i + 1]) {
cb(str.slice(start, i + 1));
console.log(
`036 ${`\u001b[${33}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`PING`}\u001b[${39}m`} "${str.slice(
start,
i + 1
)}"`
);
}
}
}
interface Total {
ok: boolean;
assertsTotal: number;
assertsPassed: number;
assertsFailed: number;
suitesTotal: number;
suitesPassed: number;
suitesFailed: number;
}
class Counter {
canCount: boolean;
doNothing: boolean;
thereWereFailuresInThisSuite: null | boolean;
total: Total;
constructor() {
this.canCount = false;
this.doNothing = false;
this.thereWereFailuresInThisSuite = null;
this.total = {
ok: true,
assertsTotal: 0,
assertsPassed: 0,
assertsFailed: 0,
suitesTotal: 0,
suitesPassed: 0,
suitesFailed: 0,
};
}
readLine(lineStr: string): void {
console.log(
!this.doNothing
? `${`\u001b[${90}m${`======================================== readLine() start`}\u001b[${39}m`}`
: ""
);
// catch the --- to ...
if (!this.doNothing && lineStr.trim() === "---") {
this.doNothing = true;
// this.canCount = false;
console.log(
`087 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.doNothing = ${
this.doNothing
}; this.canCount = ${this.canCount}`
);
}
if (this.doNothing && lineStr.trim() === "...") {
this.doNothing = false;
console.log(
`095 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.doNothing = ${
this.doNothing
}`
);
}
// catch the assertion result lines
else if (!this.doNothing && this.canCount) {
if (
lineStr.trim().startsWith("ok") ||
lineStr.trim().startsWith("not ok")
) {
if (lineStr.trim().startsWith("ok")) {
this.total.assertsPassed += 1;
console.log(
`109 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} ${`\u001b[${33}m${`this.total.assertsPassed`}\u001b[${39}m`} = ${
this.total.assertsPassed
}`
);
} else if (lineStr.trim().startsWith("not ok")) {
this.total.assertsFailed += 1;
console.log(
`116 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} ${`\u001b[${33}m${`this.total.assertsFailed`}\u001b[${39}m`} = ${
this.total.assertsFailed
}`
);
if (!this.thereWereFailuresInThisSuite) {
this.thereWereFailuresInThisSuite = true;
console.log(
`123 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} ${`\u001b[${31}m${`this.thereWereFailuresInThisSuite`}\u001b[${39}m`} = ${
this.thereWereFailuresInThisSuite
}`
);
}
}
this.total.assertsTotal += 1;
console.log(
`132 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} ${`\u001b[${33}m${`this.total.assertsTotal`}\u001b[${39}m`} = ${
this.total.assertsTotal
}`
);
} else {
this.canCount = false;
console.log(
`139 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} ${`\u001b[${31}m${`this.canCount`}\u001b[${39}m`} = ${
this.canCount
}`
);
}
}
// if { is on a separate line, bump the suite count and reset the this.thereWereFailuresInThisSuite
if (!this.doNothing && lineStr.trim() === "{") {
console.log(
`149 ${`\u001b[${35}m${`█`}\u001b[${39}m`} NEW SUITE'S OPENING CURLIE CAUGHT`
);
this.total.suitesTotal += 1;
if (this.thereWereFailuresInThisSuite !== null) {
// second suite onwards already has a gathered result
if (this.thereWereFailuresInThisSuite) {
this.total.suitesFailed += 1;
console.log(
`158 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesFailed = ${
this.total.suitesFailed
}`
);
} else {
this.total.suitesPassed += 1;
console.log(
`165 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesPassed = ${
this.total.suitesPassed
}`
);
}
}
// reset:
this.thereWereFailuresInThisSuite = false;
console.log(
`176 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesTotal = ${
this.total.suitesTotal
}; this.thereWereFailuresInThisSuite = false`
);
}
// "# Subtest" opens the gates
const magicKeyw = "# Subtest";
if (!this.doNothing && !this.canCount && lineStr.includes(magicKeyw)) {
this.canCount = true;
console.log(
`187 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.canCount = ${
this.canCount
}`
);
// if suite's opening curlie is on the same line, for example:
//
// ok 1 - test/test.js # time=22.582ms { # Subtest: ...
//
// then bump the suite count
if (lineStr.slice(0, lineStr.indexOf(magicKeyw)).trim().endsWith("{")) {
this.total.suitesTotal += 1;
console.log(
`200 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesTotal = ${
this.total.suitesTotal
}`
);
// we must skip the first opening curlies and count suite passing
// for all others
if (this.thereWereFailuresInThisSuite === null) {
// if it's first suite's opening curlie
this.thereWereFailuresInThisSuite = false;
console.log(
`211 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.thereWereFailuresInThisSuite = ${
this.thereWereFailuresInThisSuite
}`
);
} else if (this.thereWereFailuresInThisSuite) {
this.total.suitesFailed += 1;
this.thereWereFailuresInThisSuite = false;
console.log(
`219 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesFailed = ${
this.total.suitesFailed
}; this.thereWereFailuresInThisSuite = ${
this.thereWereFailuresInThisSuite
}`
);
} else {
this.total.suitesPassed += 1;
console.log(
`228 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesPassed = ${
this.total.suitesPassed
}`
);
}
}
}
console.log(
!this.doNothing
? `${`\u001b[${90}m${`---------------------------------------- readLine() end`}\u001b[${39}m`}`
: ""
);
console.log(
!this.doNothing
? `${`\u001b[${90}m${`this.canCount:`}\u001b[${39}m`} ${`\u001b[${
this.canCount ? 32 : 31
}m${this.canCount}\u001b[${39}m`}`
: ""
);
console.log(
!this.doNothing
? `${`\u001b[${90}m${`this.doNothing:`}\u001b[${39}m`} ${`\u001b[${
this.doNothing ? 32 : 31
}m${this.doNothing}\u001b[${39}m`}`
: ""
);
console.log(
!this.doNothing
? `${`\u001b[${90}m${`this.thereWereFailuresInThisSuite:`}\u001b[${39}m`} ${`\u001b[${
this.thereWereFailuresInThisSuite ? 32 : 31
}m${this.thereWereFailuresInThisSuite}\u001b[${39}m`}`
: ""
);
console.log(
!this.doNothing
? `${`\u001b[${90}m${`this.total:`}\u001b[${39}m`} ${`\u001b[${90}m${JSON.stringify(
this.total,
null,
0
)}\u001b[${39}m`}`
: ""
);
}
getTotal(): Total {
if (this.thereWereFailuresInThisSuite) {
this.total.suitesFailed += 1;
this.thereWereFailuresInThisSuite = false;
console.log(
`278 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET`}\u001b[${39}m`} this.total.suitesFailed = ${
this.total.suitesFailed
}; this.thereWereFailuresInThisSuite = ${
this.thereWereFailuresInThisSuite
}`
);
} else if (this.total.suitesTotal) {
this.total.suitesPassed += 1;
}
if (!this.total.suitesTotal && this.total.assertsTotal) {
console.log(
`290 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${36}m${`SUITE TOTALS ARE ZERO, LET'S FIX THIS`}\u001b[${39}m`}`
);
this.total.suitesTotal = 1;
console.log(
`294 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesTotal = 1`
);
if (this.thereWereFailuresInThisSuite) {
this.total.suitesFailed = 1;
console.log(
`299 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesFailed = 1`
);
} else {
this.total.suitesPassed = 1;
console.log(
`304 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`SET `}\u001b[${39}m`} this.total.suitesPassed = 1`
);
}
}
console.log(
`309 ${`\u001b[${35}m${`█`}\u001b[${39}m`} ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`}:\n${JSON.stringify(
this.total,
null,
4
)}`
);
return { ...this.total };
}
}
export { stringPingLineByLine, Counter }; | the_stack |
module android.text {
import Paint = android.graphics.Paint;
import LeadingMarginSpan = android.text.style.LeadingMarginSpan;
import LeadingMarginSpan2 = android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
import LineHeightSpan = android.text.style.LineHeightSpan;
import MetricAffectingSpan = android.text.style.MetricAffectingSpan;
import TabStopSpan = android.text.style.TabStopSpan;
import Log = android.util.Log;
import Integer = java.lang.Integer;
import System = java.lang.System;
import Layout = android.text.Layout;
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;
import TextUtils = android.text.TextUtils;
/**
* StaticLayout is a Layout for text that will not be edited after it
* is laid out. Use {@link DynamicLayout} for text that may change.
* <p>This is used by widgets to control text layout. You should not need
* to use this class directly unless you are implementing your own widget
* or custom display object, or would be tempted to call
* {@link android.graphics.Canvas#drawText(java.lang.CharSequence, int, int,
* float, float, android.graphics.Paint)
* Canvas.drawText()} directly.</p>
*/
export class StaticLayout extends Layout {
static TAG:string = "StaticLayout";
/**
* @hide
*/
constructor(source:String, bufstart:number, bufend:number, paint:TextPaint, outerwidth:number, align:Layout.Alignment,
textDir:TextDirectionHeuristic, spacingmult:number, spacingadd:number, includepad:boolean,
ellipsize:TextUtils.TruncateAt=null, ellipsizedWidth=0, maxLines=Integer.MAX_VALUE) {
super((ellipsize == null) ? source : (Spanned.isImplements(source)) ? new Layout.SpannedEllipsizer(source) : new Layout.Ellipsizer(source),
paint, outerwidth, align, textDir, spacingmult, spacingadd);
/* package */
//constructor( text:CharSequence) {
// super(text, null, 0, null, 0, 0);
// this.mColumns = StaticLayout.COLUMNS_ELLIPSIZE;
// this.mLines = androidui.util.ArrayCreator.newNumberArray(ArrayUtils.idealIntArraySize(2 * this.mColumns));
// this.mLineDirections = new Array<Layout.Directions>(ArrayUtils.idealIntArraySize(2 * this.mColumns));
// // FIXME This is never recycled
// this.mMeasured = MeasuredText.obtain();
//}
if(source==null){
this.mColumns = StaticLayout.COLUMNS_ELLIPSIZE;
this.mLines = androidui.util.ArrayCreator.newNumberArray((2 * this.mColumns));
this.mLineDirections = new Array<Layout.Directions>((2 * this.mColumns));
// FIXME This is never recycled
this.mMeasured = MeasuredText.obtain();
return;
}
/*
* This is annoying, but we can't refer to the layout until
* superclass construction is finished, and the superclass
* constructor wants the reference to the display text.
*
* This will break if the superclass constructor ever actually
* cares about the content instead of just holding the reference.
*/
if (ellipsize != null) {
let e:Layout.Ellipsizer = <Layout.Ellipsizer> this.getText();
e.mLayout = this;
e.mWidth = ellipsizedWidth;
e.mMethod = ellipsize;
this.mEllipsizedWidth = ellipsizedWidth;
this.mColumns = StaticLayout.COLUMNS_ELLIPSIZE;
} else {
this.mColumns = StaticLayout.COLUMNS_NORMAL;
this.mEllipsizedWidth = outerwidth;
}
this.mLines = androidui.util.ArrayCreator.newNumberArray(2 * this.mColumns);
this.mLineDirections = new Array<Layout.Directions>(2 * this.mColumns);
this.mMaximumVisibleLineCount = maxLines;
this.mMeasured = MeasuredText.obtain();
this.generate(source, bufstart, bufend, paint, outerwidth, textDir, spacingmult, spacingadd, includepad, includepad, ellipsizedWidth, ellipsize);
this.mMeasured = MeasuredText.recycle(this.mMeasured);
this.mFontMetricsInt = null;
}
/* package */
generate(source:String, bufStart:number, bufEnd:number, paint:TextPaint, outerWidth:number,
textDir:TextDirectionHeuristic, spacingmult:number, spacingadd:number, includepad:boolean,
trackpad:boolean, ellipsizedWidth:number, ellipsize:TextUtils.TruncateAt):void {
this.mLineCount = 0;
let v:number = 0;
let needMultiply:boolean = (spacingmult != 1 || spacingadd != 0);
let fm:Paint.FontMetricsInt = this.mFontMetricsInt;
let chooseHtv:number[] = null;
let measured:MeasuredText = this.mMeasured;
let spanned:Spanned = null;
if (Spanned.isImplements(source))
spanned = <Spanned> source;
// XXX
let DEFAULT_DIR:number = StaticLayout.DIR_LEFT_TO_RIGHT;
let paraEnd:number;
for (let paraStart:number = bufStart; paraStart <= bufEnd; paraStart = paraEnd) {
paraEnd = source.substring(0, bufEnd).indexOf(StaticLayout.CHAR_NEW_LINE, paraStart);
if (paraEnd < 0)
paraEnd = bufEnd;
else
paraEnd++;
let firstWidthLineLimit:number = this.mLineCount + 1;
let firstWidth:number = outerWidth;
let restWidth:number = outerWidth;
let chooseHt:LineHeightSpan[] = null;
if (spanned != null) {
let sp:LeadingMarginSpan[] = StaticLayout.getParagraphSpans<LeadingMarginSpan>(spanned, paraStart, paraEnd, LeadingMarginSpan.type);
for (let i:number = 0; i < sp.length; i++) {
let lms:LeadingMarginSpan = sp[i];
firstWidth -= sp[i].getLeadingMargin(true);
restWidth -= sp[i].getLeadingMargin(false);
// paragraph.
if (LeadingMarginSpan2.isImpl(lms)) {
let lms2:LeadingMarginSpan2 = <LeadingMarginSpan2> lms;
let lmsFirstLine:number = this.getLineForOffset(spanned.getSpanStart(lms2));
firstWidthLineLimit = lmsFirstLine + lms2.getLeadingMarginLineCount();
}
}
chooseHt = StaticLayout.getParagraphSpans<LineHeightSpan>(spanned, paraStart, paraEnd, LineHeightSpan.type);
if (chooseHt.length != 0) {
if (chooseHtv == null || chooseHtv.length < chooseHt.length) {
chooseHtv = androidui.util.ArrayCreator.newNumberArray(chooseHt.length);
}
for (let i:number = 0; i < chooseHt.length; i++) {
let o:number = spanned.getSpanStart(chooseHt[i]);
if (o < paraStart) {
// starts in this layout, before the
// current paragraph
chooseHtv[i] = this.getLineTop(this.getLineForOffset(o));
} else {
// starts in this paragraph
chooseHtv[i] = v;
}
}
}
}
measured.setPara(source, paraStart, paraEnd, textDir);
let chs:string = measured.mChars;
let widths:number[] = measured.mWidths;
let chdirs:number[] = measured.mLevels;
let dir:number = measured.mDir;
let easy:boolean = measured.mEasy;
let width:number = firstWidth;
let w:number = 0;
// here is the offset of the starting character of the line we are currently measuring
let here:number = paraStart;
// ok is a character offset located after a word separator (space, tab, number...) where
// we would prefer to cut the current line. Equals to here when no such break was found.
let ok:number = paraStart;
let okWidth:number = w;
let okAscent:number = 0, okDescent:number = 0, okTop:number = 0, okBottom:number = 0;
// fit is a character offset such that the [here, fit[ range fits in the allowed width.
// We will cut the line there if no ok position is found.
let fit:number = paraStart;
let fitWidth:number = w;
let fitAscent:number = 0, fitDescent:number = 0, fitTop:number = 0, fitBottom:number = 0;
let hasTabOrEmoji:boolean = false;
let hasTab:boolean = false;
let tabStops:Layout.TabStops = null;
for (let spanStart:number = paraStart, spanEnd:number; spanStart < paraEnd; spanStart = spanEnd) {
if (spanned == null) {
spanEnd = paraEnd;
let spanLen:number = spanEnd - spanStart;
measured.addStyleRun(paint, spanLen, fm);
} else {
spanEnd = spanned.nextSpanTransition(spanStart, paraEnd, MetricAffectingSpan.type);
let spanLen:number = spanEnd - spanStart;
let spans:MetricAffectingSpan[] = spanned.getSpans<MetricAffectingSpan>(spanStart, spanEnd, MetricAffectingSpan.type);
spans = TextUtils.removeEmptySpans(spans, spanned, MetricAffectingSpan.type);
measured.addStyleRun(paint, spans, spanLen, fm);
}
let fmTop:number = fm.top;
let fmBottom:number = fm.bottom;
let fmAscent:number = fm.ascent;
let fmDescent:number = fm.descent;
for (let j:number = spanStart; j < spanEnd; j++) {
let c:string = chs[j - paraStart];
if (c == StaticLayout.CHAR_NEW_LINE) {
// intentionally left empty
} else if (c == StaticLayout.CHAR_TAB) {
if (hasTab == false) {
hasTab = true;
hasTabOrEmoji = true;
if (spanned != null) {
// First tab this para, check for tabstops
let spans:TabStopSpan[] = StaticLayout.getParagraphSpans<TabStopSpan>(spanned, paraStart, paraEnd, TabStopSpan.type);
if (spans.length > 0) {
tabStops = new Layout.TabStops(StaticLayout.TAB_INCREMENT, spans);
}
}
}
if (tabStops != null) {
w = tabStops.nextTab(w);
} else {
w = StaticLayout.TabStops.nextDefaultStop(w, StaticLayout.TAB_INCREMENT);
}
} else if (c.codePointAt(0) >= StaticLayout.CHAR_FIRST_HIGH_SURROGATE
&& c.codePointAt(0) <= StaticLayout.CHAR_LAST_LOW_SURROGATE && j + 1 < spanEnd) {
let emoji:number = chs.codePointAt(j - paraStart);
//if (emoji >= StaticLayout.MIN_EMOJI && emoji <= StaticLayout.MAX_EMOJI) {
// let bm:Bitmap = StaticLayout.EMOJI_FACTORY.getBitmapFromAndroidPua(emoji);
// if (bm != null) {
// let whichPaint:Paint;
// if (spanned == null) {
// whichPaint = paint;
// } else {
// whichPaint = this.mWorkPaint;
// }
// let wid:number = bm.getWidth() * -whichPaint.ascent() / bm.getHeight();
// w += wid;
// hasTabOrEmoji = true;
// j++;
// } else {
// w += widths[j - paraStart];
// }
//} else {
w += widths[j - paraStart];
//}
} else {
w += widths[j - paraStart];
}
let isSpaceOrTab:boolean = c == StaticLayout.CHAR_SPACE || c == StaticLayout.CHAR_TAB || c == StaticLayout.CHAR_ZWSP;
if (w <= width || isSpaceOrTab) {
fitWidth = w;
fit = j + 1;
if (fmTop < fitTop)
fitTop = fmTop;
if (fmAscent < fitAscent)
fitAscent = fmAscent;
if (fmDescent > fitDescent)
fitDescent = fmDescent;
if (fmBottom > fitBottom)
fitBottom = fmBottom;
// From the Unicode Line Breaking Algorithm (at least approximately)
let isLineBreak:boolean = isSpaceOrTab || // / is class SY and - is class HY, except when followed by a digit
((c == StaticLayout.CHAR_SLASH || c == StaticLayout.CHAR_HYPHEN) && (j + 1 >= spanEnd ||
!Number.isInteger(Number.parseInt(chs[j + 1 - paraStart])))) || // (non-starters), which can be broken after but not before
(c.codePointAt(0) >= StaticLayout.CHAR_FIRST_CJK.codePointAt(0) && StaticLayout.isIdeographic(c, true) && j + 1 < spanEnd && StaticLayout.isIdeographic(chs[j + 1 - paraStart], false));
if (isLineBreak) {
okWidth = w;
ok = j + 1;
if (fitTop < okTop)
okTop = fitTop;
if (fitAscent < okAscent)
okAscent = fitAscent;
if (fitDescent > okDescent)
okDescent = fitDescent;
if (fitBottom > okBottom)
okBottom = fitBottom;
}
} else {
const moreChars:boolean = (j + 1 < spanEnd);
let endPos:number;
let above:number, below:number, top:number, bottom:number;
let currentTextWidth:number;
if (ok != here) {
endPos = ok;
above = okAscent;
below = okDescent;
top = okTop;
bottom = okBottom;
currentTextWidth = okWidth;
} else if (fit != here) {
endPos = fit;
above = fitAscent;
below = fitDescent;
top = fitTop;
bottom = fitBottom;
currentTextWidth = fitWidth;
} else {
endPos = here + 1;
above = fm.ascent;
below = fm.descent;
top = fm.top;
bottom = fm.bottom;
currentTextWidth = widths[here - paraStart];
}
v = this.out(source, here, endPos, above, below, top, bottom, v, spacingmult, spacingadd, chooseHt, chooseHtv, fm, hasTabOrEmoji, needMultiply, chdirs, dir, easy, bufEnd, includepad, trackpad, chs, widths, paraStart, ellipsize, ellipsizedWidth, currentTextWidth, paint, moreChars);
here = endPos;
// restart j-span loop from here, compensating for the j++
j = here - 1;
ok = fit = here;
w = 0;
fitAscent = fitDescent = fitTop = fitBottom = 0;
okAscent = okDescent = okTop = okBottom = 0;
if (--firstWidthLineLimit <= 0) {
width = restWidth;
}
if (here < spanStart) {
// The text was cut before the beginning of the current span range.
// Exit the span loop, and get spanStart to start over from here.
measured.setPos(here);
spanEnd = here;
break;
}
if (this.mLineCount >= this.mMaximumVisibleLineCount) {
break;
}
}
}
}
if (paraEnd != here && this.mLineCount < this.mMaximumVisibleLineCount) {
if ((fitTop | fitBottom | fitDescent | fitAscent) == 0) {
paint.getFontMetricsInt(fm);
fitTop = fm.top;
fitBottom = fm.bottom;
fitAscent = fm.ascent;
fitDescent = fm.descent;
}
// Log.e("text", "output rest " + here + " to " + end);
v = this.out(source, here, paraEnd, fitAscent, fitDescent, fitTop, fitBottom, v, spacingmult, spacingadd, chooseHt, chooseHtv, fm, hasTabOrEmoji, needMultiply, chdirs, dir, easy, bufEnd, includepad, trackpad, chs, widths, paraStart, ellipsize, ellipsizedWidth, w, paint, paraEnd != bufEnd);
}
paraStart = paraEnd;
if (paraEnd == bufEnd)
break;
}
if ((bufEnd == bufStart || source.charAt(bufEnd - 1) == StaticLayout.CHAR_NEW_LINE) && this.mLineCount < this.mMaximumVisibleLineCount) {
// Log.e("text", "output last " + bufEnd);
measured.setPara(source, bufStart, bufEnd, textDir);
paint.getFontMetricsInt(fm);
v = this.out(source, bufEnd, bufEnd, fm.ascent, fm.descent, fm.top, fm.bottom, v, spacingmult, spacingadd, null, null, fm, false, needMultiply, measured.mLevels, measured.mDir, measured.mEasy, bufEnd, includepad, trackpad, null, null, bufStart, ellipsize, ellipsizedWidth, 0, paint, false);
}
}
/**
* Returns true if the specified character is one of those specified
* as being Ideographic (class ID) by the Unicode Line Breaking Algorithm
* (http://www.unicode.org/unicode/reports/tr14/), and is therefore OK
* to break between a pair of.
*
* @param includeNonStarters also return true for category NS
* (non-starters), which can be broken
* after but not before.
*/
private static isIdeographic(c:string, includeNonStarters:boolean):boolean {
let code = c.codePointAt(0);
if (code >= '⺀'.codePointAt(0) && code <= ''.codePointAt(0)) {
// CJK, KANGXI RADICALS, DESCRIPTION SYMBOLS
return true;
}
if (c == ' ') {
// IDEOGRAPHIC SPACE
return true;
}
if (code >= ''.codePointAt(0) && code <= 'ゟ'.codePointAt(0)) {
if (!includeNonStarters) {
switch(c) {
// # HIRAGANA LETTER SMALL A
case 'ぁ':
// # HIRAGANA LETTER SMALL I
case 'ぃ':
// # HIRAGANA LETTER SMALL U
case 'ぅ':
// # HIRAGANA LETTER SMALL E
case 'ぇ':
// # HIRAGANA LETTER SMALL O
case 'ぉ':
// # HIRAGANA LETTER SMALL TU
case 'っ':
// # HIRAGANA LETTER SMALL YA
case 'ゃ':
// # HIRAGANA LETTER SMALL YU
case 'ゅ':
// # HIRAGANA LETTER SMALL YO
case 'ょ':
// # HIRAGANA LETTER SMALL WA
case 'ゎ':
// # HIRAGANA LETTER SMALL KA
case 'ゕ':
// # HIRAGANA LETTER SMALL KE
case 'ゖ':
// # KATAKANA-HIRAGANA VOICED SOUND MARK
case '゛':
// # KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
case '゜':
// # HIRAGANA ITERATION MARK
case 'ゝ':
case // # HIRAGANA VOICED ITERATION MARK
'ゞ':
return false;
}
}
// Hiragana (except small characters)
return true;
}
if (code >= '゠'.codePointAt(0) && code <= 'ヿ'.codePointAt(0)) {
if (!includeNonStarters) {
switch(c) {
// # KATAKANA-HIRAGANA DOUBLE HYPHEN
case '゠':
// # KATAKANA LETTER SMALL A
case 'ァ':
// # KATAKANA LETTER SMALL I
case 'ィ':
// # KATAKANA LETTER SMALL U
case 'ゥ':
// # KATAKANA LETTER SMALL E
case 'ェ':
// # KATAKANA LETTER SMALL O
case 'ォ':
// # KATAKANA LETTER SMALL TU
case 'ッ':
// # KATAKANA LETTER SMALL YA
case 'ャ':
// # KATAKANA LETTER SMALL YU
case 'ュ':
// # KATAKANA LETTER SMALL YO
case 'ョ':
// # KATAKANA LETTER SMALL WA
case 'ヮ':
// # KATAKANA LETTER SMALL KA
case 'ヵ':
// # KATAKANA LETTER SMALL KE
case 'ヶ':
// # KATAKANA MIDDLE DOT
case '・':
// # KATAKANA-HIRAGANA PROLONGED SOUND MARK
case 'ー':
// # KATAKANA ITERATION MARK
case 'ヽ':
case // # KATAKANA VOICED ITERATION MARK
'ヾ':
return false;
}
}
// Katakana (except small characters)
return true;
}
if (code >= '㐀'.codePointAt(0) && code <= '䶵'.codePointAt(0)) {
// CJK UNIFIED IDEOGRAPHS EXTENSION A
return true;
}
if (code >= '一'.codePointAt(0) && code <= '龻'.codePointAt(0)) {
// CJK UNIFIED IDEOGRAPHS
return true;
}
if (code >= '豈'.codePointAt(0) && code <= '龎'.codePointAt(0)) {
// CJK COMPATIBILITY IDEOGRAPHS
return true;
}
if (code >= 'ꀀ'.codePointAt(0) && code <= ''.codePointAt(0)) {
// YI SYLLABLES
return true;
}
if (code >= '꒐'.codePointAt(0) && code <= ''.codePointAt(0)) {
// YI RADICALS
return true;
}
if (code >= '﹢'.codePointAt(0) && code <= '﹦'.codePointAt(0)) {
// SMALL PLUS SIGN to SMALL EQUALS SIGN
return true;
}
if (code >= '0'.codePointAt(0) && code <= '9'.codePointAt(0)) {
// WIDE DIGITS
return true;
}
return false;
}
private out(text:String, start:number, end:number, above:number, below:number, top:number, bottom:number, v:number,
spacingmult:number, spacingadd:number, chooseHt:LineHeightSpan[], chooseHtv:number[], fm:Paint.FontMetricsInt,
hasTabOrEmoji:boolean, needMultiply:boolean, chdirs:number[], dir:number, easy:boolean, bufEnd:number,
includePad:boolean, trackPad:boolean, chs:string, widths:number[], widthStart:number, ellipsize:TextUtils.TruncateAt,
ellipsisWidth:number, textWidth:number, paint:TextPaint, moreChars:boolean):number {
let j:number = this.mLineCount;
let off:number = j * this.mColumns;
let want:number = off + this.mColumns + StaticLayout.TOP;
let lines:number[] = this.mLines;
if (want >= lines.length) {
let nlen:number = (want + 1);
let grow:number[] = androidui.util.ArrayCreator.newNumberArray(nlen);
System.arraycopy(lines, 0, grow, 0, lines.length);
this.mLines = grow;
lines = grow;
let grow2:Layout.Directions[] = new Array<Layout.Directions>(nlen);
System.arraycopy(this.mLineDirections, 0, grow2, 0, this.mLineDirections.length);
this.mLineDirections = grow2;
}
if (chooseHt != null) {
fm.ascent = above;
fm.descent = below;
fm.top = top;
fm.bottom = bottom;
for (let i:number = 0; i < chooseHt.length; i++) {
//if (chooseHt[i] instanceof LineHeightSpan.WithDensity) {
(<LineHeightSpan.WithDensity> chooseHt[i]).chooseHeight(text, start, end, chooseHtv[i], v, fm, paint);
//} else {
// chooseHt[i].chooseHeight(text, start, end, chooseHtv[i], v, fm);
//}
}
above = fm.ascent;
below = fm.descent;
top = fm.top;
bottom = fm.bottom;
}
if (j == 0) {
if (trackPad) {
this.mTopPadding = top - above;
}
if (includePad) {
above = top;
}
}
if (end == bufEnd) {
if (trackPad) {
this.mBottomPadding = bottom - below;
}
if (includePad) {
below = bottom;
}
}
let extra:number;
if (needMultiply) {
let ex:number = (below - above) * (spacingmult - 1) + spacingadd;
if (ex >= 0) {
extra = Math.floor((ex + StaticLayout.EXTRA_ROUNDING));
} else {
extra = -Math.floor((-ex + StaticLayout.EXTRA_ROUNDING));
}
} else {
extra = 0;
}
lines[off + StaticLayout.START] = start;
lines[off + StaticLayout.TOP] = v;
lines[off + StaticLayout.DESCENT] = below + extra;
v += (below - above) + extra;
lines[off + this.mColumns + StaticLayout.START] = end;
lines[off + this.mColumns + StaticLayout.TOP] = v;
if (hasTabOrEmoji)
lines[off + StaticLayout.TAB] |= StaticLayout.TAB_MASK;
lines[off + StaticLayout.DIR] |= dir << StaticLayout.DIR_SHIFT;
let linedirs:Layout.Directions = StaticLayout.DIRS_ALL_LEFT_TO_RIGHT;
// RTL paragraph. Make sure easy is false if this is the case.
//if (easy) {
this.mLineDirections[j] = linedirs;
//} else {
// this.mLineDirections[j] = AndroidBidi.directions(dir, chdirs, start - widthStart, chs, start - widthStart, end - start);
//}
if (ellipsize != null) {
// If there is only one line, then do any type of ellipsis except when it is MARQUEE
// if there are multiple lines, just allow END ellipsis on the last line
let firstLine:boolean = (j == 0);
let currentLineIsTheLastVisibleOne:boolean = (j + 1 == this.mMaximumVisibleLineCount);
let forceEllipsis:boolean = moreChars && (this.mLineCount + 1 == this.mMaximumVisibleLineCount);
let doEllipsis:boolean = (((this.mMaximumVisibleLineCount == 1 && moreChars) || (firstLine && !moreChars)) && ellipsize != TextUtils.TruncateAt.MARQUEE) || (!firstLine && (currentLineIsTheLastVisibleOne || !moreChars) && ellipsize == TextUtils.TruncateAt.END);
if (doEllipsis) {
this.calculateEllipsis(start, end, widths, widthStart, ellipsisWidth, ellipsize, j, textWidth, paint, forceEllipsis);
}
}
this.mLineCount++;
return v;
}
private calculateEllipsis(lineStart:number, lineEnd:number, widths:number[], widthStart:number, avail:number, where:TextUtils.TruncateAt, line:number, textWidth:number, paint:TextPaint, forceEllipsis:boolean):void {
if (textWidth <= avail && !forceEllipsis) {
// Everything fits!
this.mLines[this.mColumns * line + StaticLayout.ELLIPSIS_START] = 0;
this.mLines[this.mColumns * line + StaticLayout.ELLIPSIS_COUNT] = 0;
return;
}
let ellipsisWidth:number = paint.measureText(
(where == TextUtils.TruncateAt.END_SMALL) ? StaticLayout.ELLIPSIS_TWO_DOTS[0] : StaticLayout.ELLIPSIS_NORMAL[0], 0, 1);
let ellipsisStart:number = 0;
let ellipsisCount:number = 0;
let len:number = lineEnd - lineStart;
// We only support start ellipsis on a single line
if (where == TextUtils.TruncateAt.START) {
if (this.mMaximumVisibleLineCount == 1) {
let sum:number = 0;
let i:number;
for (i = len; i >= 0; i--) {
let w:number = widths[i - 1 + lineStart - widthStart];
if (w + sum + ellipsisWidth > avail) {
break;
}
sum += w;
}
ellipsisStart = 0;
ellipsisCount = i;
} else {
//if (Log.isLoggable(StaticLayout.TAG, Log.WARN)) {
// Log.w(StaticLayout.TAG, "Start Ellipsis only supported with one line");
//}
}
} else if (where == TextUtils.TruncateAt.END || where == TextUtils.TruncateAt.MARQUEE || where == TextUtils.TruncateAt.END_SMALL) {
let sum:number = 0;
let i:number;
for (i = 0; i < len; i++) {
let w:number = widths[i + lineStart - widthStart];
if (w + sum + ellipsisWidth > avail) {
break;
}
sum += w;
}
ellipsisStart = i;
ellipsisCount = len - i;
if (forceEllipsis && ellipsisCount == 0 && len > 0) {
ellipsisStart = len - 1;
ellipsisCount = 1;
}
} else {
// where = TextUtils.TruncateAt.MIDDLE We only support middle ellipsis on a single line
if (this.mMaximumVisibleLineCount == 1) {
let lsum:number = 0, rsum:number = 0;
let left:number = 0, right:number = len;
let ravail:number = (avail - ellipsisWidth) / 2;
for (right = len; right >= 0; right--) {
let w:number = widths[right - 1 + lineStart - widthStart];
if (w + rsum > ravail) {
break;
}
rsum += w;
}
let lavail:number = avail - ellipsisWidth - rsum;
for (left = 0; left < right; left++) {
let w:number = widths[left + lineStart - widthStart];
if (w + lsum > lavail) {
break;
}
lsum += w;
}
ellipsisStart = left;
ellipsisCount = right - left;
} else {
//if (Log.isLoggable(StaticLayout.TAG, Log.WARN)) {
// Log.w(StaticLayout.TAG, "Middle Ellipsis only supported with one line");
//}
}
}
this.mLines[this.mColumns * line + StaticLayout.ELLIPSIS_START] = ellipsisStart;
this.mLines[this.mColumns * line + StaticLayout.ELLIPSIS_COUNT] = ellipsisCount;
}
// Override the base class so we can directly access our members,
// rather than relying on member functions.
// The logic mirrors that of Layout.getLineForVertical
// FIXME: It may be faster to do a linear search for layouts without many lines.
getLineForVertical(vertical:number):number {
let high:number = this.mLineCount;
let low:number = -1;
let guess:number;
let lines:number[] = this.mLines;
while (high - low > 1) {
guess = (high + low) >> 1;
if (lines[this.mColumns * guess + StaticLayout.TOP] > vertical) {
high = guess;
} else {
low = guess;
}
}
if (low < 0) {
return 0;
} else {
return low;
}
}
getLineCount():number {
return this.mLineCount;
}
getLineTop(line:number):number {
let top:number = this.mLines[this.mColumns * line + StaticLayout.TOP];
if (this.mMaximumVisibleLineCount > 0 && line >= this.mMaximumVisibleLineCount && line != this.mLineCount) {
top += this.getBottomPadding();
}
return top;
}
getLineDescent(line:number):number {
let descent:number = this.mLines[this.mColumns * line + StaticLayout.DESCENT];
if (// -1 intended
this.mMaximumVisibleLineCount > 0 && line >= this.mMaximumVisibleLineCount - 1 && line != this.mLineCount) {
descent += this.getBottomPadding();
}
return descent;
}
getLineStart(line:number):number {
return this.mLines[this.mColumns * line + StaticLayout.START] & StaticLayout.START_MASK;
}
getParagraphDirection(line:number):number {
return this.mLines[this.mColumns * line + StaticLayout.DIR] >> StaticLayout.DIR_SHIFT;
}
getLineContainsTab(line:number):boolean {
return (this.mLines[this.mColumns * line + StaticLayout.TAB] & StaticLayout.TAB_MASK) != 0;
}
getLineDirections(line:number):Layout.Directions {
return this.mLineDirections[line];
}
getTopPadding():number {
return this.mTopPadding;
}
getBottomPadding():number {
return this.mBottomPadding;
}
getEllipsisCount(line:number):number {
if (this.mColumns < StaticLayout.COLUMNS_ELLIPSIZE) {
return 0;
}
return this.mLines[this.mColumns * line + StaticLayout.ELLIPSIS_COUNT];
}
getEllipsisStart(line:number):number {
if (this.mColumns < StaticLayout.COLUMNS_ELLIPSIZE) {
return 0;
}
return this.mLines[this.mColumns * line + StaticLayout.ELLIPSIS_START];
}
getEllipsizedWidth():number {
return this.mEllipsizedWidth;
}
prepare():void {
this.mMeasured = MeasuredText.obtain();
}
finish():void {
this.mMeasured = MeasuredText.recycle(this.mMeasured);
}
private mLineCount:number = 0;
private mTopPadding:number = 0;
private mBottomPadding:number = 0;
private mColumns:number = 0;
private mEllipsizedWidth:number = 0;
private static COLUMNS_NORMAL:number = 3;
private static COLUMNS_ELLIPSIZE:number = 5;
private static START:number = 0;
private static DIR:number = StaticLayout.START;
private static TAB:number = StaticLayout.START;
private static TOP:number = 1;
private static DESCENT:number = 2;
private static ELLIPSIS_START:number = 3;
private static ELLIPSIS_COUNT:number = 4;
private mLines:number[];
private mLineDirections:Layout.Directions[];
private mMaximumVisibleLineCount:number = Integer.MAX_VALUE;
private static START_MASK:number = 0x1FFFFFFF;
private static DIR_SHIFT:number = 30;
private static TAB_MASK:number = 0x20000000;
// same as Layout, but that's private
//private static TAB_INCREMENT:number = 20;
private static CHAR_FIRST_CJK = '⺀';
private static CHAR_NEW_LINE = '\n';
private static CHAR_TAB = '\t';
private static CHAR_SPACE = ' ';
private static CHAR_SLASH = '/';
private static CHAR_HYPHEN = '-';
private static CHAR_ZWSP = '';
private static EXTRA_ROUNDING:number = 0.5;
private static CHAR_FIRST_HIGH_SURROGATE:number = 0xD800;
private static CHAR_LAST_LOW_SURROGATE:number = 0xDFFF;
/*
* This is reused across calls to generate()
*/
private mMeasured:MeasuredText;
private mFontMetricsInt:Paint.FontMetricsInt = new Paint.FontMetricsInt();
}
} | the_stack |
import Log, { IGroup, IHeader, ILogOptions } from './Log'
import isUndef from 'licia/isUndef'
import perfNow from 'licia/perfNow'
import now from 'licia/now'
import isStr from 'licia/isStr'
import extend from 'licia/extend'
import uniqId from 'licia/uniqId'
import isRegExp from 'licia/isRegExp'
import isFn from 'licia/isFn'
import $ from 'licia/$'
import Stack from 'licia/Stack'
import isEmpty from 'licia/isEmpty'
import contain from 'licia/contain'
import copy from 'licia/copy'
import each from 'licia/each'
import toArr from 'licia/toArr'
import keys from 'licia/keys'
import last from 'licia/last'
import throttle from 'licia/throttle'
import xpath from 'licia/xpath'
import lowerCase from 'licia/lowerCase'
import dateFormat from 'licia/dateFormat'
import isHidden from 'licia/isHidden'
import stripIndent from 'licia/stripIndent'
import types from 'licia/types'
import { classPrefix } from '../share/util'
import Component from '../share/Component'
import raf = require('licia/raf')
const u = navigator.userAgent
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
const c = classPrefix('console')
let id = 0
type InsertOptions = Partial<ILogOptions> & { type: string; args: any[] }
type AsyncItem = [
string | InsertOptions,
any[] | undefined,
IHeader | undefined
]
interface IOptions {
maxNum?: number
asyncRender?: boolean
showHeader?: boolean
accessGetter?: boolean
unenumerable?: boolean
lazyEvaluation?: boolean
filter?: string | RegExp | types.AnyFn
}
export default class Console extends Component<IOptions> {
renderViewport: (options?: any) => void
private $el: $.$
private el: HTMLElement
private $fakeEl: $.$
private fakeEl: HTMLElement
private $space: $.$
private space: HTMLElement
private spaceHeight = 0
private topSpaceHeight = 0
// @ts-ignore
private bottomSpaceHeight = 0
private lastScrollTop = 0
private lastTimestamp = 0
private speedToleranceFactor = 100
private maxSpeedTolerance = 2000
private minSpeedTolerance = 100
private logs: Log[] = []
private displayLogs: Log[] = []
private timer: { [key: string]: number } = {}
private counter: { [key: string]: number } = {}
private lastLog?: Log
private asyncList: AsyncItem[] = []
private asyncTimer: any = null
private isAtBottom = true
private groupStack = new Stack()
private global: any
constructor(
container: HTMLElement,
{
maxNum = 0,
asyncRender = true,
showHeader = false,
filter = 'all',
accessGetter = false,
unenumerable = true,
lazyEvaluation = true,
}: IOptions = {}
) {
super(container, { compName: 'console' })
this.initTpl()
this.options = {
maxNum,
asyncRender,
showHeader,
filter,
accessGetter,
unenumerable,
lazyEvaluation,
}
this.$el = this.find('.logs')
this.el = this.$el.get(0) as HTMLElement
this.$fakeEl = this.find('.fake-logs')
this.fakeEl = this.$fakeEl.get(0) as HTMLElement
this.$space = this.find('.logs-space')
this.space = this.$space.get(0) as HTMLElement
// For android slowing rendering
if (isAndroid) {
this.speedToleranceFactor = 800
this.maxSpeedTolerance = 3000
this.minSpeedTolerance = 800
}
this.renderViewport = throttle((options) => {
this._renderViewport(options)
}, 16)
// https://developers.google.cn/web/tools/chrome-devtools/console/utilities
this.global = {
copy(value: string) {
if (!isStr(value)) value = JSON.stringify(value, null, 2)
copy(value)
},
$(selectors: string) {
return document.querySelector(selectors)
},
$$(selectors: string) {
return toArr(document.querySelectorAll(selectors))
},
$x(path: string) {
return xpath(path)
},
clear: () => {
this.clear()
},
dir: (value: any) => {
this.dir(value)
},
table: (data: any, columns: any) => {
this.table(data, columns)
},
keys,
}
this.bindEvent()
}
setGlobal(name: string, val: any) {
this.global[name] = val
}
destroy() {
super.destroy()
this.$container.off('scroll', this.onScroll)
}
count(label = 'default') {
const { counter } = this
!isUndef(counter[label]) ? counter[label]++ : (counter[label] = 1)
this.info(`${label}: ${counter[label]}`)
}
countReset(label = 'default') {
this.counter[label] = 0
}
assert(...args: any[]) {
if (isEmpty(args)) return
const exp = args.shift()
if (!exp) {
if (args.length === 0) args.unshift('console.assert')
args.unshift('Assertion failed: ')
this.insert('error', args)
}
}
log(...args: any[]) {
if (isEmpty(args)) return
this.insert('log', args)
}
debug(...args: any[]) {
if (isEmpty(args)) return
this.insert('debug', args)
}
dir(obj: any) {
if (isUndef(obj)) return
this.insert('dir', [obj])
}
table(...args: any[]) {
if (isEmpty(args)) return
this.insert('table', args)
}
time(name = 'default') {
if (this.timer[name]) {
return this.insert('warn', [`Timer '${name}' already exists`])
}
this.timer[name] = perfNow()
}
timeLog(name = 'default') {
const startTime = this.timer[name]
if (!startTime) {
return this.insert('warn', [`Timer '${name}' does not exist`])
}
this.info(`${name}: ${perfNow() - startTime}ms`)
}
timeEnd(name = 'default') {
this.timeLog(name)
delete this.timer[name]
}
clear(silent = false) {
this.logs = []
this.displayLogs = []
this.lastLog = undefined
this.counter = {}
this.timer = {}
this.groupStack = new Stack()
this.asyncList = []
if (this.asyncTimer) {
clearTimeout(this.asyncTimer)
this.asyncTimer = null
}
if (silent) {
this.render()
} else {
this.insert('log', [
'%cConsole was cleared',
'color:#808080;font-style:italic;',
])
}
}
info(...args: any[]) {
if (isEmpty(args)) return
this.insert('log', args)
}
error(...args: any[]) {
if (isEmpty(args)) return
this.insert('error', args)
}
warn(...args: any[]) {
if (isEmpty(args)) return
this.insert('warn', args)
}
group(...args: any[]) {
this.insert({
type: 'group',
args,
ignoreFilter: true,
})
}
groupCollapsed(...args: any[]) {
this.insert({
type: 'groupCollapsed',
args,
ignoreFilter: true,
})
}
groupEnd() {
this.insert('groupEnd')
}
evaluate(code: string) {
this.insert({
type: 'input',
args: [code],
ignoreFilter: true,
})
try {
this.output(this.evalJs(code))
} catch (e) {
this.insert({
type: 'error',
ignoreFilter: true,
args: [e],
})
}
}
html(...args: any) {
this.insert('html', args)
}
toggleGroup(log: Log) {
const { targetGroup } = log
;(targetGroup as IGroup).collapsed
? this.openGroup(log)
: this.collapseGroup(log)
}
private output(val: string) {
this.insert({
type: 'output',
args: [val],
ignoreFilter: true,
})
}
private render() {
const { logs } = this
this.$el.html('')
this.isAtBottom = true
this.updateBottomSpace(0)
this.updateTopSpace(0)
this.displayLogs = []
for (let i = 0, len = logs.length; i < len; i++) {
this.attachLog(logs[i])
}
}
private insert(type: string | InsertOptions, args?: any[]) {
const { showHeader, asyncRender } = this.options
let header
if (showHeader) {
header = {
time: getCurTime(),
from: getFrom(),
}
}
if (asyncRender) {
return this.insertAsync(type, args, header)
}
this.insertSync(type, args, header)
}
private insertAsync(
type: string | InsertOptions,
args?: any[],
header?: IHeader
) {
this.asyncList.push([type, args, header])
this.handleAsyncList()
}
private insertSync(
type: string | InsertOptions,
args?: any[],
header?: IHeader
) {
const { logs, groupStack } = this
const { maxNum, accessGetter, unenumerable, lazyEvaluation } = this.options
let options: InsertOptions
if (isStr(type)) {
options = {
type: type as string,
args: args as any[],
header,
}
} else {
options = type as InsertOptions
}
// Because asynchronous rendering, groupEnd must be put here.
if (options.type === 'groupEnd') {
const lastLog = this.lastLog as Log
lastLog.groupEnd()
this.groupStack.pop()
return
}
if (groupStack.size > 0) {
options.group = groupStack.peek()
}
extend(options, {
id: ++id,
accessGetter,
unenumerable,
lazyEvaluation,
})
if (options.type === 'group' || options.type === 'groupCollapsed') {
const group = {
id: uniqId('group'),
collapsed: false,
parent: groupStack.peek(),
indentLevel: groupStack.size + 1,
}
if (options.type === 'groupCollapsed') group.collapsed = true
options.targetGroup = group
groupStack.push(group)
}
let log = new Log(this, options as ILogOptions)
log.on('updateSize', () => {
this.isAtBottom = false
this.renderViewport()
})
const lastLog = this.lastLog
if (
lastLog &&
!contain(['html', 'group', 'groupCollapsed'], log.type) &&
lastLog.type === log.type &&
!log.src &&
!log.args &&
lastLog.text() === log.text()
) {
lastLog.addCount()
if (log.header) lastLog.updateTime(log.header.time)
log = lastLog
this.detachLog(lastLog)
} else {
logs.push(log)
this.lastLog = log
}
if (maxNum !== 0 && logs.length > maxNum) {
const firstLog = logs[0]
this.detachLog(firstLog)
logs.shift()
}
this.attachLog(log)
this.emit('insert', log)
}
private updateTopSpace(height: number) {
this.topSpaceHeight = height
this.el.style.top = height + 'px'
}
private updateBottomSpace(height: number) {
this.bottomSpaceHeight = height
}
private updateSpace(height: number) {
if (this.spaceHeight === height) return
this.spaceHeight = height
this.space.style.height = height + 'px'
}
private detachLog(log: Log) {
const { displayLogs } = this
const idx = displayLogs.indexOf(log)
if (idx > -1) {
displayLogs.splice(idx, 1)
this.renderViewport()
}
}
// Binary search
private attachLog(log: Log) {
if (!this.filterLog(log) || log.collapsed) return
const { displayLogs } = this
if (displayLogs.length === 0) {
displayLogs.push(log)
this.renderViewport()
return
}
const lastDisplayLog = last(displayLogs)
if (log.id > lastDisplayLog.id) {
displayLogs.push(log)
this.renderViewport()
return
}
let startIdx = 0
let endIdx = displayLogs.length - 1
let middleLog: any
let middleIdx = 0
while (startIdx <= endIdx) {
middleIdx = startIdx + Math.floor((endIdx - startIdx) / 2)
middleLog = displayLogs[middleIdx]
if (middleLog.id === log.id) {
return
}
if (middleLog.id < log.id) {
startIdx = middleIdx + 1
} else {
endIdx = middleIdx - 1
}
}
if (middleLog.id < log.id) {
displayLogs.splice(middleIdx + 1, 0, log)
} else {
displayLogs.splice(middleIdx, 0, log)
}
this.renderViewport()
}
private handleAsyncList(timeout = 20) {
const asyncList = this.asyncList
if (this.asyncTimer) return
this.asyncTimer = setTimeout(() => {
this.asyncTimer = null
let done = false
const len = asyncList.length
// insert faster if logs is huge, thus takes more time to render.
let timeout: number, num
if (len < 1000) {
num = 200
timeout = 400
} else if (len < 5000) {
num = 500
timeout = 800
} else if (len < 10000) {
num = 800
timeout = 1000
} else if (len < 25000) {
num = 1000
timeout = 1200
} else if (len < 50000) {
num = 1500
timeout = 1500
} else {
num = 2000
timeout = 2500
}
if (num > len) {
num = len
done = true
}
for (let i = 0; i < num; i++) {
const [type, args, header] = asyncList.shift() as AsyncItem
this.insertSync(type, args, header)
}
if (!done) {
raf(() => this.handleAsyncList(timeout))
}
}, timeout)
}
private injectGlobal() {
each(this.global, (val, name) => {
if (window[name]) return
;(window as any)[name] = val
})
}
private clearGlobal() {
each(this.global, (val, name) => {
if (window[name] && window[name] === val) {
delete window[name]
}
})
}
private evalJs(jsInput: string) {
let ret
this.injectGlobal()
try {
ret = eval.call(window, `(${jsInput})`)
} catch (e) {
ret = eval.call(window, jsInput)
}
this.setGlobal('$_', ret)
this.clearGlobal()
return ret
}
private filterLog(log: Log) {
const { filter } = this.options
if (filter === 'all') return true
if (log.ignoreFilter) {
return true
}
if (isFn(filter)) {
return (filter as types.AnyFn)(log)
}
if (isRegExp(filter)) {
return (filter as RegExp).test(lowerCase(log.text()))
}
return log.type === filter
}
private collapseGroup(log: Log) {
const { targetGroup } = log
;(targetGroup as IGroup).collapsed = true
log.updateIcon('caret-right')
this.updateGroup(log)
}
private openGroup(log: Log) {
const { targetGroup } = log
;(targetGroup as IGroup).collapsed = false
log.updateIcon('caret-down')
this.updateGroup(log)
}
private updateGroup(log: Log) {
const { targetGroup } = log
const { logs } = this
const len = logs.length
let i = logs.indexOf(log) + 1
while (i < len) {
const log = logs[i]
if (!log.checkGroup() && log.group === targetGroup) {
break
}
log.collapsed ? this.detachLog(log) : this.attachLog(log)
i++
}
}
private bindEvent() {
const { $el } = this
$el.on('click', c('.log-container'), function (this: any) {
this.log.click()
})
this.on('optionChange', (name, val) => {
const { logs } = this
switch (name) {
case 'maxNum':
if (val > 0 && logs.length > val) {
this.logs = logs.slice(logs.length - (val as number))
this.render()
}
break
case 'filter':
this.render()
break
}
})
this.$container.on('scroll', this.onScroll)
}
private onScroll = () => {
const { scrollHeight, offsetHeight, scrollTop } = this
.container as HTMLElement
// safari bounce effect
if (scrollTop <= 0) return
if (offsetHeight + scrollTop > scrollHeight) return
let isAtBottom = false
if (scrollHeight === offsetHeight) {
isAtBottom = true
} else if (scrollTop === scrollHeight - offsetHeight) {
isAtBottom = true
}
this.isAtBottom = isAtBottom
const lastScrollTop = this.lastScrollTop
const lastTimestamp = this.lastTimestamp
const timestamp = now()
const duration = timestamp - lastTimestamp
const distance = scrollTop - lastScrollTop
const speed = Math.abs(distance / duration)
let speedTolerance = speed * this.speedToleranceFactor
if (duration > 1000) {
speedTolerance = 1000
}
if (speedTolerance > this.maxSpeedTolerance) {
speedTolerance = this.maxSpeedTolerance
}
if (speedTolerance < this.minSpeedTolerance) {
speedTolerance = this.minSpeedTolerance
}
this.lastScrollTop = scrollTop
this.lastTimestamp = timestamp
let topTolerance = 0
let bottomTolerance = 0
if (lastScrollTop < scrollTop) {
topTolerance = this.minSpeedTolerance
bottomTolerance = speedTolerance
} else {
topTolerance = speedTolerance
bottomTolerance = this.minSpeedTolerance
}
if (
this.topSpaceHeight < scrollTop - topTolerance &&
this.topSpaceHeight + this.el.offsetHeight >
scrollTop + offsetHeight + bottomTolerance
) {
return
}
this.renderViewport({
topTolerance: topTolerance * 2,
bottomTolerance: bottomTolerance * 2,
})
}
private _renderViewport({ topTolerance = 500, bottomTolerance = 500 } = {}) {
const { el, container } = this
if (isHidden(container)) return
const { scrollTop, clientWidth, offsetHeight } = container as HTMLElement
const top = scrollTop - topTolerance
const bottom = scrollTop + offsetHeight + bottomTolerance
const { displayLogs } = this
let topSpaceHeight = 0
let bottomSpaceHeight = 0
let currentHeight = 0
const len = displayLogs.length
const { fakeEl } = this
const fakeFrag = document.createDocumentFragment()
const logs = []
for (let i = 0; i < len; i++) {
const log = displayLogs[i]
const { width, height } = log
if (height === 0 || width !== clientWidth) {
fakeFrag.appendChild(log.container)
logs.push(log)
}
}
if (logs.length > 0) {
fakeEl.appendChild(fakeFrag)
for (let i = 0, len = logs.length; i < len; i++) {
logs[i].updateSize()
}
fakeEl.innerHTML = ''
}
const frag = document.createDocumentFragment()
for (let i = 0; i < len; i++) {
const log = displayLogs[i]
const { container, height } = log
if (currentHeight > bottom) {
bottomSpaceHeight += height
} else if (currentHeight + height > top) {
frag.appendChild(container)
} else if (currentHeight < top) {
topSpaceHeight += height
}
currentHeight += height
}
this.updateSpace(currentHeight)
this.updateTopSpace(topSpaceHeight)
this.updateBottomSpace(bottomSpaceHeight)
while (el.firstChild) {
if (el.lastChild) {
el.removeChild(el.lastChild)
}
}
el.appendChild(frag)
const { scrollHeight } = container
if (this.isAtBottom && scrollTop <= scrollHeight - offsetHeight) {
container.scrollTop = 10000000
}
}
private initTpl() {
this.$container.html(
this.c(stripIndent`
<div class="logs-space">
<div class="fake-logs"></div>
<div class="logs"></div>
</div>
`)
)
}
}
module.exports = Console
module.exports.default = Console
const getCurTime = () => dateFormat('HH:MM:ss ')
function getFrom() {
const e = new Error()
let ret = ''
const lines = e.stack ? e.stack.split('\n') : ''
for (let i = 0, len = lines.length; i < len; i++) {
ret = lines[i]
if (ret.indexOf('winConsole') > -1 && i < len - 1) {
ret = lines[i + 1]
break
}
}
return ret
} | the_stack |
import { RawHttpHeadersInput } from "@azure/core-rest-pipeline";
import { RequestParameters } from "@azure-rest/core-client";
export interface ParamExistingKeyHeaders {
/** Send a post request with header value "User-Agent": "overwrite" */
"User-Agent": string;
}
export interface ParamExistingKeyHeaderParam {
headers: RawHttpHeadersInput & ParamExistingKeyHeaders;
}
export type ParamExistingKeyParameters = ParamExistingKeyHeaderParam &
RequestParameters;
export type ResponseExistingKeyParameters = RequestParameters;
export interface ParamProtectedKeyHeaders {
/** Send a post request with header value "Content-Type": "text/html" */
"Content-Type": string;
}
export interface ParamProtectedKeyHeaderParam {
headers: RawHttpHeadersInput & ParamProtectedKeyHeaders;
}
export type ParamProtectedKeyParameters = ParamProtectedKeyHeaderParam &
RequestParameters;
export type ResponseProtectedKeyParameters = RequestParameters;
export interface ParamIntegerHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
/** Send a post request with header values 1 or -2 */
value: number;
}
export interface ParamIntegerHeaderParam {
headers: RawHttpHeadersInput & ParamIntegerHeaders;
}
export type ParamIntegerParameters = ParamIntegerHeaderParam &
RequestParameters;
export interface ResponseIntegerHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
}
export interface ResponseIntegerHeaderParam {
headers: RawHttpHeadersInput & ResponseIntegerHeaders;
}
export type ResponseIntegerParameters = ResponseIntegerHeaderParam &
RequestParameters;
export interface ParamLongHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
/** Send a post request with header values 105 or -2 */
value: number;
}
export interface ParamLongHeaderParam {
headers: RawHttpHeadersInput & ParamLongHeaders;
}
export type ParamLongParameters = ParamLongHeaderParam & RequestParameters;
export interface ResponseLongHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
}
export interface ResponseLongHeaderParam {
headers: RawHttpHeadersInput & ResponseLongHeaders;
}
export type ResponseLongParameters = ResponseLongHeaderParam &
RequestParameters;
export interface ParamFloatHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
/** Send a post request with header values 0.07 or -3.0 */
value: number;
}
export interface ParamFloatHeaderParam {
headers: RawHttpHeadersInput & ParamFloatHeaders;
}
export type ParamFloatParameters = ParamFloatHeaderParam & RequestParameters;
export interface ResponseFloatHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
}
export interface ResponseFloatHeaderParam {
headers: RawHttpHeadersInput & ResponseFloatHeaders;
}
export type ResponseFloatParameters = ResponseFloatHeaderParam &
RequestParameters;
export interface ParamDoubleHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
/** Send a post request with header values 7e120 or -3.0 */
value: number;
}
export interface ParamDoubleHeaderParam {
headers: RawHttpHeadersInput & ParamDoubleHeaders;
}
export type ParamDoubleParameters = ParamDoubleHeaderParam & RequestParameters;
export interface ResponseDoubleHeaders {
/** Send a post request with header values "scenario": "positive" or "negative" */
scenario: string;
}
export interface ResponseDoubleHeaderParam {
headers: RawHttpHeadersInput & ResponseDoubleHeaders;
}
export type ResponseDoubleParameters = ResponseDoubleHeaderParam &
RequestParameters;
export interface ParamBoolHeaders {
/** Send a post request with header values "scenario": "true" or "false" */
scenario: string;
/** Send a post request with header values true or false */
value: boolean;
}
export interface ParamBoolHeaderParam {
headers: RawHttpHeadersInput & ParamBoolHeaders;
}
export type ParamBoolParameters = ParamBoolHeaderParam & RequestParameters;
export interface ResponseBoolHeaders {
/** Send a post request with header values "scenario": "true" or "false" */
scenario: string;
}
export interface ResponseBoolHeaderParam {
headers: RawHttpHeadersInput & ResponseBoolHeaders;
}
export type ResponseBoolParameters = ResponseBoolHeaderParam &
RequestParameters;
export interface ParamStringHeaders {
/** Send a post request with header values "scenario": "valid" or "null" or "empty" */
scenario: string;
/** Send a post request with header values "The quick brown fox jumps over the lazy dog" or null or "" */
value?: string;
}
export interface ParamStringHeaderParam {
headers: RawHttpHeadersInput & ParamStringHeaders;
}
export type ParamStringParameters = ParamStringHeaderParam & RequestParameters;
export interface ResponseStringHeaders {
/** Send a post request with header values "scenario": "valid" or "null" or "empty" */
scenario: string;
}
export interface ResponseStringHeaderParam {
headers: RawHttpHeadersInput & ResponseStringHeaders;
}
export type ResponseStringParameters = ResponseStringHeaderParam &
RequestParameters;
export interface ParamDateHeaders {
/** Send a post request with header values "scenario": "valid" or "min" */
scenario: string;
/** Send a post request with header values "2010-01-01" or "0001-01-01" */
value: Date | string;
}
export interface ParamDateHeaderParam {
headers: RawHttpHeadersInput & ParamDateHeaders;
}
export type ParamDateParameters = ParamDateHeaderParam & RequestParameters;
export interface ResponseDateHeaders {
/** Send a post request with header values "scenario": "valid" or "min" */
scenario: string;
}
export interface ResponseDateHeaderParam {
headers: RawHttpHeadersInput & ResponseDateHeaders;
}
export type ResponseDateParameters = ResponseDateHeaderParam &
RequestParameters;
export interface ParamDatetimeHeaders {
/** Send a post request with header values "scenario": "valid" or "min" */
scenario: string;
/** Send a post request with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z" */
value: Date | string;
}
export interface ParamDatetimeHeaderParam {
headers: RawHttpHeadersInput & ParamDatetimeHeaders;
}
export type ParamDatetimeParameters = ParamDatetimeHeaderParam &
RequestParameters;
export interface ResponseDatetimeHeaders {
/** Send a post request with header values "scenario": "valid" or "min" */
scenario: string;
}
export interface ResponseDatetimeHeaderParam {
headers: RawHttpHeadersInput & ResponseDatetimeHeaders;
}
export type ResponseDatetimeParameters = ResponseDatetimeHeaderParam &
RequestParameters;
export interface ParamDatetimeRfc1123Headers {
/** Send a post request with header values "scenario": "valid" or "min" */
scenario: string;
/** Send a post request with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, 01 Jan 0001 00:00:00 GMT" */
value?: Date | string;
}
export interface ParamDatetimeRfc1123HeaderParam {
headers: RawHttpHeadersInput & ParamDatetimeRfc1123Headers;
}
export type ParamDatetimeRfc1123Parameters = ParamDatetimeRfc1123HeaderParam &
RequestParameters;
export interface ResponseDatetimeRfc1123Headers {
/** Send a post request with header values "scenario": "valid" or "min" */
scenario: string;
}
export interface ResponseDatetimeRfc1123HeaderParam {
headers: RawHttpHeadersInput & ResponseDatetimeRfc1123Headers;
}
export type ResponseDatetimeRfc1123Parameters = ResponseDatetimeRfc1123HeaderParam &
RequestParameters;
export interface ParamDurationHeaders {
/** Send a post request with header values "scenario": "valid" */
scenario: string;
/** Send a post request with header values "P123DT22H14M12.011S" */
value: string;
}
export interface ParamDurationHeaderParam {
headers: RawHttpHeadersInput & ParamDurationHeaders;
}
export type ParamDurationParameters = ParamDurationHeaderParam &
RequestParameters;
export interface ResponseDurationHeaders {
/** Send a post request with header values "scenario": "valid" */
scenario: string;
}
export interface ResponseDurationHeaderParam {
headers: RawHttpHeadersInput & ResponseDurationHeaders;
}
export type ResponseDurationParameters = ResponseDurationHeaderParam &
RequestParameters;
export interface ParamByteHeaders {
/** Send a post request with header values "scenario": "valid" */
scenario: string;
/** Send a post request with header values "啊齄丂狛狜隣郎隣兀﨩" */
value: string;
}
export interface ParamByteHeaderParam {
headers: RawHttpHeadersInput & ParamByteHeaders;
}
export type ParamByteParameters = ParamByteHeaderParam & RequestParameters;
export interface ResponseByteHeaders {
/** Send a post request with header values "scenario": "valid" */
scenario: string;
}
export interface ResponseByteHeaderParam {
headers: RawHttpHeadersInput & ResponseByteHeaders;
}
export type ResponseByteParameters = ResponseByteHeaderParam &
RequestParameters;
export interface ParamEnumHeaders {
/** Send a post request with header values "scenario": "valid" or "null" or "empty" */
scenario: string;
/** Send a post request with header values 'GREY' */
value?: "White" | "black" | "GREY";
}
export interface ParamEnumHeaderParam {
headers: RawHttpHeadersInput & ParamEnumHeaders;
}
export type ParamEnumParameters = ParamEnumHeaderParam & RequestParameters;
export interface ResponseEnumHeaders {
/** Send a post request with header values "scenario": "valid" or "null" or "empty" */
scenario: string;
}
export interface ResponseEnumHeaderParam {
headers: RawHttpHeadersInput & ResponseEnumHeaders;
}
export type ResponseEnumParameters = ResponseEnumHeaderParam &
RequestParameters;
export type CustomRequestIdParameters = RequestParameters; | the_stack |
import {QueryAble, QueryOptions} from "./queryAble";
import {PgDb, FieldType} from "./pgDb";
import {PgDbLogger} from "./pgDbLogger"
import generateWhere from "./queryWhere";
import {PgSchema} from "./pgSchema";
import {pgUtils} from "./pgUtils";
import * as _ from 'lodash';
import * as stream from "stream";
const util = require('util');
export interface InsertOption {
logger?: PgDbLogger;
}
export interface Return {
return?: string[] | '*';
}
export interface UpdateDeleteOption {
skipUndefined?: boolean;
logger?: PgDbLogger;
}
export interface UpsertOption {
constraint?: string,
columns?: string[],
logger?: PgDbLogger;
}
export interface CountOption {
skipUndefined?: boolean;
logger?: PgDbLogger;
}
export interface Stream {
stream: true;
}
export interface TruncateOptions {
restartIdentity?: boolean,
cascade?: boolean,
logger?: PgDbLogger;
}
export class PgTable<T> extends QueryAble {
qualifiedName: string;
pkey: string;
db: PgDb;
fieldTypes: { [index: string]: FieldType }; //written directly
constructor(public schema: PgSchema, protected desc: { name: string, pkey?:string, schema: string }, fieldTypes = {}) {
super();
this.db = schema.db;
this.qualifiedName = util.format('"%s"."%s"', desc.schema, desc.name);
this.pkey = desc.pkey || desc.name + "_pkey"; //poor man's pkey (could be queried by why?)
this.fieldTypes = fieldTypes;
}
toString() {
return this.qualifiedName;
}
/**
* If you dont want to use the result set the options.return to false
* by default it is true. Also can set it to the fields that need to be returned,
* e.g.:
*
* let res = await table.insert([{username:'anonymous'},{username:'anonymous2'}], {return:['id']})
* res; // [{id:1},{id:2}]
*
* let res = await table.insert({username:'anonymous'}, {return:false})
* res; // void
*
* let res = await table.insert({username:'anonymous'})
* res; // {id:1, name:'anonymous', created:'...'}
*
*/
async insert(records: T[], options?: InsertOption): Promise<number>
async insert(records: T, options?: InsertOption): Promise<number>
async insert(records: any, options?: any): Promise<any> {
options = options || {};
if (!records) {
throw new Error("insert should be called with data");
} else if (!Array.isArray(records)) {
records = [records];
} else if (records.length === 0) {
return 0; // just return empty arrays so bulk inserting variable-length lists is more friendly
}
let {sql, parameters} = this.getInsertQuery(records);
sql = "WITH __RESULT as ( " + sql + " RETURNING 1) SELECT SUM(1) FROM __RESULT";
let result = await this.query(sql, parameters, {logger: options.logger});
return result[0].sum;
}
async insertAndGet(records: T[], options?: InsertOption & Return): Promise<T[]>
async insertAndGet(records: T, options?: InsertOption & Return): Promise<T>
async insertAndGet(records: any, options?: InsertOption & Return): Promise<any> {
let returnSingle = false;
options = options || {};
if (!records) {
throw new Error("insert should be called with data");
} else if (!Array.isArray(records)) {
returnSingle = true;
records = [records];
} else if (records.length === 0) {
return []; // just return empty arrays so bulk inserting variable-length lists is more friendly
}
let {sql, parameters} = this.getInsertQuery(records);
sql += " RETURNING " + (options && options.return && Array.isArray(options.return) ? options.return.map(pgUtils.quoteField).join(',') : '*');
let result = await this.query(sql, parameters, {logger: options.logger});
if (options.return && options.return.length == 0) {
return new Array(returnSingle ? 1 : records.length).fill({});
}
if (returnSingle) {
return result[0];
} else {
return result;
}
};
async updateOne(conditions: { [k: string]: any }, fields: { [k: string]: any }, options?: UpdateDeleteOption): Promise<number> {
let affected = await this.update(conditions, fields, options);
if (affected > 1) {
throw new Error('More then one record has been updated!');
}
return affected;
}
async updateAndGetOne(conditions: { [k: string]: any }, fields: { [k: string]: any }, options?: UpdateDeleteOption & Return): Promise<T> {
let result = await this.updateAndGet(conditions, fields, options);
if (result.length > 1) {
throw new Error('More then one record has been updated!');
}
return result[0];
}
async update(conditions: { [k: string]: any }, fields: { [k: string]: any }, options?: UpdateDeleteOption): Promise<number> {
let {sql, parameters} = this.getUpdateQuery(conditions, fields, options);
sql = "WITH __RESULT as ( " + sql + " RETURNING 1) SELECT SUM(1) FROM __RESULT";
let res = await this.query(sql, parameters, options);
return res[0].sum;
};
async updateAndGet(conditions: { [k: string]: any }, fields: { [k: string]: any }, options?: UpdateDeleteOption & Return): Promise<T[]> {
let {sql, parameters} = this.getUpdateQuery(conditions, fields, options);
sql += " RETURNING " + (options && options.return && Array.isArray(options.return) ? options.return.map(pgUtils.quoteField).join(',') : '*');
return this.query(sql, parameters, options);
};
/**
* columnsOrConstraintName is by default the primary key
*/
async upsert(record: T, options?: UpsertOption): Promise<number> {
options = options || {};
if (!record) {
throw new Error("insert should be called with data");
}
let {sql, parameters} = this.getUpsertQuery(record, options);
sql = "WITH __RESULT as ( " + sql + " RETURNING 1) SELECT SUM(1) FROM __RESULT";
let result = await this.query(sql, parameters, {logger: options.logger});
return result[0].sum;
};
/**
* columnsOrConstraintName is by default the primary key
*/
async upsertAndGet(record: T, options?: UpsertOption & Return): Promise<T> {
options = options || {};
if (!record) {
throw new Error("insert should be called with data");
}
let {sql, parameters} = this.getUpsertQuery(record, options);
sql += " RETURNING " + (options && options.return && Array.isArray(options.return) ? options.return.map(pgUtils.quoteField).join(',') : '*');
let result = await this.query(sql, parameters, {logger: options.logger});
if (options.return && options.return.length == 0) {
return <T>{};
}
return result[0];
};
async delete(conditions: { [k: string]: any }, options?: UpdateDeleteOption): Promise<number> {
let {sql, parameters} = this.getDeleteQuery(conditions, options);
sql = "WITH __RESULT as ( " + sql + " RETURNING 1) SELECT SUM(1) FROM __RESULT";
let res = await this.query(sql, parameters, options);
return res[0].sum;
}
async deleteOne(conditions: { [k: string]: any }, options?: UpdateDeleteOption): Promise<number> {
let affected = await this.delete(conditions, options);
if (affected > 1) {
throw new Error('More then one record has been deleted!');
}
return affected;
}
async deleteAndGet(conditions: { [k: string]: any }, options?: UpdateDeleteOption & Return): Promise<any[]> {
options = options || {};
let {sql, parameters} = this.getDeleteQuery(conditions, options);
sql += " RETURNING " + (options && options.return && Array.isArray(options.return) ? options.return.map(pgUtils.quoteField).join(',') : '*');
return this.query(sql, parameters);
}
async deleteAndGetOne(conditions: { [k: string]: any }, options?: UpdateDeleteOption & Return): Promise<any> {
let result = await this.deleteAndGet(conditions, options);
if (result.length > 1) {
throw new Error('More then one record has been deleted!');
}
return result[0];
}
// async deleteAll(options?:UpdateDeleteOption):Promise<number> {
// let sql = util.format("DELETE FROM %s ", this.qualifiedName);
// sql = "WITH __RESULT as ( " + sql + " RETURNING 1) SELECT SUM(1) FROM __RESULT";
// let res = await this.query(sql, {logger:options.logger});
// return res[0].sum;
// }
async truncate(options?: TruncateOptions): Promise<void> {
let sql = `TRUNCATE ${this.qualifiedName}`;
if (options && options.restartIdentity) {
sql += ' RESTART IDENTITY';
}
if (options && options.cascade) {
sql += ' CASCADE';
}
await this.query(sql, null, options);
}
async find(conditions: { [k: string]: any }, options?: QueryOptions): Promise<T[]>
async find(conditions: { [k: string]: any }, options?: QueryOptions & Stream): Promise<stream.Readable>
async find(conditions: { [k: string]: any }, options?: any): Promise<any> {
options = options || {};
options.skipUndefined = options.skipUndefined === true || (options.skipUndefined === undefined && ['all', 'select'].indexOf(this.db.config.skipUndefined) > -1);
let where = _.isEmpty(conditions) ? {
where: " ",
params: null
} : generateWhere(conditions, this.fieldTypes, this.qualifiedName, 0, options.skipUndefined);
let sql = `SELECT ${pgUtils.processQueryFields(options)} FROM ${this.qualifiedName} ${where.where} ${pgUtils.processQueryOptions(options)}`;
return options.stream ? this.queryAsStream(sql, where.params, options) : this.query(sql, where.params, options);
}
async findWhere(where: string, params: any[] | {}, options?: QueryOptions): Promise<T[]>
async findWhere(where: string, params: any[] | {}, options?: QueryOptions & Stream): Promise<stream.Readable>
async findWhere(where: string, params: any, options?: any): Promise<any> {
options = options || {};
let sql = `SELECT ${pgUtils.processQueryFields(options)} FROM ${this.qualifiedName} WHERE ${where} ${pgUtils.processQueryOptions(options)}`;
return options.stream ? this.queryAsStream(sql, params, options) : this.query(sql, params, options);
}
public async findAll(options?: QueryOptions): Promise<T[]>
public async findAll(options?: QueryOptions & Stream): Promise<stream.Readable>
public async findAll(options?: any): Promise<any> {
options = options || {};
let sql = `SELECT ${pgUtils.processQueryFields(options)} FROM ${this.qualifiedName} ${pgUtils.processQueryOptions(options)}`;
return options.stream ? this.queryAsStream(sql, null, options) : this.query(sql, null, options);
}
async findOne(conditions, options?: QueryOptions): Promise<T> {
let res = await this.find(conditions, options);
if (res.length > 1) {
let logger = (options && options.logger || this.getLogger(false));
let error = new Error('More then one rows exists');
pgUtils.logError(logger, { error, sql:this.qualifiedName, params: conditions, connection: this.db.connection });
throw error;
}
return res[0];
}
async findFirst(conditions, options?: QueryOptions): Promise<T> {
options = options || {};
options.limit = 1;
let res = await this.find(conditions, options);
return res[0];
}
async count(conditions?: {}, options?: CountOption): Promise<number> {
options = options || {};
options.skipUndefined = options.skipUndefined === true || (options.skipUndefined === undefined && ['all', 'select'].indexOf(this.db.config.skipUndefined) > -1);
let where = _.isEmpty(conditions) ? {
where: " ",
params: null
} : generateWhere(conditions, this.fieldTypes, this.qualifiedName, 0, options.skipUndefined);
let sql = `SELECT COUNT(*) c FROM ${this.qualifiedName} ${where.where}`;
return (await this.queryOneField(sql, where.params));
}
async findOneFieldOnly(conditions, field: string, options?: QueryOptions): Promise<any> {
options = options || {};
options.fields = [field];
let res = await this.findOne(conditions, options);
return res ? res[field] : null;
}
private getInsertQuery(records: T[]) {
let columnsMap = {};
records.forEach(rec => {
for (let field in <Object>rec) {
columnsMap[field] = true;
}
});
let columns = Object.keys(columnsMap);
let sql = util.format("INSERT INTO %s (%s) VALUES\n", this.qualifiedName, columns.map(pgUtils.quoteField).join(", "));
let parameters = [];
let placeholders = [];
for (let i = 0, seed = 0; i < records.length; i++) {
placeholders.push('(' + columns.map(c => "$" + (++seed)).join(', ') + ')');
parameters.push.apply(parameters, columns.map(c => pgUtils.transformInsertUpdateParams(records[i][c], this.fieldTypes[c])));
}
sql += placeholders.join(",\n");
return {sql, parameters};
}
protected getUpdateSetSnipplet(fields: { [k: string]: any }, parameters?:any[] ): { snipplet: string, parameters: any[] } {
let params = parameters || [];
let f = [];
let seed = params.length;
_.each(fields, (value, fieldName) => {
if (value === undefined) return;
f.push(util.format('%s = $%s', pgUtils.quoteField(fieldName), (++seed)));
params.push(pgUtils.transformInsertUpdateParams(value, this.fieldTypes[fieldName]));
});
return {snipplet: f.join(', '), parameters: params};
}
protected getUpdateQuery(conditions: { [k: string]: any }, fields: { [k: string]: any }, options?: UpdateDeleteOption): { sql: string, parameters: any[] } {
options = options || {};
options.skipUndefined = options.skipUndefined === true || (options.skipUndefined === undefined && this.db.config.skipUndefined === 'all');
let hasConditions = true;
if (_.isEmpty(fields)) {
throw new Error('Missing fields for update');
}
let {snipplet, parameters} = this.getUpdateSetSnipplet(fields);
let sql = util.format("UPDATE %s SET %s", this.qualifiedName, snipplet);
if (!hasConditions || !_.isEmpty(conditions)) {
let parsedWhere = generateWhere(conditions, this.fieldTypes, this.qualifiedName, parameters.length, options.skipUndefined);
sql += parsedWhere.where;
parameters = parameters.concat(parsedWhere.params);
}
return {sql, parameters};
}
protected getUpsertQuery(record: T, options?: UpsertOption): { sql: string, parameters: any[] } {
options = options || {};
if (_.isEmpty(record)) {
throw new Error('Missing fields for upsert');
}
let insert = this.getInsertQuery([record]);
let {snipplet, parameters} = this.getUpdateSetSnipplet(record, insert.parameters);
let sql = insert.sql;
if (options.columns) {
sql += " ON CONFLICT (" + options.columns.map(c=>pgUtils.quoteField(c)).join(', ') + ") DO UPDATE SET " + snipplet;
} else {
let constraint = options.constraint || this.pkey;
sql += " ON CONFLICT ON CONSTRAINT " + util.format('"%s"', constraint) + " DO UPDATE SET " + snipplet;
}
return {sql, parameters};
}
protected getDeleteQuery(conditions: { [k: string]: any }, options?: UpdateDeleteOption): { sql: string, parameters: any[] } {
options = options || {};
options.skipUndefined = options.skipUndefined === true || (options.skipUndefined === undefined && this.db.config.skipUndefined === 'all');
let sql = util.format("DELETE FROM %s ", this.qualifiedName);
let parsedWhere;
if (!_.isEmpty(conditions)) {
parsedWhere = generateWhere(conditions, this.fieldTypes, this.qualifiedName, 0, options.skipUndefined);
sql += parsedWhere.where;
}
return {sql, parameters: parsedWhere && parsedWhere.params || []}
}
} | the_stack |
* This file was automatically generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
* In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
**/
gapi.load('client', () => {
/** now we can use gapi.client */
gapi.client.load('storage', 'v1', () => {
/** now we can use gapi.client.storage */
/** don't forget to authenticate your client before sending any request to resources: */
/** declare client_id registered in Google Developers Console */
const client_id = '<<PUT YOUR CLIENT ID HERE>>';
const scope = [
/** View and manage your data across Google Cloud Platform services */
'https://www.googleapis.com/auth/cloud-platform',
/** View your data across Google Cloud Platform services */
'https://www.googleapis.com/auth/cloud-platform.read-only',
/** Manage your data and permissions in Google Cloud Storage */
'https://www.googleapis.com/auth/devstorage.full_control',
/** View your data in Google Cloud Storage */
'https://www.googleapis.com/auth/devstorage.read_only',
/** Manage your data in Google Cloud Storage */
'https://www.googleapis.com/auth/devstorage.read_write',
];
const immediate = true;
gapi.auth.authorize({ client_id, scope, immediate }, authResult => {
if (authResult && !authResult.error) {
/** handle succesfull authorization */
run();
} else {
/** handle authorization error */
}
});
run();
});
async function run() {
/** Permanently deletes the ACL entry for the specified entity on the specified bucket. */
await gapi.client.bucketAccessControls.delete({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Returns the ACL entry for the specified entity on the specified bucket. */
await gapi.client.bucketAccessControls.get({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Creates a new ACL entry on the specified bucket. */
await gapi.client.bucketAccessControls.insert({
bucket: "bucket",
userProject: "userProject",
});
/** Retrieves ACL entries on the specified bucket. */
await gapi.client.bucketAccessControls.list({
bucket: "bucket",
userProject: "userProject",
});
/** Updates an ACL entry on the specified bucket. This method supports patch semantics. */
await gapi.client.bucketAccessControls.patch({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Updates an ACL entry on the specified bucket. */
await gapi.client.bucketAccessControls.update({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Permanently deletes an empty bucket. */
await gapi.client.buckets.delete({
bucket: "bucket",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
userProject: "userProject",
});
/** Returns metadata for the specified bucket. */
await gapi.client.buckets.get({
bucket: "bucket",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
projection: "projection",
userProject: "userProject",
});
/** Returns an IAM policy for the specified bucket. */
await gapi.client.buckets.getIamPolicy({
bucket: "bucket",
userProject: "userProject",
});
/** Creates a new bucket. */
await gapi.client.buckets.insert({
predefinedAcl: "predefinedAcl",
predefinedDefaultObjectAcl: "predefinedDefaultObjectAcl",
project: "project",
projection: "projection",
userProject: "userProject",
});
/** Retrieves a list of buckets for a given project. */
await gapi.client.buckets.list({
maxResults: 1,
pageToken: "pageToken",
prefix: "prefix",
project: "project",
projection: "projection",
userProject: "userProject",
});
/**
* Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate. This method
* supports patch semantics.
*/
await gapi.client.buckets.patch({
bucket: "bucket",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
predefinedAcl: "predefinedAcl",
predefinedDefaultObjectAcl: "predefinedDefaultObjectAcl",
projection: "projection",
userProject: "userProject",
});
/** Updates an IAM policy for the specified bucket. */
await gapi.client.buckets.setIamPolicy({
bucket: "bucket",
userProject: "userProject",
});
/** Tests a set of permissions on the given bucket to see which, if any, are held by the caller. */
await gapi.client.buckets.testIamPermissions({
bucket: "bucket",
permissions: "permissions",
userProject: "userProject",
});
/** Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate. */
await gapi.client.buckets.update({
bucket: "bucket",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
predefinedAcl: "predefinedAcl",
predefinedDefaultObjectAcl: "predefinedDefaultObjectAcl",
projection: "projection",
userProject: "userProject",
});
/** Stop watching resources through this channel */
await gapi.client.channels.stop({
});
/** Permanently deletes the default object ACL entry for the specified entity on the specified bucket. */
await gapi.client.defaultObjectAccessControls.delete({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Returns the default object ACL entry for the specified entity on the specified bucket. */
await gapi.client.defaultObjectAccessControls.get({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Creates a new default object ACL entry on the specified bucket. */
await gapi.client.defaultObjectAccessControls.insert({
bucket: "bucket",
userProject: "userProject",
});
/** Retrieves default object ACL entries on the specified bucket. */
await gapi.client.defaultObjectAccessControls.list({
bucket: "bucket",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
userProject: "userProject",
});
/** Updates a default object ACL entry on the specified bucket. This method supports patch semantics. */
await gapi.client.defaultObjectAccessControls.patch({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Updates a default object ACL entry on the specified bucket. */
await gapi.client.defaultObjectAccessControls.update({
bucket: "bucket",
entity: "entity",
userProject: "userProject",
});
/** Permanently deletes a notification subscription. */
await gapi.client.notifications.delete({
bucket: "bucket",
notification: "notification",
userProject: "userProject",
});
/** View a notification configuration. */
await gapi.client.notifications.get({
bucket: "bucket",
notification: "notification",
userProject: "userProject",
});
/** Creates a notification subscription for a given bucket. */
await gapi.client.notifications.insert({
bucket: "bucket",
userProject: "userProject",
});
/** Retrieves a list of notification subscriptions for a given bucket. */
await gapi.client.notifications.list({
bucket: "bucket",
userProject: "userProject",
});
/** Permanently deletes the ACL entry for the specified entity on the specified object. */
await gapi.client.objectAccessControls.delete({
bucket: "bucket",
entity: "entity",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Returns the ACL entry for the specified entity on the specified object. */
await gapi.client.objectAccessControls.get({
bucket: "bucket",
entity: "entity",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Creates a new ACL entry on the specified object. */
await gapi.client.objectAccessControls.insert({
bucket: "bucket",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Retrieves ACL entries on the specified object. */
await gapi.client.objectAccessControls.list({
bucket: "bucket",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Updates an ACL entry on the specified object. This method supports patch semantics. */
await gapi.client.objectAccessControls.patch({
bucket: "bucket",
entity: "entity",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Updates an ACL entry on the specified object. */
await gapi.client.objectAccessControls.update({
bucket: "bucket",
entity: "entity",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Concatenates a list of existing objects into a new object in the same bucket. */
await gapi.client.objects.compose({
destinationBucket: "destinationBucket",
destinationObject: "destinationObject",
destinationPredefinedAcl: "destinationPredefinedAcl",
ifGenerationMatch: "ifGenerationMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
kmsKeyName: "kmsKeyName",
userProject: "userProject",
});
/** Copies a source object to a destination object. Optionally overrides metadata. */
await gapi.client.objects.copy({
destinationBucket: "destinationBucket",
destinationObject: "destinationObject",
destinationPredefinedAcl: "destinationPredefinedAcl",
ifGenerationMatch: "ifGenerationMatch",
ifGenerationNotMatch: "ifGenerationNotMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
ifSourceGenerationMatch: "ifSourceGenerationMatch",
ifSourceGenerationNotMatch: "ifSourceGenerationNotMatch",
ifSourceMetagenerationMatch: "ifSourceMetagenerationMatch",
ifSourceMetagenerationNotMatch: "ifSourceMetagenerationNotMatch",
projection: "projection",
sourceBucket: "sourceBucket",
sourceGeneration: "sourceGeneration",
sourceObject: "sourceObject",
userProject: "userProject",
});
/** Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used. */
await gapi.client.objects.delete({
bucket: "bucket",
generation: "generation",
ifGenerationMatch: "ifGenerationMatch",
ifGenerationNotMatch: "ifGenerationNotMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
object: "object",
userProject: "userProject",
});
/** Retrieves an object or its metadata. */
await gapi.client.objects.get({
bucket: "bucket",
generation: "generation",
ifGenerationMatch: "ifGenerationMatch",
ifGenerationNotMatch: "ifGenerationNotMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
object: "object",
projection: "projection",
userProject: "userProject",
});
/** Returns an IAM policy for the specified object. */
await gapi.client.objects.getIamPolicy({
bucket: "bucket",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Stores a new object and metadata. */
await gapi.client.objects.insert({
bucket: "bucket",
contentEncoding: "contentEncoding",
ifGenerationMatch: "ifGenerationMatch",
ifGenerationNotMatch: "ifGenerationNotMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
kmsKeyName: "kmsKeyName",
name: "name",
predefinedAcl: "predefinedAcl",
projection: "projection",
userProject: "userProject",
});
/** Retrieves a list of objects matching the criteria. */
await gapi.client.objects.list({
bucket: "bucket",
delimiter: "delimiter",
maxResults: 3,
pageToken: "pageToken",
prefix: "prefix",
projection: "projection",
userProject: "userProject",
versions: true,
});
/** Updates an object's metadata. This method supports patch semantics. */
await gapi.client.objects.patch({
bucket: "bucket",
generation: "generation",
ifGenerationMatch: "ifGenerationMatch",
ifGenerationNotMatch: "ifGenerationNotMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
object: "object",
predefinedAcl: "predefinedAcl",
projection: "projection",
userProject: "userProject",
});
/** Rewrites a source object to a destination object. Optionally overrides metadata. */
await gapi.client.objects.rewrite({
destinationBucket: "destinationBucket",
destinationKmsKeyName: "destinationKmsKeyName",
destinationObject: "destinationObject",
destinationPredefinedAcl: "destinationPredefinedAcl",
ifGenerationMatch: "ifGenerationMatch",
ifGenerationNotMatch: "ifGenerationNotMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
ifSourceGenerationMatch: "ifSourceGenerationMatch",
ifSourceGenerationNotMatch: "ifSourceGenerationNotMatch",
ifSourceMetagenerationMatch: "ifSourceMetagenerationMatch",
ifSourceMetagenerationNotMatch: "ifSourceMetagenerationNotMatch",
maxBytesRewrittenPerCall: "maxBytesRewrittenPerCall",
projection: "projection",
rewriteToken: "rewriteToken",
sourceBucket: "sourceBucket",
sourceGeneration: "sourceGeneration",
sourceObject: "sourceObject",
userProject: "userProject",
});
/** Updates an IAM policy for the specified object. */
await gapi.client.objects.setIamPolicy({
bucket: "bucket",
generation: "generation",
object: "object",
userProject: "userProject",
});
/** Tests a set of permissions on the given object to see which, if any, are held by the caller. */
await gapi.client.objects.testIamPermissions({
bucket: "bucket",
generation: "generation",
object: "object",
permissions: "permissions",
userProject: "userProject",
});
/** Updates an object's metadata. */
await gapi.client.objects.update({
bucket: "bucket",
generation: "generation",
ifGenerationMatch: "ifGenerationMatch",
ifGenerationNotMatch: "ifGenerationNotMatch",
ifMetagenerationMatch: "ifMetagenerationMatch",
ifMetagenerationNotMatch: "ifMetagenerationNotMatch",
object: "object",
predefinedAcl: "predefinedAcl",
projection: "projection",
userProject: "userProject",
});
/** Watch for changes on all objects in a bucket. */
await gapi.client.objects.watchAll({
bucket: "bucket",
delimiter: "delimiter",
maxResults: 3,
pageToken: "pageToken",
prefix: "prefix",
projection: "projection",
userProject: "userProject",
versions: true,
});
}
}); | the_stack |
import getAjvAsyncInstances from "./ajv_async_instances"
import _Ajv from "./ajv"
import chai from "./chai"
const should = chai.should()
describe("async schemas, formats and keywords", function () {
this.timeout(30000)
let ajv, instances
beforeEach(() => {
instances = getAjvAsyncInstances()
ajv = instances[0]
})
describe("async schemas without async elements", () => {
it("should return result as promise", () => {
const schema = {
$async: true,
type: "string",
maxLength: 3,
}
return repeat(() => {
return Promise.all(instances.map(test))
})
function test(_ajv) {
const validate = _ajv.compile(schema)
return Promise.all([
shouldBeValid(validate("abc"), "abc"),
shouldBeInvalid(validate("abcd")),
shouldBeInvalid(validate(1)),
])
}
})
it("should fail compilation if async schema is inside sync schema", () => {
const schema: any = {
type: "object",
properties: {
foo: {
$async: true,
type: "string",
maxLength: 3,
},
},
}
should.throw(() => {
ajv.compile(schema)
}, "async schema in sync schema")
ajv.compile({...schema, $async: true})
})
})
describe("async formats", () => {
beforeEach(addFormatEnglishWord)
it("should fail compilation if async format is inside sync schema", () => {
instances.forEach((_ajv) => {
let schema: any = {
type: "string",
format: "english_word",
}
should.throw(() => {
_ajv.compile(schema)
}, "async format in sync schema")
schema = {...schema, $async: true}
_ajv.compile(schema)
})
})
})
describe("async user-defined keywords", () => {
beforeEach(() => {
instances.forEach((_ajv) => {
_ajv.addKeyword({
keyword: "idExists",
async: true,
type: "number",
validate: checkIdExists,
errors: false,
})
_ajv.addKeyword({
keyword: "idExistsWithError",
async: true,
type: "number",
validate: checkIdExistsWithError,
errors: true,
})
})
})
it("should fail compilation if async keyword is inside sync schema", () => {
instances.forEach((_ajv) => {
let schema: any = {
type: "object",
properties: {
userId: {
type: "integer",
idExists: {table: "users"},
},
},
}
should.throw(() => {
_ajv.compile(schema)
}, "async keyword in sync schema")
schema = {...schema, $async: true}
_ajv.compile(schema)
})
})
it("should return user-defined error", () => {
return Promise.all(
instances.map((_ajv) => {
const schema = {
$async: true,
type: "object",
properties: {
userId: {
type: "integer",
idExistsWithError: {table: "users"},
},
postId: {
type: "integer",
idExistsWithError: {table: "posts"},
},
},
}
const validate = _ajv.compile(schema)
return Promise.all([
shouldBeInvalid(validate({userId: 5, postId: 10}), ["id not found in table posts"]),
shouldBeInvalid(validate({userId: 9, postId: 25}), ["id not found in table users"]),
])
})
)
})
function checkIdExists(schema, data) {
switch (schema.table) {
case "users":
return check([1, 5, 8])
case "posts":
return check([21, 25, 28])
default:
throw new Error("no such table")
}
function check(IDs) {
return Promise.resolve(IDs.indexOf(data) >= 0)
}
}
function checkIdExistsWithError(schema, data) {
const {table} = schema
switch (table) {
case "users":
return check(table, [1, 5, 8])
case "posts":
return check(table, [21, 25, 28])
default:
throw new Error("no such table")
}
function check(_table, IDs) {
if (IDs.indexOf(data) >= 0) return Promise.resolve(true)
const error = {
keyword: "idExistsWithError",
message: "id not found in table " + _table,
}
return Promise.reject(new _Ajv.ValidationError([error]))
}
}
})
describe("async referenced schemas", () => {
beforeEach(() => {
instances = getAjvAsyncInstances({inlineRefs: false, ignoreKeywordsWithRef: true})
addFormatEnglishWord()
})
it("should validate referenced async schema", () => {
const schema = {
$async: true,
definitions: {
english_word: {
$async: true,
type: "string",
format: "english_word",
},
},
type: "object",
properties: {
word: {$ref: "#/definitions/english_word"},
},
}
return repeat(() => {
return Promise.all(
instances.map((_ajv) => {
const validate = _ajv.compile(schema)
const validData = {word: "tomorrow"}
return Promise.all([
shouldBeValid(validate(validData), validData),
shouldBeInvalid(validate({word: "manana"})),
shouldBeInvalid(validate({word: 1})),
shouldThrow(validate({word: "today"}), "unknown word"),
])
})
)
})
})
it("should validate recursive async schema", () => {
const schema = {
$async: true,
definitions: {
english_word: {
$async: true,
type: "string",
format: "english_word",
},
},
type: "object",
properties: {
foo: {
anyOf: [{$ref: "#/definitions/english_word"}, {$ref: "#"}],
},
},
}
return recursiveTest(schema)
})
it("should validate recursive ref to async sub-schema, issue #612", () => {
const schema = {
$async: true,
type: "object",
properties: {
foo: {
$async: true,
anyOf: [
{
type: "string",
format: "english_word",
},
{
type: "object",
properties: {
foo: {$ref: "#/properties/foo"},
},
},
],
},
},
}
return recursiveTest(schema)
})
it("should validate ref from referenced async schema to root schema", () => {
const schema = {
$async: true,
definitions: {
wordOrRoot: {
$async: true,
anyOf: [
{
type: "string",
format: "english_word",
},
{$ref: "#"},
],
},
},
type: "object",
properties: {
foo: {$ref: "#/definitions/wordOrRoot"},
},
}
return recursiveTest(schema)
})
it("should validate refs between two async schemas", () => {
const schemaObj = {
$id: "http://e.com/obj.json#",
$async: true,
type: "object",
properties: {
foo: {$ref: "http://e.com/word.json#"},
},
}
const schemaWord = {
$id: "http://e.com/word.json#",
$async: true,
anyOf: [
{
type: "string",
format: "english_word",
},
{$ref: "http://e.com/obj.json#"},
],
}
return recursiveTest(schemaObj, schemaWord)
})
it("should fail compilation if sync schema references async schema", () => {
let schema: any = {
$id: "http://e.com/obj.json#",
type: "object",
properties: {
foo: {$ref: "http://e.com/word.json#"},
},
}
const schemaWord = {
$id: "http://e.com/word.json#",
$async: true,
anyOf: [
{
type: "string",
format: "english_word",
},
{$ref: "http://e.com/obj.json#"},
],
}
ajv.addSchema(schemaWord)
ajv.addFormat("english_word", {
async: true,
validate: checkWordOnServer,
})
should.throw(() => {
ajv.compile(schema)
}, "async schema referenced by sync schema")
schema = {...schema, $id: "http://e.com/obj2.json#", $async: true}
ajv.compile(schema)
})
function recursiveTest(schema, refSchema?) {
return repeat(() => {
return Promise.all(
instances.map((_ajv) => {
if (refSchema) _ajv.addSchema(refSchema)
const validate = _ajv.compile(schema)
let data
return Promise.all([
shouldBeValid(validate((data = {foo: "tomorrow"})), data),
shouldBeInvalid(validate({foo: "manana"})),
shouldBeInvalid(validate({foo: 1})),
shouldThrow(validate({foo: "today"}), "unknown word"),
shouldBeValid(validate((data = {foo: {foo: "tomorrow"}})), data),
shouldBeInvalid(validate({foo: {foo: "manana"}})),
shouldBeInvalid(validate({foo: {foo: 1}})),
shouldThrow(validate({foo: {foo: "today"}}), "unknown word"),
shouldBeValid(validate((data = {foo: {foo: {foo: "tomorrow"}}})), data),
shouldBeInvalid(validate({foo: {foo: {foo: "manana"}}})),
shouldBeInvalid(validate({foo: {foo: {foo: 1}}})),
shouldThrow(validate({foo: {foo: {foo: "today"}}}), "unknown word"),
])
})
)
})
}
})
function addFormatEnglishWord() {
instances.forEach((_ajv) => {
_ajv.addFormat("english_word", {
async: true,
validate: checkWordOnServer,
})
})
}
})
function checkWordOnServer(str) {
return str === "tomorrow"
? Promise.resolve(true)
: str === "manana"
? Promise.resolve(false)
: Promise.reject(new Error("unknown word"))
}
function shouldBeValid(p, data) {
return p.then((valid) => valid.should.equal(data))
}
const SHOULD_BE_INVALID = "test: should be invalid"
function shouldBeInvalid(p, expectedMessages?: string[]) {
return checkNotValid(p).then((err) => {
err.should.be.instanceof(_Ajv.ValidationError)
err.errors.should.be.an("array")
err.validation.should.equal(true)
if (expectedMessages) {
const messages = err.errors.map((e) => e.message)
messages.should.eql(expectedMessages)
}
})
}
function shouldThrow(p, exception) {
return checkNotValid(p).then((err) => err.message.should.equal(exception))
}
function checkNotValid(p) {
return p
.then((/* valid */) => {
throw new Error(SHOULD_BE_INVALID)
})
.catch((err) => {
err.should.be.instanceof(Error)
if (err.message === SHOULD_BE_INVALID) throw err
return err
})
}
function repeat(func) {
return func()
// var promises = [];
// for (var i=0; i<1000; i++) promises.push(func());
// return Promise.all(promises);
} | the_stack |
type ErrorText = { [key: string]: string };
/**
* Describes the structure of error messages
*/
export interface ParserErrorMessage {
code: ErrorCodes;
text: string;
position: number;
line: number;
column: number;
}
export type ErrorCodes =
// --- Missing or faulty tokens
| "Z0001"
| "Z0002"
| "Z0003"
| "Z0004"
| "Z0005"
| "Z0006"
| "Z0007"
| "Z0008"
// --- Missing or faulty language elements
| "Z0101"
| "Z0102"
| "Z0103"
| "Z0104"
| "Z0105"
| "Z0106"
| "Z0107"
| "Z0108"
| "Z0109"
| "Z0110"
| "Z0111"
| "Z0112"
| "Z0113"
| "Z0114"
// --- Directive error messages
| "Z0201"
| "Z0202"
| "Z0203"
| "Z0204"
| "Z0205"
| "Z0206"
| "Z0207"
| "Z0208"
// --- Pragma messages
| "Z0301"
| "Z0302"
| "Z0303"
| "Z0304"
| "Z0305"
| "Z0306"
| "Z0307"
| "Z0308"
| "Z0309"
| "Z0310"
| "Z0311"
| "Z0312"
| "Z0313"
| "Z0314"
| "Z0315"
| "Z0316"
| "Z0317"
| "Z0318"
| "Z0319"
| "Z0320"
| "Z0321"
| "Z0322"
| "Z0323"
| "Z0324"
| "Z0325"
| "Z0326"
| "Z0327"
| "Z0328"
| "Z0329"
| "Z0330"
// --- Instructions
| "Z0401"
| "Z0402"
| "Z0403"
| "Z0404"
| "Z0405"
| "Z0406"
| "Z0407"
| "Z0408"
| "Z0409"
| "Z0410"
| "Z0411"
| "Z0412"
| "Z0413"
| "Z0414"
// --- Labels and symbols
| "Z0501"
| "Z0502"
| "Z0503"
| "Z0504"
| "Z0505"
// --- Expressions and operands
| "Z0601"
| "Z0602"
| "Z0603"
| "Z0604"
| "Z0605"
| "Z0606"
// --- Statements
| "Z0701"
| "Z0702"
| "Z0703"
| "Z0704"
| "Z0705"
| "Z0706"
| "Z0707"
| "Z0708"
| "Z0709"
| "Z0710"
// --- Structs
| "Z0801"
| "Z0802"
| "Z0803"
| "Z0804"
| "Z0805"
| "Z0806"
| "Z0807"
| "Z0808"
| "Z0809"
| "Z0810"
// --- Modules
| "Z0901"
| "Z0902"
| "Z0903"
// --- Macros
| "Z1001"
| "Z1002"
| "Z1003"
| "Z1004"
| "Z1005"
| "Z1006"
| "Z1007"
| "Z1008"
| "Z1009"
| "Z1010"
| "Z1011"
| "Z1012"
// --- Others
| "Z2000";
export const errorMessages: ErrorText = {
// --- Missing or faulty tokens
Z0001: "Invalid token at the end of the line: {0}",
Z0002: "A line cannot start with this token: {0}",
Z0003: "A comma expected",
Z0004: "'(' expected",
Z0005: "')' expected",
Z0006: "'}}' expected",
Z0007: "'=' expected",
Z0008: "'to' expected",
// --- Missing or faulty language elements
Z0101: "Register A expected",
Z0102: "Register B expected",
Z0103: "Register DE expected",
Z0104: "Register D expected",
Z0105: "Register E expected",
Z0106: "BC, DE, HL, or SP expected",
Z0107: "An identifier expected",
Z0108: "A string literal expected",
Z0109:
"The lreg and hreg functions accept only a bc, de, hl, ix, or iy as their argument.",
Z0110: "A byte-emitting pragma expected",
Z0111: "An expression expected",
Z0112:
"A mnemonic, a register, or a register indirection expression expected.",
Z0113: "Operand expected",
Z0114: "Cannot parse an integer literal",
// --- Directive error messages
Z0201: "Cannot find include file: '{0}'",
Z0202:
"Include file '{0}' is included more than once into the same parent source file",
Z0203: "Include file '{0}' causes circular file reference",
Z0204: "Error reading include file: '{0}' ({1})",
Z0205: "Missing #endif directive",
Z0206:
"An #ifmod or #ifnmod directive cen be used only with these identifiers: 'SPECTRUM48', 'SPECTRUM128', 'SPECTRUMP3', 'NEXT'.",
Z0207: "Unexpected #else directive",
Z0208: "Unexpected #endif directive",
// --- Pragma messages
Z0301:
"The .ZXBASIC pragma should be used before any other pragma or instruction.",
Z0302: "A .model pragma can be used only once.",
Z0303:
"A .model pragma can have only these values: 'SPECTRUM48', 'SPECTRUM128', 'SPECTRUMP3', 'NEXT'.",
Z0304: "An .equ pragma must have a label",
Z0305: "The .bank pragma cannot have a label.",
Z0306: "The .bank pragma's value must be between 0 and 7.",
Z0307: "The .bank pragma's offset value must be between 0 and #03fff.",
Z0308: "The .bank pragma cannot be used with the ZX Spectrum 48 model type.",
Z0309: "You have already used the .bank pragma for bank {0}.",
Z0310: "The {0} pragma can be used only in the global scope.",
Z0311: "A .var pragma must have a label",
Z0312: "A .var pragma cannot redefine a non-.var-created symbol",
Z0313:
".skip to {0} is invalid, as this address is less then the current address, {1}",
Z0314: "Only one .xorg pragma can be used within a code segment.",
Z0315: ".defm/.defn pragma requires a string argument.",
Z0316: ".defh pragma requires a string argument.",
Z0317: ".defh pragma requires a string with even hexadecimal digits.",
Z0318:
".align pragma must be used with a parameter value between 1 and #4000; {0} is an invalid value.",
Z0319: ".includebin pragma requires a string argument.",
Z0320:
"Invalid .includebin offset value (negative, or greater than the file length).",
Z0321:
"Invalid .includebin length value (negative, or segment exceends the file length).",
Z0322: "Cannot open file '{0}' used in .includebin pragma ({0}).",
Z0323: "Emitting the .includebin segment would overflow the current segment.",
Z0324: ".defgx pragma requires a string argument.",
Z0325: "Cannot use an empty pattern with .defg/.defgx pragma.",
Z0326: "The .comparebin pragma expects a string as its first argument.",
Z0327:
"Invalid .comparebin offset value (negative, or greater than the file length).",
Z0328:
"Invalid .comparebin length value (negative, or segment exceends the file length).",
Z0329: "Cannot open file '{0}' used in .comparebin pragma ({1}).",
Z0330: ".comparebin fails: {0}.",
// --- Instructions
Z0401: "Unexpected error when emitting code for mnemonic '{0}'.",
Z0402:
"The jr instructions cannot be used with the pe, po, p, or m conditions.",
Z0403:
"Relative jump distance should be between -128 and 127. {0} is invalid.",
Z0404:
"The rst instruction can be used only with #00, #08, #10, #18, #20, #28, #30, or #38 arguments. #{0} is invalid.",
Z0405: "Interrupt mode can only be 0, 1, or 2. '{0}' is invalid.",
Z0406: "Output value can only be 0",
Z0407: "Bit index should be between 0 and 7. '{0}' is invalid",
Z0408:
"The first operand must be 'a' when using the two-argument form of the ALU operation.",
Z0409: "The first argument of an 8-bit ALU operation can only be 'a'.",
Z0410: "The current assembly address overflew $FFFF",
Z0411: "The emitted code overflows the segment/bank.",
Z0412: "The pop instruction cannot be used with an expression operand",
Z0413:
"The push and pop instructions can use only these registers: af, bc, de, hl, ix, and iy.",
Z0414:
"To use this Spectrum Next-specific instruction, you need to set .model type to NEXT explicitly.",
// --- Labels and symbols
Z0501: "Label '{0}' is already defined",
Z0502:
"Variable {0} is already declared, it cannot be used as a .for-loop variable again.",
Z0503: "The {0} section in .if/.ifused/.ifnused cannot have a label.",
Z0504: "You cannot define a local symbol with a temporary name ({0}).",
Z0505: "This local symbol is already declared: ({0}).",
// --- Expressions and operands
Z0601: "A string value is used where a numeric value is expected.",
Z0602: "An integral value is expected.",
Z0603: "A numeric expression expected.",
Z0604: "Invalid operand",
Z0605: "Identifier '{0}' is not defined yet.",
Z0606: "Expression evaluation error: {0}",
// --- Statements
Z0701: "Missing end statement for {0}.",
Z0702: "Loop counter cannot be greater than 65535 (#FFFF).",
Z0703:
"Too many errors detected while compiling a loop, further processing aborted.",
Z0704:
"Orphan '{0}' statement found without a corresponding '{1}' statement.",
Z0705: "$CNT cannot be used outside of loop constructs.",
Z0706: "The .step value in a .for-loop cannot be zero.",
Z0707: ".break cannot be used outside of loop constructs.",
Z0708: ".continue cannot be used outside of loop constructs.",
Z0709:
".if/.ifused/.ifnused cannot have an {0} section after a detected .else section.",
Z0710: ".local can be used only within .proc",
// --- Structs
Z0801:
"The .struct size of {0} is {1} byte(s). The invocation wants to emit {2} bytes.",
Z0802: "The .struct definition of {0} does not have a field named {1}.",
Z0803:
"Field assignment instruction cannot be used outside of .struct invocation.",
Z0804: "You cannot define a struct without a name.",
Z0805: "You cannot define a struct with a temporary name ({0}).",
Z0806: "Structure name '{0}' has already been declared.",
Z0807: "The .ends statement cannot have a label.",
Z0808:
"Structures can use only pragmas that emit bytes, words, strings, or reserve space.",
Z0809: "A .struct invocation ({0}) cannot have arguments.",
Z0810: "Duplicated field label {0} in a .struct definition.",
// --- Modules
Z0901: "You cannot define a module without a name.",
Z0902: "You cannot define a module with a temporary name ({0}).",
Z0903: "Module with name '{0}' already exists.",
// --- Macros
Z1001: "Duplicated .macro argument: {0}.",
Z1002: "You cannot define a macro without a name.",
Z1003: "You cannot define a macro with a temporary name ({0}).",
Z1004: "Macro name '{0}' has already been declared.",
Z1005: "Macro definition cannot be nested into another macro definition.",
Z1006: "Unknown macro argument ('{0}') is used in a macro definition.",
Z1007: "Unknown macro: {0}.",
Z1008:
"The declaration of macro {0} contains {1} argument(s), but it is invoked with more parameters ({2}).",
Z1009: "A macro-time function accepts only macro parameters.",
Z1010: "Cannot pass a macro parameter template in a macro argument.",
Z1011: "Macro parameter can only be used within a macro declaration.",
Z1012: "Error in macro invocation",
// --- Others
Z2000: "ERROR: {0}",
}; | the_stack |
declare module com {
export module yalantis {
export module ucrop {
export class BuildConfig {
public static DEBUG: boolean;
public static APPLICATION_ID: string;
public static BUILD_TYPE: string;
public static FLAVOR: string;
public static VERSION_CODE: number;
public static VERSION_NAME: string;
public constructor();
}
}
}
}
import androidnetUri = android.net.Uri;
import androidappActivity = android.app.Activity;
import androidcontentContext = android.content.Context;
import androidappFragment = android.app.Fragment;
import androidsupportv4appFragment = android.support.v4.app.Fragment;
import androidcontentIntent = android.content.Intent;
import javalangThrowable = java.lang.Throwable;
import androidosBundle = android.os.Bundle;
import androidgraphicsBitmapCompressFormat = android.graphics.Bitmap.CompressFormat;
/// <reference path="./android.app.Activity.d.ts" />
/// <reference path="./android.app.Fragment.d.ts" />
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.content.Intent.d.ts" />
/// <reference path="./android.net.Uri.d.ts" />
/// <reference path="./android.os.Bundle.d.ts" />
/// <reference path="./android.support.v4.app.Fragment.d.ts" />
/// <reference path="./com.yalantis.ucrop.model.AspectRatio.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
/// <reference path="./java.lang.Throwable.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export class UCrop {
public static REQUEST_CROP: number;
public static RESULT_ERROR: number;
public static EXTRA_INPUT_URI: string;
public static EXTRA_OUTPUT_URI: string;
public static EXTRA_OUTPUT_CROP_ASPECT_RATIO: string;
public static EXTRA_OUTPUT_IMAGE_WIDTH: string;
public static EXTRA_OUTPUT_IMAGE_HEIGHT: string;
public static EXTRA_OUTPUT_OFFSET_X: string;
public static EXTRA_OUTPUT_OFFSET_Y: string;
public static EXTRA_ERROR: string;
public static EXTRA_ASPECT_RATIO_X: string;
public static EXTRA_ASPECT_RATIO_Y: string;
public static EXTRA_MAX_SIZE_X: string;
public static EXTRA_MAX_SIZE_Y: string;
public start(param0: androidcontentContext, param1: androidsupportv4appFragment): void;
public start(param0: androidcontentContext, param1: androidsupportv4appFragment, param2: number): void;
public useSourceImageAspectRatio(): com.yalantis.ucrop.UCrop;
public withMaxResultSize(param0: number, param1: number): com.yalantis.ucrop.UCrop;
public static getOutputImageWidth(param0: androidcontentIntent): number;
public start(param0: androidappActivity, param1: number): void;
public static getOutputCropAspectRatio(param0: androidcontentIntent): number;
public start(param0: androidappActivity): void;
public withOptions(param0: com.yalantis.ucrop.UCrop.Options): com.yalantis.ucrop.UCrop;
public static getOutput(param0: androidcontentIntent): androidnetUri;
public static getOutputImageHeight(param0: androidcontentIntent): number;
public static getError(param0: androidcontentIntent): javalangThrowable;
public static of(param0: androidnetUri, param1: androidnetUri): com.yalantis.ucrop.UCrop;
public start(param0: androidcontentContext, param1: androidappFragment): void;
public withAspectRatio(param0: number, param1: number): com.yalantis.ucrop.UCrop;
public getIntent(param0: androidcontentContext): androidcontentIntent;
public start(param0: androidcontentContext, param1: androidappFragment, param2: number): void;
}
export module UCrop {
export class Options {
public static EXTRA_COMPRESSION_FORMAT_NAME: string;
public static EXTRA_COMPRESSION_QUALITY: string;
public static EXTRA_ALLOWED_GESTURES: string;
public static EXTRA_MAX_BITMAP_SIZE: string;
public static EXTRA_MAX_SCALE_MULTIPLIER: string;
public static EXTRA_IMAGE_TO_CROP_BOUNDS_ANIM_DURATION: string;
public static EXTRA_DIMMED_LAYER_COLOR: string;
public static EXTRA_CIRCLE_DIMMED_LAYER: string;
public static EXTRA_SHOW_CROP_FRAME: string;
public static EXTRA_CROP_FRAME_COLOR: string;
public static EXTRA_CROP_FRAME_STROKE_WIDTH: string;
public static EXTRA_SHOW_CROP_GRID: string;
public static EXTRA_CROP_GRID_ROW_COUNT: string;
public static EXTRA_CROP_GRID_COLUMN_COUNT: string;
public static EXTRA_CROP_GRID_COLOR: string;
public static EXTRA_CROP_GRID_STROKE_WIDTH: string;
public static EXTRA_TOOL_BAR_COLOR: string;
public static EXTRA_STATUS_BAR_COLOR: string;
public static EXTRA_UCROP_COLOR_WIDGET_ACTIVE: string;
public static EXTRA_UCROP_WIDGET_COLOR_TOOLBAR: string;
public static EXTRA_UCROP_TITLE_TEXT_TOOLBAR: string;
public static EXTRA_UCROP_WIDGET_CANCEL_DRAWABLE: string;
public static EXTRA_UCROP_WIDGET_CROP_DRAWABLE: string;
public static EXTRA_UCROP_LOGO_COLOR: string;
public static EXTRA_HIDE_BOTTOM_CONTROLS: string;
public static EXTRA_FREE_STYLE_CROP: string;
public static EXTRA_ASPECT_RATIO_SELECTED_BY_DEFAULT: string;
public static EXTRA_ASPECT_RATIO_OPTIONS: string;
public static EXTRA_UCROP_ROOT_VIEW_BACKGROUND_COLOR: string;
public setAllowedGestures(param0: number, param1: number, param2: number): void;
public setImageToCropBoundsAnimDuration(param0: number): void;
public setActiveWidgetColor(param0: number): void;
public setAspectRatioOptions(param0: number, param1: native.Array<com.yalantis.ucrop.model.AspectRatio>): void;
public setMaxBitmapSize(param0: number): void;
public getOptionBundle(): androidosBundle;
public setToolbarColor(param0: number): void;
public setToolbarCancelDrawable(param0: number): void;
public setCropGridColumnCount(param0: number): void;
public setLogoColor(param0: number): void;
public setFreeStyleCropEnabled(param0: boolean): void;
public constructor();
public setCircleDimmedLayer(param0: boolean): void;
public setDimmedLayerColor(param0: number): void;
public setCropGridRowCount(param0: number): void;
public setCropGridStrokeWidth(param0: number): void;
public setToolbarCropDrawable(param0: number): void;
public setCropFrameColor(param0: number): void;
public setRootViewBackgroundColor(param0: number): void;
public setCompressionQuality(param0: number): void;
public setCropGridColor(param0: number): void;
public setStatusBarColor(param0: number): void;
public setToolbarTitle(param0: string): void;
public useSourceImageAspectRatio(): void;
public setCropFrameStrokeWidth(param0: number): void;
public setToolbarWidgetColor(param0: number): void;
public withAspectRatio(param0: number, param1: number): void;
public setHideBottomControls(param0: boolean): void;
public setShowCropGrid(param0: boolean): void;
public withMaxResultSize(param0: number, param1: number): void;
public setCompressionFormat(param0: androidgraphicsBitmapCompressFormat): void;
public setShowCropFrame(param0: boolean): void;
public setMaxScaleMultiplier(param0: number): void;
}
}
}
}
}
import androidviewMenu = android.view.Menu;
import androidviewMenuItem = android.view.MenuItem;
/// <reference path="./android.net.Uri.d.ts" />
/// <reference path="./android.os.Bundle.d.ts" />
/// <reference path="./android.view.Menu.d.ts" />
/// <reference path="./android.view.MenuItem.d.ts" />
/// <reference path="./java.lang.Throwable.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export class UCropActivity {
public static DEFAULT_COMPRESS_QUALITY: number;
public static DEFAULT_COMPRESS_FORMAT: androidgraphicsBitmapCompressFormat;
public static NONE: number;
public static SCALE: number;
public static ROTATE: number;
public static ALL: number;
public onCreate(param0: androidosBundle): void;
public onPrepareOptionsMenu(param0: androidviewMenu): boolean;
public onOptionsItemSelected(param0: androidviewMenuItem): boolean;
public onCreateOptionsMenu(param0: androidviewMenu): boolean;
public onStop(): void;
public cropAndSaveImage(): void;
public setResultUri(param0: androidnetUri, param1: number, param2: number, param3: number, param4: number, param5: number): void;
public constructor();
public setResultError(param0: javalangThrowable): void;
}
export module UCropActivity {
export class GestureTypes {
/**
* Constructs a new instance of the com.yalantis.ucrop.UCropActivity$GestureTypes interface with the provided implementation.
*/
public constructor(implementation: {
});
}
}
}
}
}
/// <reference path="./android.net.Uri.d.ts" />
/// <reference path="./java.lang.Throwable.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module callback {
export class BitmapCropCallback {
/**
* Constructs a new instance of the com.yalantis.ucrop.callback.BitmapCropCallback interface with the provided implementation.
*/
public constructor(implementation: {
onBitmapCropped(param0: androidnetUri, param1: number, param2: number, param3: number, param4: number): void;
onCropFailure(param0: javalangThrowable): void;
});
public onCropFailure(param0: javalangThrowable): void;
public onBitmapCropped(param0: androidnetUri, param1: number, param2: number, param3: number, param4: number): void;
}
}
}
}
}
import androidgraphicsBitmap = android.graphics.Bitmap;
import javalangException = java.lang.Exception;
/// <reference path="./android.graphics.Bitmap.d.ts" />
/// <reference path="./com.yalantis.ucrop.model.ExifInfo.d.ts" />
/// <reference path="./java.lang.Exception.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module callback {
export class BitmapLoadCallback {
/**
* Constructs a new instance of the com.yalantis.ucrop.callback.BitmapLoadCallback interface with the provided implementation.
*/
public constructor(implementation: {
onBitmapLoaded(param0: androidgraphicsBitmap, param1: com.yalantis.ucrop.model.ExifInfo, param2: string, param3: string): void;
onFailure(param0: javalangException): void;
});
public onFailure(param0: javalangException): void;
public onBitmapLoaded(param0: androidgraphicsBitmap, param1: com.yalantis.ucrop.model.ExifInfo, param2: string, param3: string): void;
}
}
}
}
}
declare module com {
export module yalantis {
export module ucrop {
export module callback {
export class CropBoundsChangeListener {
/**
* Constructs a new instance of the com.yalantis.ucrop.callback.CropBoundsChangeListener interface with the provided implementation.
*/
public constructor(implementation: {
onCropAspectRatioChanged(param0: number): void;
});
public onCropAspectRatioChanged(param0: number): void;
}
}
}
}
}
import androidgraphicsRectF = android.graphics.RectF;
/// <reference path="./android.graphics.RectF.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module callback {
export class OverlayViewChangeListener {
/**
* Constructs a new instance of the com.yalantis.ucrop.callback.OverlayViewChangeListener interface with the provided implementation.
*/
public constructor(implementation: {
onCropRectUpdated(param0: androidgraphicsRectF): void;
});
public onCropRectUpdated(param0: androidgraphicsRectF): void;
}
}
}
}
}
import androidosParcel = android.os.Parcel;
import androidosParcelableCreator = android.os.Parcelable.Creator;
/// <reference path="./android.os.Parcel.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module model {
export class AspectRatio {
public static CREATOR: androidosParcelableCreator;
public getAspectRatioTitle(): string;
public constructor(param0: androidosParcel);
public describeContents(): number;
public constructor(param0: string, param1: number, param2: number);
public writeToParcel(param0: androidosParcel, param1: number): void;
public getAspectRatioX(): number;
public getAspectRatioY(): number;
}
}
}
}
}
/// <reference path="./com.yalantis.ucrop.model.ExifInfo.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module model {
export class CropParameters {
public constructor(param0: number, param1: number, param2: androidgraphicsBitmapCompressFormat, param3: number, param4: string, param5: string, param6: com.yalantis.ucrop.model.ExifInfo);
public getCompressFormat(): androidgraphicsBitmapCompressFormat;
public getExifInfo(): com.yalantis.ucrop.model.ExifInfo;
public getCompressQuality(): number;
public getImageOutputPath(): string;
public getImageInputPath(): string;
public getMaxResultImageSizeY(): number;
public getMaxResultImageSizeX(): number;
}
}
}
}
}
import javalangObject = java.lang.Object;
/// <reference path="./java.lang.Object.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module model {
export class ExifInfo {
public getExifDegrees(): number;
public equals(param0: javalangObject): boolean;
public constructor(param0: number, param1: number, param2: number);
public setExifDegrees(param0: number): void;
public getExifTranslation(): number;
public setExifOrientation(param0: number): void;
public getExifOrientation(): number;
public hashCode(): number;
public setExifTranslation(param0: number): void;
}
}
}
}
}
/// <reference path="./android.graphics.RectF.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module model {
export class ImageState {
public constructor(param0: androidgraphicsRectF, param1: androidgraphicsRectF, param2: number, param3: number);
public getCurrentImageRect(): androidgraphicsRectF;
public getCurrentScale(): number;
public getCurrentAngle(): number;
public getCropRect(): androidgraphicsRectF;
}
}
}
}
}
import javalangVoid = java.lang.Void;
/// <reference path="./android.graphics.Bitmap.d.ts" />
/// <reference path="./com.yalantis.ucrop.callback.BitmapCropCallback.d.ts" />
/// <reference path="./com.yalantis.ucrop.model.CropParameters.d.ts" />
/// <reference path="./com.yalantis.ucrop.model.ImageState.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
/// <reference path="./java.lang.Throwable.d.ts" />
/// <reference path="./java.lang.Void.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module task {
export class BitmapCropTask {
public constructor(param0: androidgraphicsBitmap, param1: com.yalantis.ucrop.model.ImageState, param2: com.yalantis.ucrop.model.CropParameters, param3: com.yalantis.ucrop.callback.BitmapCropCallback);
public doInBackground(param0: native.Array<javalangVoid>): javalangThrowable;
public onPostExecute(param0: javalangThrowable): void;
public static cropCImg(param0: string, param1: string, param2: number, param3: number, param4: number, param5: number, param6: number, param7: number, param8: number, param9: number, param10: number, param11: number): boolean;
}
}
}
}
}
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.graphics.Bitmap.d.ts" />
/// <reference path="./android.net.Uri.d.ts" />
/// <reference path="./com.yalantis.ucrop.callback.BitmapLoadCallback.d.ts" />
/// <reference path="./com.yalantis.ucrop.model.ExifInfo.d.ts" />
/// <reference path="./java.lang.Exception.d.ts" />
/// <reference path="./java.lang.Void.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module task {
export class BitmapLoadTask {
public constructor(param0: androidcontentContext, param1: androidnetUri, param2: androidnetUri, param3: number, param4: number, param5: com.yalantis.ucrop.callback.BitmapLoadCallback);
public doInBackground(param0: native.Array<javalangVoid>): com.yalantis.ucrop.task.BitmapLoadTask.BitmapWorkerResult;
public onPostExecute(param0: com.yalantis.ucrop.task.BitmapLoadTask.BitmapWorkerResult): void;
}
export module BitmapLoadTask {
export class BitmapWorkerResult {
public constructor(param0: androidgraphicsBitmap, param1: com.yalantis.ucrop.model.ExifInfo);
public constructor(param0: javalangException);
}
}
}
}
}
}
import androidgraphicsMatrix = android.graphics.Matrix;
import androidgraphicsBitmapFactoryOptions = android.graphics.BitmapFactory.Options;
import javaioCloseable = java.io.Closeable;
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.graphics.Bitmap.d.ts" />
/// <reference path="./android.graphics.Matrix.d.ts" />
/// <reference path="./android.net.Uri.d.ts" />
/// <reference path="./com.yalantis.ucrop.callback.BitmapLoadCallback.d.ts" />
/// <reference path="./java.io.Closeable.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class BitmapLoadUtils {
public static calculateInSampleSize(param0: androidgraphicsBitmapFactoryOptions, param1: number, param2: number): number;
public static exifToTranslation(param0: number): number;
public static calculateMaxBitmapSize(param0: androidcontentContext): number;
public constructor();
public static close(param0: javaioCloseable): void;
public static getExifOrientation(param0: androidcontentContext, param1: androidnetUri): number;
public static decodeBitmapInBackground(param0: androidcontentContext, param1: androidnetUri, param2: androidnetUri, param3: number, param4: number, param5: com.yalantis.ucrop.callback.BitmapLoadCallback): void;
public static transformBitmap(param0: androidgraphicsBitmap, param1: androidgraphicsMatrix): androidgraphicsBitmap;
public static exifToDegrees(param0: number): number;
}
}
}
}
}
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class CubicEasing {
public static easeInOut(param0: number, param1: number, param2: number, param3: number): number;
public constructor();
public static easeIn(param0: number, param1: number, param2: number, param3: number): number;
public static easeOut(param0: number, param1: number, param2: number, param3: number): number;
}
}
}
}
}
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class EglUtils {
public static getMaxTextureSize(): number;
}
}
}
}
}
import androidgraphicsCanvas = android.graphics.Canvas;
import androidgraphicsColorFilter = android.graphics.ColorFilter;
/// <reference path="./android.graphics.Bitmap.d.ts" />
/// <reference path="./android.graphics.Canvas.d.ts" />
/// <reference path="./android.graphics.ColorFilter.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class FastBitmapDrawable {
public constructor(param0: androidgraphicsBitmap);
public getAlpha(): number;
public getMinimumWidth(): number;
public getBitmap(): androidgraphicsBitmap;
public getIntrinsicHeight(): number;
public setBitmap(param0: androidgraphicsBitmap): void;
public setColorFilter(param0: androidgraphicsColorFilter): void;
public getIntrinsicWidth(): number;
public setAlpha(param0: number): void;
public setFilterBitmap(param0: boolean): void;
public draw(param0: androidgraphicsCanvas): void;
public getMinimumHeight(): number;
public getOpacity(): number;
}
}
}
}
}
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.net.Uri.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class FileUtils {
public static getPath(param0: androidcontentContext, param1: androidnetUri): string;
public static copyFile(param0: string, param1: string): void;
public static isDownloadsDocument(param0: androidnetUri): boolean;
public static isGooglePhotosUri(param0: androidnetUri): boolean;
public static isMediaDocument(param0: androidnetUri): boolean;
public static isExternalStorageDocument(param0: androidnetUri): boolean;
public static getDataColumn(param0: androidcontentContext, param1: androidnetUri, param2: string, param3: native.Array<string>): string;
}
}
}
}
}
import javaioInputStream = java.io.InputStream;
import androidmediaExifInterface = android.media.ExifInterface;
import javanioByteOrder = java.nio.ByteOrder;
/// <reference path="./android.media.ExifInterface.d.ts" />
/// <reference path="./java.io.InputStream.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
/// <reference path="./java.nio.ByteOrder.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class ImageHeaderParser {
public static UNKNOWN_ORIENTATION: number;
public constructor(param0: javaioInputStream);
public getOrientation(): number;
public static copyExif(param0: androidmediaExifInterface, param1: number, param2: number, param3: string): void;
}
export module ImageHeaderParser {
export class RandomAccessReader {
public constructor(param0: native.Array<number>, param1: number);
public order(param0: javanioByteOrder): void;
public length(): number;
public getInt32(param0: number): number;
public getInt16(param0: number): number;
}
export class Reader {
/**
* Constructs a new instance of the com.yalantis.ucrop.util.ImageHeaderParser$Reader interface with the provided implementation.
*/
public constructor(implementation: {
getUInt16(): number;
getUInt8(): number;
skip(param0: number): number;
read(param0: native.Array<number>, param1: number): number;
});
public skip(param0: number): number;
public getUInt16(): number;
public getUInt8(): number;
public read(param0: native.Array<number>, param1: number): number;
}
export class StreamReader {
public skip(param0: number): number;
public getUInt16(): number;
public constructor(param0: javaioInputStream);
public getUInt8(): number;
public read(param0: native.Array<number>, param1: number): number;
}
}
}
}
}
}
/// <reference path="./android.graphics.RectF.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class RectUtils {
public static getCornersFromRect(param0: androidgraphicsRectF): native.Array<number>;
public static getCenterFromRect(param0: androidgraphicsRectF): native.Array<number>;
public constructor();
public static getRectSidesFromCorners(param0: native.Array<number>): native.Array<number>;
public static trapToRect(param0: native.Array<number>): androidgraphicsRectF;
}
}
}
}
}
import androidviewMotionEvent = android.view.MotionEvent;
/// <reference path="./android.view.MotionEvent.d.ts" />
/// <reference path="./com.yalantis.ucrop.util.RotationGestureDetector.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class RotationGestureDetector {
public constructor(param0: com.yalantis.ucrop.util.RotationGestureDetector.OnRotationGestureListener);
public getAngle(): number;
public onTouchEvent(param0: androidviewMotionEvent): boolean;
}
export module RotationGestureDetector {
export class OnRotationGestureListener {
/**
* Constructs a new instance of the com.yalantis.ucrop.util.RotationGestureDetector$OnRotationGestureListener interface with the provided implementation.
*/
public constructor(implementation: {
onRotation(param0: com.yalantis.ucrop.util.RotationGestureDetector): boolean;
});
public onRotation(param0: com.yalantis.ucrop.util.RotationGestureDetector): boolean;
}
export class SimpleOnRotationGestureListener {
public constructor();
public onRotation(param0: com.yalantis.ucrop.util.RotationGestureDetector): boolean;
}
}
}
}
}
}
import androidgraphicsdrawableDrawable = android.graphics.drawable.Drawable;
/// <reference path="./android.graphics.drawable.Drawable.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module util {
export class SelectedStateListDrawable {
public constructor(param0: androidgraphicsdrawableDrawable, param1: number);
public onStateChange(param0: native.Array<number>): boolean;
public isStateful(): boolean;
}
}
}
}
}
import androidutilAttributeSet = android.util.AttributeSet;
import androidcontentresTypedArray = android.content.res.TypedArray;
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.content.res.TypedArray.d.ts" />
/// <reference path="./android.graphics.RectF.d.ts" />
/// <reference path="./android.util.AttributeSet.d.ts" />
/// <reference path="./com.yalantis.ucrop.callback.BitmapCropCallback.d.ts" />
/// <reference path="./com.yalantis.ucrop.callback.CropBoundsChangeListener.d.ts" />
/// <reference path="./com.yalantis.ucrop.view.CropImageView.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module view {
export class CropImageView extends com.yalantis.ucrop.view.TransformImageView {
public static DEFAULT_MAX_BITMAP_SIZE: number;
public static DEFAULT_IMAGE_TO_CROP_BOUNDS_ANIM_DURATION: number;
public static DEFAULT_MAX_SCALE_MULTIPLIER: number;
public static SOURCE_IMAGE_ASPECT_RATIO: number;
public static DEFAULT_ASPECT_RATIO: number;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number);
public zoomInImage(param0: number, param1: number, param2: number): void;
public postRotate(param0: number, param1: number, param2: number): void;
public setCropRect(param0: androidgraphicsRectF): void;
public processStyledAttributes(param0: androidcontentresTypedArray): void;
public cropAndSaveImage(param0: androidgraphicsBitmapCompressFormat, param1: number, param2: com.yalantis.ucrop.callback.BitmapCropCallback): void;
public getCropBoundsChangeListener(): com.yalantis.ucrop.callback.CropBoundsChangeListener;
public setMaxResultImageSizeX(param0: number): void;
public zoomOutImage(param0: number): void;
public cancelAllAnimations(): void;
public getMinScale(): number;
public getTargetAspectRatio(): number;
public zoomImageToPosition(param0: number, param1: number, param2: number, param3: number): void;
public setTargetAspectRatio(param0: number): void;
public isImageWrapCropBounds(param0: native.Array<number>): boolean;
public postScale(param0: number, param1: number, param2: number): void;
public postRotate(param0: number): void;
public setImageToWrapCropBoundsAnimDuration(param0: number): void;
public onImageLaidOut(): void;
public setCropBoundsChangeListener(param0: com.yalantis.ucrop.callback.CropBoundsChangeListener): void;
public isImageWrapCropBounds(): boolean;
public setMaxResultImageSizeY(param0: number): void;
public setImageToWrapCropBounds(param0: boolean): void;
public getMaxScale(): number;
public zoomInImage(param0: number): void;
public zoomOutImage(param0: number, param1: number, param2: number): void;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet);
public setImageToWrapCropBounds(): void;
public constructor(param0: androidcontentContext);
public setMaxScaleMultiplier(param0: number): void;
}
export module CropImageView {
export class WrapCropBoundsRunnable {
public run(): void;
public constructor(param0: com.yalantis.ucrop.view.CropImageView, param1: number, param2: number, param3: number, param4: number, param5: number, param6: number, param7: number, param8: boolean);
}
export class ZoomImageToPosition {
public run(): void;
public constructor(param0: com.yalantis.ucrop.view.CropImageView, param1: number, param2: number, param3: number, param4: number, param5: number);
}
}
}
}
}
}
import androidviewScaleGestureDetector = android.view.ScaleGestureDetector;
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.util.AttributeSet.d.ts" />
/// <reference path="./android.view.MotionEvent.d.ts" />
/// <reference path="./android.view.ScaleGestureDetector.d.ts" />
/// <reference path="./com.yalantis.ucrop.util.RotationGestureDetector.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module view {
export class GestureCropImageView extends com.yalantis.ucrop.view.CropImageView {
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number);
public onTouchEvent(param0: androidviewMotionEvent): boolean;
public isRotateEnabled(): boolean;
public getDoubleTapScaleSteps(): number;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet);
public isScaleEnabled(): boolean;
public constructor(param0: androidcontentContext);
public init(): void;
public setScaleEnabled(param0: boolean): void;
public setRotateEnabled(param0: boolean): void;
public setDoubleTapScaleSteps(param0: number): void;
public getDoubleTapTargetScale(): number;
}
export module GestureCropImageView {
export class GestureListener {
public onDoubleTap(param0: androidviewMotionEvent): boolean;
public onScroll(param0: androidviewMotionEvent, param1: androidviewMotionEvent, param2: number, param3: number): boolean;
}
export class RotateListener extends com.yalantis.ucrop.util.RotationGestureDetector.SimpleOnRotationGestureListener {
public onRotation(param0: com.yalantis.ucrop.util.RotationGestureDetector): boolean;
}
export class ScaleListener {
public onScale(param0: androidviewScaleGestureDetector): boolean;
}
}
}
}
}
}
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.content.res.TypedArray.d.ts" />
/// <reference path="./android.graphics.Canvas.d.ts" />
/// <reference path="./android.graphics.RectF.d.ts" />
/// <reference path="./android.util.AttributeSet.d.ts" />
/// <reference path="./android.view.MotionEvent.d.ts" />
/// <reference path="./com.yalantis.ucrop.callback.OverlayViewChangeListener.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module view {
export class OverlayView {
public static FREESTYLE_CROP_MODE_DISABLE: number;
public static FREESTYLE_CROP_MODE_ENABLE: number;
public static FREESTYLE_CROP_MODE_ENABLE_WITH_PASS_THROUGH: number;
public static DEFAULT_SHOW_CROP_FRAME: boolean;
public static DEFAULT_SHOW_CROP_GRID: boolean;
public static DEFAULT_CIRCLE_DIMMED_LAYER: boolean;
public static DEFAULT_FREESTYLE_CROP_MODE: number;
public static DEFAULT_CROP_GRID_ROW_COUNT: number;
public static DEFAULT_CROP_GRID_COLUMN_COUNT: number;
public mThisWidth: number;
public mThisHeight: number;
public mCropGridCorners: native.Array<number>;
public mCropGridCenter: native.Array<number>;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number);
public onTouchEvent(param0: androidviewMotionEvent): boolean;
public setDimmedColor(param0: number): void;
public onDraw(param0: androidgraphicsCanvas): void;
public processStyledAttributes(param0: androidcontentresTypedArray): void;
public setCropGridColumnCount(param0: number): void;
public getOverlayViewChangeListener(): com.yalantis.ucrop.callback.OverlayViewChangeListener;
public setTargetAspectRatio(param0: number): void;
public setCircleDimmedLayer(param0: boolean): void;
public setCropGridRowCount(param0: number): void;
public setCropGridStrokeWidth(param0: number): void;
public drawCropGrid(param0: androidgraphicsCanvas): void;
public setCropFrameColor(param0: number): void;
public setCropGridColor(param0: number): void;
public init(): void;
public setCropFrameStrokeWidth(param0: number): void;
public getFreestyleCropMode(): number;
public setFreestyleCropEnabled(param0: boolean): void;
public drawDimmedLayer(param0: androidgraphicsCanvas): void;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet);
public setFreestyleCropMode(param0: number): void;
public setShowCropGrid(param0: boolean): void;
public onLayout(param0: boolean, param1: number, param2: number, param3: number, param4: number): void;
public isFreestyleCropEnabled(): boolean;
public constructor(param0: androidcontentContext);
public setShowCropFrame(param0: boolean): void;
public setupCropBounds(): void;
public getCropViewRect(): androidgraphicsRectF;
public setOverlayViewChangeListener(param0: com.yalantis.ucrop.callback.OverlayViewChangeListener): void;
}
export module OverlayView {
export class FreestyleMode {
/**
* Constructs a new instance of the com.yalantis.ucrop.view.OverlayView$FreestyleMode interface with the provided implementation.
*/
public constructor(implementation: {
});
}
}
}
}
}
}
import androidwidgetImageViewScaleType = android.widget.ImageView.ScaleType;
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.graphics.Bitmap.d.ts" />
/// <reference path="./android.graphics.Matrix.d.ts" />
/// <reference path="./android.net.Uri.d.ts" />
/// <reference path="./android.util.AttributeSet.d.ts" />
/// <reference path="./com.yalantis.ucrop.model.ExifInfo.d.ts" />
/// <reference path="./java.lang.Exception.d.ts" />
/// <reference path="./java.lang.String.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module view {
export class TransformImageView {
public mCurrentImageCorners: native.Array<number>;
public mCurrentImageCenter: native.Array<number>;
public mCurrentImageMatrix: androidgraphicsMatrix;
public mThisWidth: number;
public mThisHeight: number;
public mTransformImageListener: com.yalantis.ucrop.view.TransformImageView.TransformImageListener;
public mBitmapDecoded: boolean;
public mBitmapLaidOut: boolean;
public getMatrixValue(param0: androidgraphicsMatrix, param1: number): number;
public getMaxBitmapSize(): number;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number);
public postRotate(param0: number, param1: number, param2: number): void;
public setImageUri(param0: androidnetUri, param1: androidnetUri): void;
public setMaxBitmapSize(param0: number): void;
public setTransformImageListener(param0: com.yalantis.ucrop.view.TransformImageView.TransformImageListener): void;
public postTranslate(param0: number, param1: number): void;
public getExifInfo(): com.yalantis.ucrop.model.ExifInfo;
public getImageInputPath(): string;
public getMatrixAngle(param0: androidgraphicsMatrix): number;
public postScale(param0: number, param1: number, param2: number): void;
public setImageMatrix(param0: androidgraphicsMatrix): void;
public setScaleType(param0: androidwidgetImageViewScaleType): void;
public onImageLaidOut(): void;
public getMatrixScale(param0: androidgraphicsMatrix): number;
public getCurrentScale(): number;
public getViewBitmap(): androidgraphicsBitmap;
public getImageOutputPath(): string;
public setImageBitmap(param0: androidgraphicsBitmap): void;
public init(): void;
public printMatrix(param0: string, param1: androidgraphicsMatrix): void;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet);
public onLayout(param0: boolean, param1: number, param2: number, param3: number, param4: number): void;
public getCurrentAngle(): number;
public constructor(param0: androidcontentContext);
}
export module TransformImageView {
export class TransformImageListener {
/**
* Constructs a new instance of the com.yalantis.ucrop.view.TransformImageView$TransformImageListener interface with the provided implementation.
*/
public constructor(implementation: {
onLoadComplete(): void;
onLoadFailure(param0: javalangException): void;
onRotate(param0: number): void;
onScale(param0: number): void;
});
public onLoadFailure(param0: javalangException): void;
public onRotate(param0: number): void;
public onScale(param0: number): void;
public onLoadComplete(): void;
}
}
}
}
}
}
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.util.AttributeSet.d.ts" />
/// <reference path="./com.yalantis.ucrop.view.GestureCropImageView.d.ts" />
/// <reference path="./com.yalantis.ucrop.view.OverlayView.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module view {
export class UCropView {
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number);
public shouldDelayChildPressedState(): boolean;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet);
public getCropImageView(): com.yalantis.ucrop.view.GestureCropImageView;
public resetCropImageView(): void;
public getOverlayView(): com.yalantis.ucrop.view.OverlayView;
}
}
}
}
}
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.graphics.Canvas.d.ts" />
/// <reference path="./android.util.AttributeSet.d.ts" />
/// <reference path="./com.yalantis.ucrop.model.AspectRatio.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module view {
export module widget {
export class AspectRatioTextView {
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet);
public setActiveColor(param0: number): void;
public getAspectRatio(param0: boolean): number;
public onDraw(param0: androidgraphicsCanvas): void;
public setAspectRatio(param0: com.yalantis.ucrop.model.AspectRatio): void;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number);
public constructor(param0: androidcontentContext);
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number, param3: number);
}
}
}
}
}
}
/// <reference path="./android.content.Context.d.ts" />
/// <reference path="./android.graphics.Canvas.d.ts" />
/// <reference path="./android.util.AttributeSet.d.ts" />
/// <reference path="./android.view.MotionEvent.d.ts" />
declare module com {
export module yalantis {
export module ucrop {
export module view {
export module widget {
export class HorizontalProgressWheelView {
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet);
public setScrollingListener(param0: com.yalantis.ucrop.view.widget.HorizontalProgressWheelView.ScrollingListener): void;
public onDraw(param0: androidgraphicsCanvas): void;
public setMiddleLineColor(param0: number): void;
public onTouchEvent(param0: androidviewMotionEvent): boolean;
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number);
public constructor(param0: androidcontentContext);
public constructor(param0: androidcontentContext, param1: androidutilAttributeSet, param2: number, param3: number);
}
export module HorizontalProgressWheelView {
export class ScrollingListener {
/**
* Constructs a new instance of the com.yalantis.ucrop.view.widget.HorizontalProgressWheelView$ScrollingListener interface with the provided implementation.
*/
public constructor(implementation: {
onScrollStart(): void;
onScroll(param0: number, param1: number): void;
onScrollEnd(): void;
});
public onScrollStart(): void;
public onScroll(param0: number, param1: number): void;
public onScrollEnd(): void;
}
}
}
}
}
}
} | the_stack |
// WARNING: Do not edit the *.js version of this file. Instead, always edit the
// corresponding *.ts source in the ts subfolder, and then invoke the
// compileTypescript.sh bash script to generate new *.js and *.js.map files.
module workbench {
export module query {
/**
* JSON value provided by script element in document (see query.xsl).
*/
declare var sparqlNamespaces: any;
/**
* Holds the current selected query language.
*/
var currentQueryLn = '';
var yasqe: YASQE_Instance = null;
/**
* Populate reasonable default name space declarations into the query text area.
* The server has provided the declaration text in hidden elements.
*/
export function loadNamespaces() {
function toggleNamespaces() {
workbench.query.setQueryValue(namespaces.text());
currentQueryLn = queryLn;
}
var query: string = workbench.query.getQueryValue();
var queryLn = $('#queryLn').val();
var namespaces = $('#' + queryLn + '-namespaces');
var last = $('#' + currentQueryLn + '-namespaces');
if (namespaces.length) {
if (!query || query.trim().length == 0) {
toggleNamespaces();
}
if (last.length && (query == last.text())) {
toggleNamespaces();
}
}
}
/**
*Fires when the query language is changed
*/
export function onQlChange() {
workbench.query.loadNamespaces();
workbench.query.updateYasqe();
}
/**
* Invoked by the "clear" button. After confirming with the user,
* clears the query text and loads the current repository and query
* language name space declarations.
*/
export function resetNamespaces() {
if (confirm('Click OK to clear the current query text and replace' +
'it with the ' + $('#queryLn').val() +
' namespace declarations.')) {
workbench.query.setQueryValue('');
workbench.query.loadNamespaces();
}
}
/**
* Clear any contents of the save feedback field.
*/
export function clearFeedback() {
$('#save-feedback').removeClass().text('');
}
/**
* Clear the save feedback field, and look at the contents of the query name
* field. Disables the save button if the field doesn't satisfy a given regular
* expression. With a delay of 200 msec, to give enough time after
* the event for the document to have changed. (Workaround for annoying browser
* behavior.)
*/
export function handleNameChange() {
setTimeout(function disableSaveIfNotValidName() {
$('#save').prop('disabled',
!/^[- \w]{1,32}$/.test($('#query-name').val()));
workbench.query.clearFeedback();
}, 0);
}
interface AjaxSaveResponse {
accessible: boolean;
existed: boolean;
written: boolean;
}
/**
* Send a background HTTP request to save the query, and handle the
* response asynchronously.
*
* @param overwrite
* if true, add a URL parameter that tells the server we wish
* to overwrite any already saved query
*/
function ajaxSave(overwrite: boolean) {
var feedback = $('#save-feedback');
var url: string[] = [];
url[url.length] = 'query';
if (overwrite) {
url[url.length] = document.all ? ';' : '?';
url[url.length] = 'overwrite=true&'
}
var href = url.join('');
var form = $('form[action="query"]');
$.ajax({
url: href,
type: 'POST',
dataType: 'json',
data: form.serialize(),
timeout: 5000,
error: function(jqXHR: JQueryXHR, textStatus: string, errorThrown: string) {
feedback.removeClass().addClass('error');
if (textStatus == 'timeout') {
feedback.text('Timed out waiting for response. Uncertain if save occured.');
} else {
feedback.text('Save Request Failed: Error Type = ' +
textStatus + ', HTTP Status Text = "' + errorThrown + '"');
}
},
success: function(response: AjaxSaveResponse) {
if (response.accessible) {
if (response.written) {
feedback.removeClass().addClass('success');
feedback.text('Query saved.');
} else {
if (response.existed) {
if (confirm('Query name exists. Click OK to overwrite.')) {
ajaxSave(true);
} else {
feedback.removeClass().addClass('error');
feedback.text('Cancelled overwriting existing query.');
}
}
}
} else {
feedback.removeClass().addClass('error');
feedback.text('Repository was not accessible (check your permissions).');
}
}
});
}
/**
* Invoked by form submission.
*
* @returns {boolean} true if a form POST is performed, false if
* a GET is instead performed
*/
export function doSubmit() {
//if yasqe is instantiated, make sure we save the value to the textarea
if (yasqe) yasqe.save();
var allowPageToSubmitForm = false;
var save = ($('#action').val() == 'save');
if (save) {
ajaxSave(false);
} else {
var url: string[] = [];
url[url.length] = 'query';
if (document.all) {
url[url.length] = ';';
} else {
url[url.length] = '?';
}
workbench.addParam(url, 'action');
workbench.addParam(url, 'queryLn');
workbench.addParam(url, 'query');
workbench.addParam(url, 'limit_query');
workbench.addParam(url, 'infer');
var href = url.join('');
var loc = document.location;
var currentBaseLength = loc.href.length - loc.pathname.length
- loc.search.length;
var pathLength = href.length;
var urlLength = pathLength + currentBaseLength;
// Published Internet Explorer restrictions on URL length, which are the
// most restrictive of the major browsers.
if (pathLength > 2048 || urlLength > 2083) {
alert("Due to its length, your query will be posted in the request body. "
+ "It won't be possible to use a bookmark for the results page.");
allowPageToSubmitForm = true;
} else {
// GET using the constructed URL, method exits here
document.location.href = href;
}
}
// Value returned to form submit event. If not true, prevents normal form
// submission.
return allowPageToSubmitForm;
}
export function setQueryValue(queryString: string): void {
yasqe.setValue(queryString.trim());
}
export function getQueryValue(): string {
return yasqe.getValue().trim();
}
export function getYasqe(): YASQE_Instance {
return yasqe;
}
export function updateYasqe() {
if ($("#queryLn").val() == "SPARQL") {
initYasqe();
} else {
closeYasqe();
}
}
function initYasqe() {
workbench.yasqeHelper.setupCompleters(sparqlNamespaces);
yasqe = YASQE.fromTextArea(<HTMLTextAreaElement>document.getElementById('query'), {
consumeShareLink: null//don't try to parse the url args. this is already done by the addLoad function below
});
//some styling conflicts. Could add my own css file, but not a lot of things need changing, so just do this programmatically
//first, set the font size (otherwise font is as small as menu, which is too small)
//second, set the width. YASQE normally expands to 100%, but the use of a table requires us to set a fixed width
$(yasqe.getWrapperElement()).css({"fontSize": "14px", "width": "900px"});
//we made a change to the css wrapper element (and did so after initialization). So, force a manual update of the yasqe instance
yasqe.refresh();
}
function closeYasqe() {
if (yasqe) {
//store yasqe value in text area (not sure whether this is desired, but it mimics current behavior)
//it closes the yasqe instance as well
yasqe.toTextArea();
yasqe = null;
}
}
}
}
interface QueryTextResponse {
queryText: string;
}
workbench.addLoad(function queryPageLoaded() {
/**
* Gets a parameter from the URL or the cookies, preferentially in that
* order.
*
* @param param
* the name of the parameter
* @returns the value of the given parameter, or something that evaluates
as false, if the parameter was not found
*/
function getParameterFromUrlOrCookie(param: string) {
var href = document.location.href;
var elements = href.substring(href.indexOf('?') + 1).substring(
href.indexOf(';') + 1).split(decodeURIComponent('%26'));
var result = '';
for (var i = 0; elements.length - i; i++) {
var pair = elements[i].split('=');
var value = decodeURIComponent(pair[1]).replace(/\+/g, ' ');
if (pair[0] == param) {
result = value;
}
}
if (!result) {
result = workbench.getCookie(param);
}
return result;
}
function getQueryTextFromServer(queryParam: string, refParam: string) {
$.getJSON('query', {
action: "get",
query: queryParam,
ref: refParam
}, function(response: QueryTextResponse) {
if (response.queryText) {
workbench.query.setQueryValue(response.queryText);
}
});
}
//Start with initializing our YASQE instance, given that 'SPARQL' is the selected query language
//(all the following 'set' and 'get' SPARQL query functions require an instantiated yasqe instance
workbench.query.updateYasqe();
// Populate the query text area with the value of the URL query parameter,
// only if it is present. If it is not present in the URL query, then
// looks for the 'query' cookie, and sets it from that. (The cookie
// enables re-populating the text field with the previous query when the
// user returns via the browser back button.)
var query = getParameterFromUrlOrCookie('query');
if (query) {
var ref = getParameterFromUrlOrCookie('ref');
if (ref == 'id' || ref == 'hash') {
getQueryTextFromServer(query, ref);
} else {
workbench.query.setQueryValue(query);
}
}
workbench.query.loadNamespaces();
// Trim the query text area contents of any leading and/or trailing
// whitespace.
workbench.query.setQueryValue($.trim(workbench.query.getQueryValue()));
// Add click handlers identifying the clicked element in a hidden 'action'
// form field.
var addHandler = function(id: string) {
$('#' + id).click(function setAction() { $('#action').val(id); });
};
addHandler('exec');
addHandler('save');
// Add event handlers to the save name field to react to changes in it.
$('#query-name').bind('keydown cut paste', workbench.query.handleNameChange);
// Add event handlers to the query text area to react to changes in it.
$('#query').bind('keydown cut paste', workbench.query.clearFeedback);
if (workbench.query.getYasqe()) {
workbench.query.getYasqe().on('change',
workbench.query.clearFeedback);
}
// Detect if there is no current authenticated user, and if so, disable
// the 'save privately' option.
if ($('#selected-user>span').is('.disabled')) {
$('#save-private').prop('checked', false).prop('disabled', true);
}
}); | the_stack |
// Transaction
// -------
import { EventEmitter } from './deps/@jspm/core@1.1.0/nodelibs/events.js';
import Debug from './deps/debug@4.1.1/src/index.js';
import makeKnex from './util/make-knex.js';
import { callbackify } from './deps/@jspm/core@1.1.0/nodelibs/util.js';
import { timeout, KnexTimeoutError } from './util/timeout.js';
import finallyMixin from './util/finally-mixin.js';
const debug = Debug('knex:tx');
import _ from './deps/lodash@4.17.15/index.js';
const uniqueId = _.uniqueId;
// FYI: This is defined as a function instead of a constant so that
// each Transactor can have its own copy of the default config.
// This will minimize the impact of bugs that might be introduced
// if a Transactor ever mutates its config.
function DEFAULT_CONFIG() {
return {
userParams: {},
doNotRejectOnRollback: true,
};
}
// Acts as a facade for a Promise, keeping the internal state
// and managing any child transactions.
class Transaction extends EventEmitter {
constructor(client, container, config = DEFAULT_CONFIG(), outerTx = null) {
super();
this.userParams = config.userParams;
this.doNotRejectOnRollback = config.doNotRejectOnRollback;
const txid = (this.txid = uniqueId('trx'));
this.client = client;
this.logger = client.logger;
this.outerTx = outerTx;
this.trxClient = undefined;
this._completed = false;
this._debug = client.config && client.config.debug;
debug(
'%s: Starting %s transaction',
txid,
outerTx ? 'nested' : 'top level'
);
// `this` can potentially serve as an `outerTx` for another
// Transaction. So, go ahead and establish `_lastChild` now.
this._lastChild = Promise.resolve();
const _previousSibling = outerTx ? outerTx._lastChild : Promise.resolve();
// FYI: As you will see in a moment, this Promise will be used to construct
// 2 separate Promise Chains. This ensures that each Promise Chain
// can establish its error-handling semantics without interfering
// with the other Promise Chain.
const basePromise = _previousSibling.then(() =>
this._evaluateContainer(config, container)
);
// FYI: This is the Promise Chain for EXTERNAL use. It ensures that the
// caller must handle any exceptions that result from `basePromise`.
this._promise = basePromise.then((x) => x);
if (outerTx) {
// FYI: This is the Promise Chain for INTERNAL use. It serves as a signal
// for when the next sibling should begin its execution. Therefore,
// exceptions are caught and ignored.
outerTx._lastChild = basePromise.catch(() => {});
}
}
isCompleted() {
return (
this._completed || (this.outerTx && this.outerTx.isCompleted()) || false
);
}
begin(conn) {
return this.query(conn, 'BEGIN;');
}
savepoint(conn) {
return this.query(conn, `SAVEPOINT ${this.txid};`);
}
commit(conn, value) {
return this.query(conn, 'COMMIT;', 1, value);
}
release(conn, value) {
return this.query(conn, `RELEASE SAVEPOINT ${this.txid};`, 1, value);
}
rollback(conn, error) {
return timeout(this.query(conn, 'ROLLBACK', 2, error), 5000).catch(
(err) => {
if (!(err instanceof KnexTimeoutError)) {
return Promise.reject(err);
}
this._rejecter(error);
}
);
}
rollbackTo(conn, error) {
return timeout(
this.query(conn, `ROLLBACK TO SAVEPOINT ${this.txid}`, 2, error),
5000
).catch((err) => {
if (!(err instanceof KnexTimeoutError)) {
return Promise.reject(err);
}
this._rejecter(error);
});
}
query(conn, sql, status, value) {
const q = this.trxClient
.query(conn, sql)
.catch((err) => {
status = 2;
value = err;
this._completed = true;
debug('%s error running transaction query', this.txid);
})
.then((res) => {
if (status === 1) {
this._resolver(value);
}
if (status === 2) {
if (value === undefined) {
if (this.doNotRejectOnRollback && /^ROLLBACK\b/i.test(sql)) {
this._resolver();
return;
}
value = new Error(`Transaction rejected with non-error: ${value}`);
}
this._rejecter(value);
}
return res;
});
if (status === 1 || status === 2) {
this._completed = true;
}
return q;
}
debug(enabled) {
this._debug = arguments.length ? enabled : true;
return this;
}
async _evaluateContainer(config, container) {
return this.acquireConnection(config, (connection) => {
const trxClient = (this.trxClient = makeTxClient(
this,
this.client,
connection
));
const init = this.client.transacting
? this.savepoint(connection)
: this.begin(connection);
const executionPromise = new Promise((resolver, rejecter) => {
this._resolver = resolver;
this._rejecter = rejecter;
});
init
.then(() => {
return makeTransactor(this, connection, trxClient);
})
.then((transactor) => {
transactor.executionPromise = executionPromise;
// If we've returned a "thenable" from the transaction container, assume
// the rollback and commit are chained to this object's success / failure.
// Directly thrown errors are treated as automatic rollbacks.
let result;
try {
result = container(transactor);
} catch (err) {
result = Promise.reject(err);
}
if (result && result.then && typeof result.then === 'function') {
result
.then((val) => {
return transactor.commit(val);
})
.catch((err) => {
return transactor.rollback(err);
});
}
return null;
})
.catch((e) => {
return this._rejecter(e);
});
return executionPromise;
});
}
// Acquire a connection and create a disposer - either using the one passed
// via config or getting one off the client. The disposer will be called once
// the original promise is marked completed.
async acquireConnection(config, cb) {
const configConnection = config && config.connection;
const connection =
configConnection || (await this.client.acquireConnection());
try {
connection.__knexTxId = this.txid;
return await cb(connection);
} finally {
if (!configConnection) {
debug('%s: releasing connection', this.txid);
this.client.releaseConnection(connection);
} else {
debug('%s: not releasing external connection', this.txid);
}
}
}
then(onResolve, onReject) {
return this._promise.then(onResolve, onReject);
}
catch(onReject) {
return this._promise.catch(onReject);
}
asCallback(cb) {
callbackify(() => this._promise)(cb);
return this._promise;
}
}
finallyMixin(Transaction.prototype);
// The transactor is a full featured knex object, with a "commit", a "rollback"
// and a "savepoint" function. The "savepoint" is just sugar for creating a new
// transaction. If the rollback is run inside a savepoint, it rolls back to the
// last savepoint - otherwise it rolls back the transaction.
function makeTransactor(trx, connection, trxClient) {
const transactor = makeKnex(trxClient);
transactor.context.withUserParams = () => {
throw new Error(
'Cannot set user params on a transaction - it can only inherit params from main knex instance'
);
};
transactor.isTransaction = true;
transactor.userParams = trx.userParams || {};
transactor.context.transaction = function (container, options) {
if (!options) {
options = { doNotRejectOnRollback: true };
} else if (options.doNotRejectOnRollback === undefined) {
options.doNotRejectOnRollback = true;
}
return this._transaction(container, options, trx);
};
transactor.savepoint = function (container, options) {
return transactor.transaction(container, options);
};
if (trx.client.transacting) {
transactor.commit = (value) => trx.release(connection, value);
transactor.rollback = (error) => trx.rollbackTo(connection, error);
} else {
transactor.commit = (value) => trx.commit(connection, value);
transactor.rollback = (error) => trx.rollback(connection, error);
}
transactor.isCompleted = () => trx.isCompleted();
return transactor;
}
// We need to make a client object which always acquires the same
// connection and does not release back into the pool.
function makeTxClient(trx, client, connection) {
const trxClient = Object.create(client.constructor.prototype);
trxClient.version = client.version;
trxClient.config = client.config;
trxClient.driver = client.driver;
trxClient.connectionSettings = client.connectionSettings;
trxClient.transacting = true;
trxClient.valueForUndefined = client.valueForUndefined;
trxClient.logger = client.logger;
trxClient.on('query', function (arg) {
trx.emit('query', arg);
client.emit('query', arg);
});
trxClient.on('query-error', function (err, obj) {
trx.emit('query-error', err, obj);
client.emit('query-error', err, obj);
});
trxClient.on('query-response', function (response, obj, builder) {
trx.emit('query-response', response, obj, builder);
client.emit('query-response', response, obj, builder);
});
const _query = trxClient.query;
trxClient.query = function (conn, obj) {
const completed = trx.isCompleted();
return new Promise(function (resolve, reject) {
try {
if (conn !== connection)
throw new Error('Invalid connection for transaction query.');
if (completed) completedError(trx, obj);
resolve(_query.call(trxClient, conn, obj));
} catch (e) {
reject(e);
}
});
};
const _stream = trxClient.stream;
trxClient.stream = function (conn, obj, stream, options) {
const completed = trx.isCompleted();
return new Promise(function (resolve, reject) {
try {
if (conn !== connection)
throw new Error('Invalid connection for transaction query.');
if (completed) completedError(trx, obj);
resolve(_stream.call(trxClient, conn, obj, stream, options));
} catch (e) {
reject(e);
}
});
};
trxClient.acquireConnection = function () {
return Promise.resolve(connection);
};
trxClient.releaseConnection = function () {
return Promise.resolve();
};
return trxClient;
}
function completedError(trx, obj) {
const sql = typeof obj === 'string' ? obj : obj && obj.sql;
debug('%s: Transaction completed: %s', trx.txid, sql);
throw new Error(
'Transaction query already complete, run with DEBUG=knex:tx for more info'
);
}
export default Transaction; | the_stack |
import { URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import * as errors from 'vs/base/common/errors';
import { Disposable, IDisposable, dispose, toDisposable, MutableDisposable, combinedDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { RunOnceScheduler } from 'vs/base/common/async';
import { FileChangeType, FileChangesEvent, IFileService, whenProviderRegistered, FileOperationError, FileOperationResult, FileOperation, FileOperationEvent } from 'vs/platform/files/common/files';
import { ConfigurationModel, ConfigurationModelParser, ConfigurationParseOptions, UserSettings } from 'vs/platform/configuration/common/configurationModels';
import { WorkspaceConfigurationModelParser, StandaloneConfigurationModelParser } from 'vs/workbench/services/configuration/common/configurationModels';
import { TASKS_CONFIGURATION_KEY, FOLDER_SETTINGS_NAME, LAUNCH_CONFIGURATION_KEY, IConfigurationCache, ConfigurationKey, REMOTE_MACHINE_SCOPES, FOLDER_SCOPES, WORKSPACE_SCOPES } from 'vs/workbench/services/configuration/common/configuration';
import { IStoredWorkspaceFolder } from 'vs/platform/workspaces/common/workspaces';
import { JSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditingService';
import { WorkbenchState, IWorkspaceFolder, IWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace';
import { ConfigurationScope, Extensions, IConfigurationRegistry, OVERRIDE_PROPERTY_REGEX } from 'vs/platform/configuration/common/configurationRegistry';
import { equals } from 'vs/base/common/objects';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { hash } from 'vs/base/common/hash';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { ILogService } from 'vs/platform/log/common/log';
import { IStringDictionary } from 'vs/base/common/collections';
import { joinPath } from 'vs/base/common/resources';
import { Registry } from 'vs/platform/registry/common/platform';
import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService';
import { isObject } from 'vs/base/common/types';
import { IUserDataProfile } from 'vs/platform/userDataProfile/common/userDataProfile';
import { DefaultConfiguration as BaseDefaultConfiguration } from 'vs/platform/configuration/common/configurations';
export class DefaultConfiguration extends BaseDefaultConfiguration {
static readonly DEFAULT_OVERRIDES_CACHE_EXISTS_KEY = 'DefaultOverridesCacheExists';
private readonly configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
private cachedConfigurationDefaultsOverrides: IStringDictionary<any> = {};
private readonly cacheKey: ConfigurationKey = { type: 'defaults', key: 'configurationDefaultsOverrides' };
private updateCache: boolean = false;
constructor(
private readonly configurationCache: IConfigurationCache,
environmentService: IBrowserWorkbenchEnvironmentService,
) {
super();
if (environmentService.options?.configurationDefaults) {
this.configurationRegistry.registerDefaultConfigurations([{ overrides: environmentService.options.configurationDefaults }]);
}
}
protected override getConfigurationDefaultOverrides(): IStringDictionary<any> {
return this.cachedConfigurationDefaultsOverrides;
}
override async initialize(): Promise<ConfigurationModel> {
await this.initializeCachedConfigurationDefaultsOverrides();
return super.initialize();
}
override reload(): ConfigurationModel {
this.updateCache = true;
this.cachedConfigurationDefaultsOverrides = {};
this.updateCachedConfigurationDefaultsOverrides();
return super.reload();
}
private initiaizeCachedConfigurationDefaultsOverridesPromise: Promise<void> | undefined;
private initializeCachedConfigurationDefaultsOverrides(): Promise<void> {
if (!this.initiaizeCachedConfigurationDefaultsOverridesPromise) {
this.initiaizeCachedConfigurationDefaultsOverridesPromise = (async () => {
try {
// Read only when the cache exists
if (window.localStorage.getItem(DefaultConfiguration.DEFAULT_OVERRIDES_CACHE_EXISTS_KEY)) {
const content = await this.configurationCache.read(this.cacheKey);
if (content) {
this.cachedConfigurationDefaultsOverrides = JSON.parse(content);
}
}
} catch (error) { /* ignore */ }
this.cachedConfigurationDefaultsOverrides = isObject(this.cachedConfigurationDefaultsOverrides) ? this.cachedConfigurationDefaultsOverrides : {};
})();
}
return this.initiaizeCachedConfigurationDefaultsOverridesPromise;
}
protected override onDidUpdateConfiguration(properties: string[], defaultsOverrides?: boolean): void {
super.onDidUpdateConfiguration(properties, defaultsOverrides);
if (defaultsOverrides) {
this.updateCachedConfigurationDefaultsOverrides();
}
}
private async updateCachedConfigurationDefaultsOverrides(): Promise<void> {
if (!this.updateCache) {
return;
}
const cachedConfigurationDefaultsOverrides: IStringDictionary<any> = {};
const configurationDefaultsOverrides = this.configurationRegistry.getConfigurationDefaultsOverrides();
for (const [key, value] of configurationDefaultsOverrides) {
if (!OVERRIDE_PROPERTY_REGEX.test(key) && value.value !== undefined) {
cachedConfigurationDefaultsOverrides[key] = value.value;
}
}
try {
if (Object.keys(cachedConfigurationDefaultsOverrides).length) {
window.localStorage.setItem(DefaultConfiguration.DEFAULT_OVERRIDES_CACHE_EXISTS_KEY, 'yes');
await this.configurationCache.write(this.cacheKey, JSON.stringify(cachedConfigurationDefaultsOverrides));
} else {
window.localStorage.removeItem(DefaultConfiguration.DEFAULT_OVERRIDES_CACHE_EXISTS_KEY);
await this.configurationCache.remove(this.cacheKey);
}
} catch (error) {/* Ignore error */ }
}
}
export class UserConfiguration extends Disposable {
private readonly _onDidChangeConfiguration: Emitter<ConfigurationModel> = this._register(new Emitter<ConfigurationModel>());
readonly onDidChangeConfiguration: Event<ConfigurationModel> = this._onDidChangeConfiguration.event;
private readonly userConfiguration: MutableDisposable<UserSettings | FileServiceBasedConfiguration> = this._register(new MutableDisposable<UserSettings | FileServiceBasedConfiguration>());
private readonly reloadConfigurationScheduler: RunOnceScheduler;
private readonly configurationParseOptions: ConfigurationParseOptions;
get hasTasksLoaded(): boolean { return this.userConfiguration.value instanceof FileServiceBasedConfiguration; }
constructor(
private readonly userDataProfile: IUserDataProfile,
scopes: ConfigurationScope[] | undefined,
private readonly fileService: IFileService,
private readonly uriIdentityService: IUriIdentityService,
private readonly logService: ILogService,
) {
super();
this.configurationParseOptions = { scopes, skipRestricted: false };
this.userConfiguration.value = new UserSettings(this.userDataProfile.settingsResource, scopes, uriIdentityService.extUri, this.fileService);
this._register(this.userConfiguration.value.onDidChange(() => this.reloadConfigurationScheduler.schedule()));
this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.reload().then(configurationModel => this._onDidChangeConfiguration.fire(configurationModel)), 50));
}
async initialize(): Promise<ConfigurationModel> {
return this.userConfiguration.value!.loadConfiguration();
}
async reload(): Promise<ConfigurationModel> {
if (this.hasTasksLoaded) {
return this.userConfiguration.value!.loadConfiguration();
}
const folder = this.uriIdentityService.extUri.dirname(this.userDataProfile.settingsResource);
const standAloneConfigurationResources: [string, URI][] = [[TASKS_CONFIGURATION_KEY, this.userDataProfile.tasksResource]];
const fileServiceBasedConfiguration = new FileServiceBasedConfiguration(folder.toString(), this.userDataProfile.settingsResource, standAloneConfigurationResources, this.configurationParseOptions, this.fileService, this.uriIdentityService, this.logService);
const configurationModel = await fileServiceBasedConfiguration.loadConfiguration();
this.userConfiguration.value = fileServiceBasedConfiguration;
// Check for value because userConfiguration might have been disposed.
if (this.userConfiguration.value) {
this._register(this.userConfiguration.value.onDidChange(() => this.reloadConfigurationScheduler.schedule()));
}
return configurationModel;
}
reparse(): ConfigurationModel {
return this.userConfiguration.value!.reparse(this.configurationParseOptions);
}
getRestrictedSettings(): string[] {
return this.userConfiguration.value!.getRestrictedSettings();
}
}
class FileServiceBasedConfiguration extends Disposable {
private readonly allResources: URI[];
private _folderSettingsModelParser: ConfigurationModelParser;
private _folderSettingsParseOptions: ConfigurationParseOptions;
private _standAloneConfigurations: ConfigurationModel[];
private _cache: ConfigurationModel;
private readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
constructor(
name: string,
private readonly settingsResource: URI,
private readonly standAloneConfigurationResources: [string, URI][],
configurationParseOptions: ConfigurationParseOptions,
private readonly fileService: IFileService,
private readonly uriIdentityService: IUriIdentityService,
private readonly logService: ILogService,
) {
super();
this.allResources = [this.settingsResource, ...this.standAloneConfigurationResources.map(([, resource]) => resource)];
this._register(combinedDisposable(...this.allResources.map(resource => combinedDisposable(
this.fileService.watch(uriIdentityService.extUri.dirname(resource)),
// Also listen to the resource incase the resource is a symlink - https://github.com/microsoft/vscode/issues/118134
this.fileService.watch(resource)
))));
this._folderSettingsModelParser = new ConfigurationModelParser(name);
this._folderSettingsParseOptions = configurationParseOptions;
this._standAloneConfigurations = [];
this._cache = new ConfigurationModel();
this._register(Event.debounce(
Event.any(
Event.filter(this.fileService.onDidFilesChange, e => this.handleFileChangesEvent(e)),
Event.filter(this.fileService.onDidRunOperation, e => this.handleFileOperationEvent(e))
), () => undefined, 100)(() => this._onDidChange.fire()));
}
async resolveContents(): Promise<[string | undefined, [string, string | undefined][]]> {
const resolveContents = async (resources: URI[]): Promise<(string | undefined)[]> => {
return Promise.all(resources.map(async resource => {
try {
const content = (await this.fileService.readFile(resource)).value.toString();
return content;
} catch (error) {
this.logService.trace(`Error while resolving configuration file '${resource.toString()}': ${errors.getErrorMessage(error)}`);
if ((<FileOperationError>error).fileOperationResult !== FileOperationResult.FILE_NOT_FOUND
&& (<FileOperationError>error).fileOperationResult !== FileOperationResult.FILE_NOT_DIRECTORY) {
this.logService.error(error);
}
}
return '{}';
}));
};
const [[settingsContent], standAloneConfigurationContents] = await Promise.all([
resolveContents([this.settingsResource]),
resolveContents(this.standAloneConfigurationResources.map(([, resource]) => resource)),
]);
return [settingsContent, standAloneConfigurationContents.map((content, index) => ([this.standAloneConfigurationResources[index][0], content]))];
}
async loadConfiguration(): Promise<ConfigurationModel> {
const [settingsContent, standAloneConfigurationContents] = await this.resolveContents();
// reset
this._standAloneConfigurations = [];
this._folderSettingsModelParser.parse('', this._folderSettingsParseOptions);
// parse
if (settingsContent !== undefined) {
this._folderSettingsModelParser.parse(settingsContent, this._folderSettingsParseOptions);
}
for (let index = 0; index < standAloneConfigurationContents.length; index++) {
const contents = standAloneConfigurationContents[index][1];
if (contents !== undefined) {
const standAloneConfigurationModelParser = new StandaloneConfigurationModelParser(this.standAloneConfigurationResources[index][1].toString(), this.standAloneConfigurationResources[index][0]);
standAloneConfigurationModelParser.parse(contents);
this._standAloneConfigurations.push(standAloneConfigurationModelParser.configurationModel);
}
}
// Consolidate (support *.json files in the workspace settings folder)
this.consolidate();
return this._cache;
}
getRestrictedSettings(): string[] {
return this._folderSettingsModelParser.restrictedConfigurations;
}
reparse(configurationParseOptions: ConfigurationParseOptions): ConfigurationModel {
const oldContents = this._folderSettingsModelParser.configurationModel.contents;
this._folderSettingsParseOptions = configurationParseOptions;
this._folderSettingsModelParser.reparse(this._folderSettingsParseOptions);
if (!equals(oldContents, this._folderSettingsModelParser.configurationModel.contents)) {
this.consolidate();
}
return this._cache;
}
private consolidate(): void {
this._cache = this._folderSettingsModelParser.configurationModel.merge(...this._standAloneConfigurations);
}
private handleFileChangesEvent(event: FileChangesEvent): boolean {
// One of the resources has changed
if (this.allResources.some(resource => event.contains(resource))) {
return true;
}
// One of the resource's parent got deleted
if (this.allResources.some(resource => event.contains(this.uriIdentityService.extUri.dirname(resource), FileChangeType.DELETED))) {
return true;
}
return false;
}
private handleFileOperationEvent(event: FileOperationEvent): boolean {
// One of the resources has changed
if ((event.isOperation(FileOperation.CREATE) || event.isOperation(FileOperation.COPY) || event.isOperation(FileOperation.DELETE) || event.isOperation(FileOperation.WRITE))
&& this.allResources.some(resource => this.uriIdentityService.extUri.isEqual(event.resource, resource))) {
return true;
}
// One of the resource's parent got deleted
if (event.isOperation(FileOperation.DELETE) && this.allResources.some(resource => this.uriIdentityService.extUri.isEqual(event.resource, this.uriIdentityService.extUri.dirname(resource)))) {
return true;
}
return false;
}
}
export class RemoteUserConfiguration extends Disposable {
private readonly _cachedConfiguration: CachedRemoteUserConfiguration;
private readonly _fileService: IFileService;
private _userConfiguration: FileServiceBasedRemoteUserConfiguration | CachedRemoteUserConfiguration;
private _userConfigurationInitializationPromise: Promise<ConfigurationModel> | null = null;
private readonly _onDidChangeConfiguration: Emitter<ConfigurationModel> = this._register(new Emitter<ConfigurationModel>());
public readonly onDidChangeConfiguration: Event<ConfigurationModel> = this._onDidChangeConfiguration.event;
private readonly _onDidInitialize = this._register(new Emitter<ConfigurationModel>());
public readonly onDidInitialize = this._onDidInitialize.event;
constructor(
remoteAuthority: string,
configurationCache: IConfigurationCache,
fileService: IFileService,
uriIdentityService: IUriIdentityService,
remoteAgentService: IRemoteAgentService
) {
super();
this._fileService = fileService;
this._userConfiguration = this._cachedConfiguration = new CachedRemoteUserConfiguration(remoteAuthority, configurationCache, { scopes: REMOTE_MACHINE_SCOPES });
remoteAgentService.getEnvironment().then(async environment => {
if (environment) {
const userConfiguration = this._register(new FileServiceBasedRemoteUserConfiguration(environment.settingsPath, { scopes: REMOTE_MACHINE_SCOPES }, this._fileService, uriIdentityService));
this._register(userConfiguration.onDidChangeConfiguration(configurationModel => this.onDidUserConfigurationChange(configurationModel)));
this._userConfigurationInitializationPromise = userConfiguration.initialize();
const configurationModel = await this._userConfigurationInitializationPromise;
this._userConfiguration.dispose();
this._userConfiguration = userConfiguration;
this.onDidUserConfigurationChange(configurationModel);
this._onDidInitialize.fire(configurationModel);
}
});
}
async initialize(): Promise<ConfigurationModel> {
if (this._userConfiguration instanceof FileServiceBasedRemoteUserConfiguration) {
return this._userConfiguration.initialize();
}
// Initialize cached configuration
let configurationModel = await this._userConfiguration.initialize();
if (this._userConfigurationInitializationPromise) {
// Use user configuration
configurationModel = await this._userConfigurationInitializationPromise;
this._userConfigurationInitializationPromise = null;
}
return configurationModel;
}
reload(): Promise<ConfigurationModel> {
return this._userConfiguration.reload();
}
reparse(): ConfigurationModel {
return this._userConfiguration.reparse({ scopes: REMOTE_MACHINE_SCOPES });
}
getRestrictedSettings(): string[] {
return this._userConfiguration.getRestrictedSettings();
}
private onDidUserConfigurationChange(configurationModel: ConfigurationModel): void {
this.updateCache();
this._onDidChangeConfiguration.fire(configurationModel);
}
private async updateCache(): Promise<void> {
if (this._userConfiguration instanceof FileServiceBasedRemoteUserConfiguration) {
let content: string | undefined;
try {
content = await this._userConfiguration.resolveContent();
} catch (error) {
if ((<FileOperationError>error).fileOperationResult !== FileOperationResult.FILE_NOT_FOUND) {
return;
}
}
await this._cachedConfiguration.updateConfiguration(content);
}
}
}
class FileServiceBasedRemoteUserConfiguration extends Disposable {
private readonly parser: ConfigurationModelParser;
private parseOptions: ConfigurationParseOptions;
private readonly reloadConfigurationScheduler: RunOnceScheduler;
protected readonly _onDidChangeConfiguration: Emitter<ConfigurationModel> = this._register(new Emitter<ConfigurationModel>());
readonly onDidChangeConfiguration: Event<ConfigurationModel> = this._onDidChangeConfiguration.event;
private fileWatcherDisposable: IDisposable = Disposable.None;
private directoryWatcherDisposable: IDisposable = Disposable.None;
constructor(
private readonly configurationResource: URI,
configurationParseOptions: ConfigurationParseOptions,
private readonly fileService: IFileService,
private readonly uriIdentityService: IUriIdentityService,
) {
super();
this.parser = new ConfigurationModelParser(this.configurationResource.toString());
this.parseOptions = configurationParseOptions;
this._register(fileService.onDidFilesChange(e => this.handleFileChangesEvent(e)));
this._register(fileService.onDidRunOperation(e => this.handleFileOperationEvent(e)));
this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.reload().then(configurationModel => this._onDidChangeConfiguration.fire(configurationModel)), 50));
this._register(toDisposable(() => {
this.stopWatchingResource();
this.stopWatchingDirectory();
}));
}
private watchResource(): void {
this.fileWatcherDisposable = this.fileService.watch(this.configurationResource);
}
private stopWatchingResource(): void {
this.fileWatcherDisposable.dispose();
this.fileWatcherDisposable = Disposable.None;
}
private watchDirectory(): void {
const directory = this.uriIdentityService.extUri.dirname(this.configurationResource);
this.directoryWatcherDisposable = this.fileService.watch(directory);
}
private stopWatchingDirectory(): void {
this.directoryWatcherDisposable.dispose();
this.directoryWatcherDisposable = Disposable.None;
}
async initialize(): Promise<ConfigurationModel> {
const exists = await this.fileService.exists(this.configurationResource);
this.onResourceExists(exists);
return this.reload();
}
async resolveContent(): Promise<string> {
const content = await this.fileService.readFile(this.configurationResource);
return content.value.toString();
}
async reload(): Promise<ConfigurationModel> {
try {
const content = await this.resolveContent();
this.parser.parse(content, this.parseOptions);
return this.parser.configurationModel;
} catch (e) {
return new ConfigurationModel();
}
}
reparse(configurationParseOptions: ConfigurationParseOptions): ConfigurationModel {
this.parseOptions = configurationParseOptions;
this.parser.reparse(this.parseOptions);
return this.parser.configurationModel;
}
getRestrictedSettings(): string[] {
return this.parser.restrictedConfigurations;
}
private handleFileChangesEvent(event: FileChangesEvent): void {
// Find changes that affect the resource
let affectedByChanges = event.contains(this.configurationResource, FileChangeType.UPDATED);
if (event.contains(this.configurationResource, FileChangeType.ADDED)) {
affectedByChanges = true;
this.onResourceExists(true);
} else if (event.contains(this.configurationResource, FileChangeType.DELETED)) {
affectedByChanges = true;
this.onResourceExists(false);
}
if (affectedByChanges) {
this.reloadConfigurationScheduler.schedule();
}
}
private handleFileOperationEvent(event: FileOperationEvent): void {
if ((event.isOperation(FileOperation.CREATE) || event.isOperation(FileOperation.COPY) || event.isOperation(FileOperation.DELETE) || event.isOperation(FileOperation.WRITE))
&& this.uriIdentityService.extUri.isEqual(event.resource, this.configurationResource)) {
this.reloadConfigurationScheduler.schedule();
}
}
private onResourceExists(exists: boolean): void {
if (exists) {
this.stopWatchingDirectory();
this.watchResource();
} else {
this.stopWatchingResource();
this.watchDirectory();
}
}
}
class CachedRemoteUserConfiguration extends Disposable {
private readonly _onDidChange: Emitter<ConfigurationModel> = this._register(new Emitter<ConfigurationModel>());
readonly onDidChange: Event<ConfigurationModel> = this._onDidChange.event;
private readonly key: ConfigurationKey;
private readonly parser: ConfigurationModelParser;
private parseOptions: ConfigurationParseOptions;
private configurationModel: ConfigurationModel;
constructor(
remoteAuthority: string,
private readonly configurationCache: IConfigurationCache,
configurationParseOptions: ConfigurationParseOptions,
) {
super();
this.key = { type: 'user', key: remoteAuthority };
this.parser = new ConfigurationModelParser('CachedRemoteUserConfiguration');
this.parseOptions = configurationParseOptions;
this.configurationModel = new ConfigurationModel();
}
getConfigurationModel(): ConfigurationModel {
return this.configurationModel;
}
initialize(): Promise<ConfigurationModel> {
return this.reload();
}
reparse(configurationParseOptions: ConfigurationParseOptions): ConfigurationModel {
this.parseOptions = configurationParseOptions;
this.parser.reparse(this.parseOptions);
this.configurationModel = this.parser.configurationModel;
return this.configurationModel;
}
getRestrictedSettings(): string[] {
return this.parser.restrictedConfigurations;
}
async reload(): Promise<ConfigurationModel> {
try {
const content = await this.configurationCache.read(this.key);
const parsed: { content: string } = JSON.parse(content);
if (parsed.content) {
this.parser.parse(parsed.content, this.parseOptions);
this.configurationModel = this.parser.configurationModel;
}
} catch (e) { /* Ignore error */ }
return this.configurationModel;
}
async updateConfiguration(content: string | undefined): Promise<void> {
if (content) {
return this.configurationCache.write(this.key, JSON.stringify({ content }));
} else {
return this.configurationCache.remove(this.key);
}
}
}
export class WorkspaceConfiguration extends Disposable {
private readonly _cachedConfiguration: CachedWorkspaceConfiguration;
private _workspaceConfiguration: CachedWorkspaceConfiguration | FileServiceBasedWorkspaceConfiguration;
private _workspaceConfigurationDisposables = this._register(new DisposableStore());
private _workspaceIdentifier: IWorkspaceIdentifier | null = null;
private _isWorkspaceTrusted: boolean = false;
private readonly _onDidUpdateConfiguration = this._register(new Emitter<boolean>());
public readonly onDidUpdateConfiguration = this._onDidUpdateConfiguration.event;
private _initialized: boolean = false;
get initialized(): boolean { return this._initialized; }
constructor(
private readonly configurationCache: IConfigurationCache,
private readonly fileService: IFileService,
private readonly uriIdentityService: IUriIdentityService,
private readonly logService: ILogService,
) {
super();
this.fileService = fileService;
this._workspaceConfiguration = this._cachedConfiguration = new CachedWorkspaceConfiguration(configurationCache);
}
async initialize(workspaceIdentifier: IWorkspaceIdentifier, workspaceTrusted: boolean): Promise<void> {
this._workspaceIdentifier = workspaceIdentifier;
this._isWorkspaceTrusted = workspaceTrusted;
if (!this._initialized) {
if (this.configurationCache.needsCaching(this._workspaceIdentifier.configPath)) {
this._workspaceConfiguration = this._cachedConfiguration;
this.waitAndInitialize(this._workspaceIdentifier);
} else {
this.doInitialize(new FileServiceBasedWorkspaceConfiguration(this.fileService, this.uriIdentityService, this.logService));
}
}
await this.reload();
}
async reload(): Promise<void> {
if (this._workspaceIdentifier) {
await this._workspaceConfiguration.load(this._workspaceIdentifier, { scopes: WORKSPACE_SCOPES, skipRestricted: this.isUntrusted() });
}
}
getFolders(): IStoredWorkspaceFolder[] {
return this._workspaceConfiguration.getFolders();
}
setFolders(folders: IStoredWorkspaceFolder[], jsonEditingService: JSONEditingService): Promise<void> {
if (this._workspaceIdentifier) {
return jsonEditingService.write(this._workspaceIdentifier.configPath, [{ path: ['folders'], value: folders }], true)
.then(() => this.reload());
}
return Promise.resolve();
}
isTransient(): boolean {
return this._workspaceConfiguration.isTransient();
}
getConfiguration(): ConfigurationModel {
return this._workspaceConfiguration.getWorkspaceSettings();
}
updateWorkspaceTrust(trusted: boolean): ConfigurationModel {
this._isWorkspaceTrusted = trusted;
return this.reparseWorkspaceSettings();
}
reparseWorkspaceSettings(): ConfigurationModel {
this._workspaceConfiguration.reparseWorkspaceSettings({ scopes: WORKSPACE_SCOPES, skipRestricted: this.isUntrusted() });
return this.getConfiguration();
}
getRestrictedSettings(): string[] {
return this._workspaceConfiguration.getRestrictedSettings();
}
private async waitAndInitialize(workspaceIdentifier: IWorkspaceIdentifier): Promise<void> {
await whenProviderRegistered(workspaceIdentifier.configPath, this.fileService);
if (!(this._workspaceConfiguration instanceof FileServiceBasedWorkspaceConfiguration)) {
const fileServiceBasedWorkspaceConfiguration = this._register(new FileServiceBasedWorkspaceConfiguration(this.fileService, this.uriIdentityService, this.logService));
await fileServiceBasedWorkspaceConfiguration.load(workspaceIdentifier, { scopes: WORKSPACE_SCOPES, skipRestricted: this.isUntrusted() });
this.doInitialize(fileServiceBasedWorkspaceConfiguration);
this.onDidWorkspaceConfigurationChange(false, true);
}
}
private doInitialize(fileServiceBasedWorkspaceConfiguration: FileServiceBasedWorkspaceConfiguration): void {
this._workspaceConfigurationDisposables.clear();
this._workspaceConfiguration = this._workspaceConfigurationDisposables.add(fileServiceBasedWorkspaceConfiguration);
this._workspaceConfigurationDisposables.add(this._workspaceConfiguration.onDidChange(e => this.onDidWorkspaceConfigurationChange(true, false)));
this._initialized = true;
}
private isUntrusted(): boolean {
return !this._isWorkspaceTrusted;
}
private async onDidWorkspaceConfigurationChange(reload: boolean, fromCache: boolean): Promise<void> {
if (reload) {
await this.reload();
}
this.updateCache();
this._onDidUpdateConfiguration.fire(fromCache);
}
private async updateCache(): Promise<void> {
if (this._workspaceIdentifier && this.configurationCache.needsCaching(this._workspaceIdentifier.configPath) && this._workspaceConfiguration instanceof FileServiceBasedWorkspaceConfiguration) {
const content = await this._workspaceConfiguration.resolveContent(this._workspaceIdentifier);
await this._cachedConfiguration.updateWorkspace(this._workspaceIdentifier, content);
}
}
}
class FileServiceBasedWorkspaceConfiguration extends Disposable {
workspaceConfigurationModelParser: WorkspaceConfigurationModelParser;
workspaceSettings: ConfigurationModel;
private _workspaceIdentifier: IWorkspaceIdentifier | null = null;
private workspaceConfigWatcher: IDisposable;
private readonly reloadConfigurationScheduler: RunOnceScheduler;
protected readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
constructor(
private readonly fileService: IFileService,
uriIdentityService: IUriIdentityService,
private readonly logService: ILogService,
) {
super();
this.workspaceConfigurationModelParser = new WorkspaceConfigurationModelParser('');
this.workspaceSettings = new ConfigurationModel();
this._register(Event.any(
Event.filter(this.fileService.onDidFilesChange, e => !!this._workspaceIdentifier && e.contains(this._workspaceIdentifier.configPath)),
Event.filter(this.fileService.onDidRunOperation, e => !!this._workspaceIdentifier && (e.isOperation(FileOperation.CREATE) || e.isOperation(FileOperation.COPY) || e.isOperation(FileOperation.DELETE) || e.isOperation(FileOperation.WRITE)) && uriIdentityService.extUri.isEqual(e.resource, this._workspaceIdentifier.configPath))
)(() => this.reloadConfigurationScheduler.schedule()));
this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this._onDidChange.fire(), 50));
this.workspaceConfigWatcher = this._register(this.watchWorkspaceConfigurationFile());
}
get workspaceIdentifier(): IWorkspaceIdentifier | null {
return this._workspaceIdentifier;
}
async resolveContent(workspaceIdentifier: IWorkspaceIdentifier): Promise<string> {
const content = await this.fileService.readFile(workspaceIdentifier.configPath);
return content.value.toString();
}
async load(workspaceIdentifier: IWorkspaceIdentifier, configurationParseOptions: ConfigurationParseOptions): Promise<void> {
if (!this._workspaceIdentifier || this._workspaceIdentifier.id !== workspaceIdentifier.id) {
this._workspaceIdentifier = workspaceIdentifier;
this.workspaceConfigurationModelParser = new WorkspaceConfigurationModelParser(this._workspaceIdentifier.id);
dispose(this.workspaceConfigWatcher);
this.workspaceConfigWatcher = this._register(this.watchWorkspaceConfigurationFile());
}
let contents = '';
try {
contents = await this.resolveContent(this._workspaceIdentifier);
} catch (error) {
const exists = await this.fileService.exists(this._workspaceIdentifier.configPath);
if (exists) {
this.logService.error(error);
}
}
this.workspaceConfigurationModelParser.parse(contents, configurationParseOptions);
this.consolidate();
}
getConfigurationModel(): ConfigurationModel {
return this.workspaceConfigurationModelParser.configurationModel;
}
getFolders(): IStoredWorkspaceFolder[] {
return this.workspaceConfigurationModelParser.folders;
}
isTransient(): boolean {
return this.workspaceConfigurationModelParser.transient;
}
getWorkspaceSettings(): ConfigurationModel {
return this.workspaceSettings;
}
reparseWorkspaceSettings(configurationParseOptions: ConfigurationParseOptions): ConfigurationModel {
this.workspaceConfigurationModelParser.reparseWorkspaceSettings(configurationParseOptions);
this.consolidate();
return this.getWorkspaceSettings();
}
getRestrictedSettings(): string[] {
return this.workspaceConfigurationModelParser.getRestrictedWorkspaceSettings();
}
private consolidate(): void {
this.workspaceSettings = this.workspaceConfigurationModelParser.settingsModel.merge(this.workspaceConfigurationModelParser.launchModel, this.workspaceConfigurationModelParser.tasksModel);
}
private watchWorkspaceConfigurationFile(): IDisposable {
return this._workspaceIdentifier ? this.fileService.watch(this._workspaceIdentifier.configPath) : Disposable.None;
}
}
class CachedWorkspaceConfiguration {
readonly onDidChange: Event<void> = Event.None;
workspaceConfigurationModelParser: WorkspaceConfigurationModelParser;
workspaceSettings: ConfigurationModel;
constructor(private readonly configurationCache: IConfigurationCache) {
this.workspaceConfigurationModelParser = new WorkspaceConfigurationModelParser('');
this.workspaceSettings = new ConfigurationModel();
}
async load(workspaceIdentifier: IWorkspaceIdentifier, configurationParseOptions: ConfigurationParseOptions): Promise<void> {
try {
const key = this.getKey(workspaceIdentifier);
const contents = await this.configurationCache.read(key);
const parsed: { content: string } = JSON.parse(contents);
if (parsed.content) {
this.workspaceConfigurationModelParser = new WorkspaceConfigurationModelParser(key.key);
this.workspaceConfigurationModelParser.parse(parsed.content, configurationParseOptions);
this.consolidate();
}
} catch (e) {
}
}
get workspaceIdentifier(): IWorkspaceIdentifier | null {
return null;
}
getConfigurationModel(): ConfigurationModel {
return this.workspaceConfigurationModelParser.configurationModel;
}
getFolders(): IStoredWorkspaceFolder[] {
return this.workspaceConfigurationModelParser.folders;
}
isTransient(): boolean {
return this.workspaceConfigurationModelParser.transient;
}
getWorkspaceSettings(): ConfigurationModel {
return this.workspaceSettings;
}
reparseWorkspaceSettings(configurationParseOptions: ConfigurationParseOptions): ConfigurationModel {
this.workspaceConfigurationModelParser.reparseWorkspaceSettings(configurationParseOptions);
this.consolidate();
return this.getWorkspaceSettings();
}
getRestrictedSettings(): string[] {
return this.workspaceConfigurationModelParser.getRestrictedWorkspaceSettings();
}
private consolidate(): void {
this.workspaceSettings = this.workspaceConfigurationModelParser.settingsModel.merge(this.workspaceConfigurationModelParser.launchModel, this.workspaceConfigurationModelParser.tasksModel);
}
async updateWorkspace(workspaceIdentifier: IWorkspaceIdentifier, content: string | undefined): Promise<void> {
try {
const key = this.getKey(workspaceIdentifier);
if (content) {
await this.configurationCache.write(key, JSON.stringify({ content }));
} else {
await this.configurationCache.remove(key);
}
} catch (error) {
}
}
private getKey(workspaceIdentifier: IWorkspaceIdentifier): ConfigurationKey {
return {
type: 'workspaces',
key: workspaceIdentifier.id
};
}
}
class CachedFolderConfiguration {
readonly onDidChange = Event.None;
private _folderSettingsModelParser: ConfigurationModelParser;
private _folderSettingsParseOptions: ConfigurationParseOptions;
private _standAloneConfigurations: ConfigurationModel[];
private configurationModel: ConfigurationModel;
private readonly key: ConfigurationKey;
constructor(
folder: URI,
configFolderRelativePath: string,
configurationParseOptions: ConfigurationParseOptions,
private readonly configurationCache: IConfigurationCache,
) {
this.key = { type: 'folder', key: hash(joinPath(folder, configFolderRelativePath).toString()).toString(16) };
this._folderSettingsModelParser = new ConfigurationModelParser('CachedFolderConfiguration');
this._folderSettingsParseOptions = configurationParseOptions;
this._standAloneConfigurations = [];
this.configurationModel = new ConfigurationModel();
}
async loadConfiguration(): Promise<ConfigurationModel> {
try {
const contents = await this.configurationCache.read(this.key);
const { content: configurationContents }: { content: IStringDictionary<string> } = JSON.parse(contents.toString());
if (configurationContents) {
for (const key of Object.keys(configurationContents)) {
if (key === FOLDER_SETTINGS_NAME) {
this._folderSettingsModelParser.parse(configurationContents[key], this._folderSettingsParseOptions);
} else {
const standAloneConfigurationModelParser = new StandaloneConfigurationModelParser(key, key);
standAloneConfigurationModelParser.parse(configurationContents[key]);
this._standAloneConfigurations.push(standAloneConfigurationModelParser.configurationModel);
}
}
}
this.consolidate();
} catch (e) {
}
return this.configurationModel;
}
async updateConfiguration(settingsContent: string | undefined, standAloneConfigurationContents: [string, string | undefined][]): Promise<void> {
const content: any = {};
if (settingsContent) {
content[FOLDER_SETTINGS_NAME] = settingsContent;
}
standAloneConfigurationContents.forEach(([key, contents]) => {
if (contents) {
content[key] = contents;
}
});
if (Object.keys(content).length) {
await this.configurationCache.write(this.key, JSON.stringify({ content }));
} else {
await this.configurationCache.remove(this.key);
}
}
getRestrictedSettings(): string[] {
return this._folderSettingsModelParser.restrictedConfigurations;
}
reparse(configurationParseOptions: ConfigurationParseOptions): ConfigurationModel {
this._folderSettingsParseOptions = configurationParseOptions;
this._folderSettingsModelParser.reparse(this._folderSettingsParseOptions);
this.consolidate();
return this.configurationModel;
}
private consolidate(): void {
this.configurationModel = this._folderSettingsModelParser.configurationModel.merge(...this._standAloneConfigurations);
}
getUnsupportedKeys(): string[] {
return [];
}
}
export class FolderConfiguration extends Disposable {
protected readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
private folderConfiguration: CachedFolderConfiguration | FileServiceBasedConfiguration;
private readonly scopes: ConfigurationScope[];
private readonly configurationFolder: URI;
private cachedFolderConfiguration: CachedFolderConfiguration;
constructor(
useCache: boolean,
readonly workspaceFolder: IWorkspaceFolder,
configFolderRelativePath: string,
private readonly workbenchState: WorkbenchState,
private workspaceTrusted: boolean,
fileService: IFileService,
uriIdentityService: IUriIdentityService,
logService: ILogService,
private readonly configurationCache: IConfigurationCache
) {
super();
this.scopes = WorkbenchState.WORKSPACE === this.workbenchState ? FOLDER_SCOPES : WORKSPACE_SCOPES;
this.configurationFolder = uriIdentityService.extUri.joinPath(workspaceFolder.uri, configFolderRelativePath);
this.cachedFolderConfiguration = new CachedFolderConfiguration(workspaceFolder.uri, configFolderRelativePath, { scopes: this.scopes, skipRestricted: this.isUntrusted() }, configurationCache);
if (useCache && this.configurationCache.needsCaching(workspaceFolder.uri)) {
this.folderConfiguration = this.cachedFolderConfiguration;
whenProviderRegistered(workspaceFolder.uri, fileService)
.then(() => {
this.folderConfiguration = this._register(this.createFileServiceBasedConfiguration(fileService, uriIdentityService, logService));
this._register(this.folderConfiguration.onDidChange(e => this.onDidFolderConfigurationChange()));
this.onDidFolderConfigurationChange();
});
} else {
this.folderConfiguration = this._register(this.createFileServiceBasedConfiguration(fileService, uriIdentityService, logService));
this._register(this.folderConfiguration.onDidChange(e => this.onDidFolderConfigurationChange()));
}
}
loadConfiguration(): Promise<ConfigurationModel> {
return this.folderConfiguration.loadConfiguration();
}
updateWorkspaceTrust(trusted: boolean): ConfigurationModel {
this.workspaceTrusted = trusted;
return this.reparse();
}
reparse(): ConfigurationModel {
const configurationModel = this.folderConfiguration.reparse({ scopes: this.scopes, skipRestricted: this.isUntrusted() });
this.updateCache();
return configurationModel;
}
getRestrictedSettings(): string[] {
return this.folderConfiguration.getRestrictedSettings();
}
private isUntrusted(): boolean {
return !this.workspaceTrusted;
}
private onDidFolderConfigurationChange(): void {
this.updateCache();
this._onDidChange.fire();
}
private createFileServiceBasedConfiguration(fileService: IFileService, uriIdentityService: IUriIdentityService, logService: ILogService) {
const settingsResource = uriIdentityService.extUri.joinPath(this.configurationFolder, `${FOLDER_SETTINGS_NAME}.json`);
const standAloneConfigurationResources: [string, URI][] = [TASKS_CONFIGURATION_KEY, LAUNCH_CONFIGURATION_KEY].map(name => ([name, uriIdentityService.extUri.joinPath(this.configurationFolder, `${name}.json`)]));
return new FileServiceBasedConfiguration(this.configurationFolder.toString(), settingsResource, standAloneConfigurationResources, { scopes: this.scopes, skipRestricted: this.isUntrusted() }, fileService, uriIdentityService, logService);
}
private async updateCache(): Promise<void> {
if (this.configurationCache.needsCaching(this.configurationFolder) && this.folderConfiguration instanceof FileServiceBasedConfiguration) {
const [settingsContent, standAloneConfigurationContents] = await this.folderConfiguration.resolveContents();
this.cachedFolderConfiguration.updateConfiguration(settingsContent, standAloneConfigurationContents);
}
}
} | the_stack |
import * as $protobuf from "protobufjs";
/** Namespace google. */
export namespace google {
/** Namespace longrunning. */
namespace longrunning {
/** Represents an Operations */
class Operations extends $protobuf.rpc.Service {
/**
* Constructs a new Operations service.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
*/
constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
/**
* Creates new Operations service using the specified rpc implementation.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
* @returns RPC service. Useful where requests and/or responses are streamed.
*/
public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Operations;
/**
* Calls ListOperations.
* @param request ListOperationsRequest message or plain object
* @param callback Node-style callback called with the error, if any, and ListOperationsResponse
*/
public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void;
/**
* Calls ListOperations.
* @param request ListOperationsRequest message or plain object
* @returns Promise
*/
public listOperations(request: google.longrunning.IListOperationsRequest): Promise<google.longrunning.ListOperationsResponse>;
/**
* Calls GetOperation.
* @param request GetOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Operation
*/
public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void;
/**
* Calls GetOperation.
* @param request GetOperationRequest message or plain object
* @returns Promise
*/
public getOperation(request: google.longrunning.IGetOperationRequest): Promise<google.longrunning.Operation>;
/**
* Calls DeleteOperation.
* @param request DeleteOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void;
/**
* Calls DeleteOperation.
* @param request DeleteOperationRequest message or plain object
* @returns Promise
*/
public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise<google.protobuf.Empty>;
/**
* Calls CancelOperation.
* @param request CancelOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Empty
*/
public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void;
/**
* Calls CancelOperation.
* @param request CancelOperationRequest message or plain object
* @returns Promise
*/
public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise<google.protobuf.Empty>;
/**
* Calls WaitOperation.
* @param request WaitOperationRequest message or plain object
* @param callback Node-style callback called with the error, if any, and Operation
*/
public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void;
/**
* Calls WaitOperation.
* @param request WaitOperationRequest message or plain object
* @returns Promise
*/
public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise<google.longrunning.Operation>;
}
namespace Operations {
/**
* Callback as used by {@link google.longrunning.Operations#listOperations}.
* @param error Error, if any
* @param [response] ListOperationsResponse
*/
type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void;
/**
* Callback as used by {@link google.longrunning.Operations#getOperation}.
* @param error Error, if any
* @param [response] Operation
*/
type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void;
/**
* Callback as used by {@link google.longrunning.Operations#deleteOperation}.
* @param error Error, if any
* @param [response] Empty
*/
type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.longrunning.Operations#cancelOperation}.
* @param error Error, if any
* @param [response] Empty
*/
type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void;
/**
* Callback as used by {@link google.longrunning.Operations#waitOperation}.
* @param error Error, if any
* @param [response] Operation
*/
type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void;
}
/** Properties of an Operation. */
interface IOperation {
/** Operation name */
name?: (string|null);
/** Operation metadata */
metadata?: (google.protobuf.IAny|null);
/** Operation done */
done?: (boolean|null);
/** Operation error */
error?: (google.rpc.IStatus|null);
/** Operation response */
response?: (google.protobuf.IAny|null);
}
/** Represents an Operation. */
class Operation implements IOperation {
/**
* Constructs a new Operation.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IOperation);
/** Operation name. */
public name: string;
/** Operation metadata. */
public metadata?: (google.protobuf.IAny|null);
/** Operation done. */
public done: boolean;
/** Operation error. */
public error?: (google.rpc.IStatus|null);
/** Operation response. */
public response?: (google.protobuf.IAny|null);
/** Operation result. */
public result?: ("error"|"response");
/**
* Creates a new Operation instance using the specified properties.
* @param [properties] Properties to set
* @returns Operation instance
*/
public static create(properties?: google.longrunning.IOperation): google.longrunning.Operation;
/**
* Encodes the specified Operation message. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages.
* @param message Operation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Operation message, length delimited. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages.
* @param message Operation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Operation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Operation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.Operation;
/**
* Decodes an Operation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Operation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.Operation;
/**
* Verifies an Operation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Operation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Operation
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.Operation;
/**
* Creates a plain object from an Operation message. Also converts values to other types if specified.
* @param message Operation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Operation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetOperationRequest. */
interface IGetOperationRequest {
/** GetOperationRequest name */
name?: (string|null);
}
/** Represents a GetOperationRequest. */
class GetOperationRequest implements IGetOperationRequest {
/**
* Constructs a new GetOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IGetOperationRequest);
/** GetOperationRequest name. */
public name: string;
/**
* Creates a new GetOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GetOperationRequest instance
*/
public static create(properties?: google.longrunning.IGetOperationRequest): google.longrunning.GetOperationRequest;
/**
* Encodes the specified GetOperationRequest message. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages.
* @param message GetOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages.
* @param message GetOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.GetOperationRequest;
/**
* Decodes a GetOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.GetOperationRequest;
/**
* Verifies a GetOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest;
/**
* Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified.
* @param message GetOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListOperationsRequest. */
interface IListOperationsRequest {
/** ListOperationsRequest name */
name?: (string|null);
/** ListOperationsRequest filter */
filter?: (string|null);
/** ListOperationsRequest pageSize */
pageSize?: (number|null);
/** ListOperationsRequest pageToken */
pageToken?: (string|null);
}
/** Represents a ListOperationsRequest. */
class ListOperationsRequest implements IListOperationsRequest {
/**
* Constructs a new ListOperationsRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IListOperationsRequest);
/** ListOperationsRequest name. */
public name: string;
/** ListOperationsRequest filter. */
public filter: string;
/** ListOperationsRequest pageSize. */
public pageSize: number;
/** ListOperationsRequest pageToken. */
public pageToken: string;
/**
* Creates a new ListOperationsRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ListOperationsRequest instance
*/
public static create(properties?: google.longrunning.IListOperationsRequest): google.longrunning.ListOperationsRequest;
/**
* Encodes the specified ListOperationsRequest message. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages.
* @param message ListOperationsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListOperationsRequest message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages.
* @param message ListOperationsRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListOperationsRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListOperationsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsRequest;
/**
* Decodes a ListOperationsRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListOperationsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsRequest;
/**
* Verifies a ListOperationsRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListOperationsRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest;
/**
* Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified.
* @param message ListOperationsRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListOperationsRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ListOperationsResponse. */
interface IListOperationsResponse {
/** ListOperationsResponse operations */
operations?: (google.longrunning.IOperation[]|null);
/** ListOperationsResponse nextPageToken */
nextPageToken?: (string|null);
}
/** Represents a ListOperationsResponse. */
class ListOperationsResponse implements IListOperationsResponse {
/**
* Constructs a new ListOperationsResponse.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IListOperationsResponse);
/** ListOperationsResponse operations. */
public operations: google.longrunning.IOperation[];
/** ListOperationsResponse nextPageToken. */
public nextPageToken: string;
/**
* Creates a new ListOperationsResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ListOperationsResponse instance
*/
public static create(properties?: google.longrunning.IListOperationsResponse): google.longrunning.ListOperationsResponse;
/**
* Encodes the specified ListOperationsResponse message. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages.
* @param message ListOperationsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListOperationsResponse message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages.
* @param message ListOperationsResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListOperationsResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListOperationsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsResponse;
/**
* Decodes a ListOperationsResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListOperationsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsResponse;
/**
* Verifies a ListOperationsResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListOperationsResponse
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse;
/**
* Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified.
* @param message ListOperationsResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListOperationsResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CancelOperationRequest. */
interface ICancelOperationRequest {
/** CancelOperationRequest name */
name?: (string|null);
}
/** Represents a CancelOperationRequest. */
class CancelOperationRequest implements ICancelOperationRequest {
/**
* Constructs a new CancelOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.ICancelOperationRequest);
/** CancelOperationRequest name. */
public name: string;
/**
* Creates a new CancelOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns CancelOperationRequest instance
*/
public static create(properties?: google.longrunning.ICancelOperationRequest): google.longrunning.CancelOperationRequest;
/**
* Encodes the specified CancelOperationRequest message. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages.
* @param message CancelOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CancelOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages.
* @param message CancelOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CancelOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CancelOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.CancelOperationRequest;
/**
* Decodes a CancelOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CancelOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.CancelOperationRequest;
/**
* Verifies a CancelOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CancelOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest;
/**
* Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified.
* @param message CancelOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CancelOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DeleteOperationRequest. */
interface IDeleteOperationRequest {
/** DeleteOperationRequest name */
name?: (string|null);
}
/** Represents a DeleteOperationRequest. */
class DeleteOperationRequest implements IDeleteOperationRequest {
/**
* Constructs a new DeleteOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IDeleteOperationRequest);
/** DeleteOperationRequest name. */
public name: string;
/**
* Creates a new DeleteOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns DeleteOperationRequest instance
*/
public static create(properties?: google.longrunning.IDeleteOperationRequest): google.longrunning.DeleteOperationRequest;
/**
* Encodes the specified DeleteOperationRequest message. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages.
* @param message DeleteOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DeleteOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages.
* @param message DeleteOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DeleteOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DeleteOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.DeleteOperationRequest;
/**
* Decodes a DeleteOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DeleteOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.DeleteOperationRequest;
/**
* Verifies a DeleteOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DeleteOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest;
/**
* Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified.
* @param message DeleteOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DeleteOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WaitOperationRequest. */
interface IWaitOperationRequest {
/** WaitOperationRequest name */
name?: (string|null);
/** WaitOperationRequest timeout */
timeout?: (google.protobuf.IDuration|null);
}
/** Represents a WaitOperationRequest. */
class WaitOperationRequest implements IWaitOperationRequest {
/**
* Constructs a new WaitOperationRequest.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IWaitOperationRequest);
/** WaitOperationRequest name. */
public name: string;
/** WaitOperationRequest timeout. */
public timeout?: (google.protobuf.IDuration|null);
/**
* Creates a new WaitOperationRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns WaitOperationRequest instance
*/
public static create(properties?: google.longrunning.IWaitOperationRequest): google.longrunning.WaitOperationRequest;
/**
* Encodes the specified WaitOperationRequest message. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages.
* @param message WaitOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WaitOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages.
* @param message WaitOperationRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WaitOperationRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WaitOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.WaitOperationRequest;
/**
* Decodes a WaitOperationRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WaitOperationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.WaitOperationRequest;
/**
* Verifies a WaitOperationRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WaitOperationRequest
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest;
/**
* Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified.
* @param message WaitOperationRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WaitOperationRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OperationInfo. */
interface IOperationInfo {
/** OperationInfo responseType */
responseType?: (string|null);
/** OperationInfo metadataType */
metadataType?: (string|null);
}
/** Represents an OperationInfo. */
class OperationInfo implements IOperationInfo {
/**
* Constructs a new OperationInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.longrunning.IOperationInfo);
/** OperationInfo responseType. */
public responseType: string;
/** OperationInfo metadataType. */
public metadataType: string;
/**
* Creates a new OperationInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns OperationInfo instance
*/
public static create(properties?: google.longrunning.IOperationInfo): google.longrunning.OperationInfo;
/**
* Encodes the specified OperationInfo message. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages.
* @param message OperationInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OperationInfo message, length delimited. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages.
* @param message OperationInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OperationInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OperationInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.OperationInfo;
/**
* Decodes an OperationInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OperationInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.OperationInfo;
/**
* Verifies an OperationInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OperationInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OperationInfo
*/
public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo;
/**
* Creates a plain object from an OperationInfo message. Also converts values to other types if specified.
* @param message OperationInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OperationInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace api. */
namespace api {
/** Properties of a Http. */
interface IHttp {
/** Http rules */
rules?: (google.api.IHttpRule[]|null);
/** Http fullyDecodeReservedExpansion */
fullyDecodeReservedExpansion?: (boolean|null);
}
/** Represents a Http. */
class Http implements IHttp {
/**
* Constructs a new Http.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.IHttp);
/** Http rules. */
public rules: google.api.IHttpRule[];
/** Http fullyDecodeReservedExpansion. */
public fullyDecodeReservedExpansion: boolean;
/**
* Creates a new Http instance using the specified properties.
* @param [properties] Properties to set
* @returns Http instance
*/
public static create(properties?: google.api.IHttp): google.api.Http;
/**
* Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages.
* @param message Http message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages.
* @param message Http message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Http message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Http
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http;
/**
* Decodes a Http message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Http
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http;
/**
* Verifies a Http message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Http message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Http
*/
public static fromObject(object: { [k: string]: any }): google.api.Http;
/**
* Creates a plain object from a Http message. Also converts values to other types if specified.
* @param message Http
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Http to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a HttpRule. */
interface IHttpRule {
/** HttpRule selector */
selector?: (string|null);
/** HttpRule get */
get?: (string|null);
/** HttpRule put */
put?: (string|null);
/** HttpRule post */
post?: (string|null);
/** HttpRule delete */
"delete"?: (string|null);
/** HttpRule patch */
patch?: (string|null);
/** HttpRule custom */
custom?: (google.api.ICustomHttpPattern|null);
/** HttpRule body */
body?: (string|null);
/** HttpRule responseBody */
responseBody?: (string|null);
/** HttpRule additionalBindings */
additionalBindings?: (google.api.IHttpRule[]|null);
}
/** Represents a HttpRule. */
class HttpRule implements IHttpRule {
/**
* Constructs a new HttpRule.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.IHttpRule);
/** HttpRule selector. */
public selector: string;
/** HttpRule get. */
public get: string;
/** HttpRule put. */
public put: string;
/** HttpRule post. */
public post: string;
/** HttpRule delete. */
public delete: string;
/** HttpRule patch. */
public patch: string;
/** HttpRule custom. */
public custom?: (google.api.ICustomHttpPattern|null);
/** HttpRule body. */
public body: string;
/** HttpRule responseBody. */
public responseBody: string;
/** HttpRule additionalBindings. */
public additionalBindings: google.api.IHttpRule[];
/** HttpRule pattern. */
public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom");
/**
* Creates a new HttpRule instance using the specified properties.
* @param [properties] Properties to set
* @returns HttpRule instance
*/
public static create(properties?: google.api.IHttpRule): google.api.HttpRule;
/**
* Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages.
* @param message HttpRule message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages.
* @param message HttpRule message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a HttpRule message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns HttpRule
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule;
/**
* Decodes a HttpRule message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns HttpRule
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule;
/**
* Verifies a HttpRule message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a HttpRule message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns HttpRule
*/
public static fromObject(object: { [k: string]: any }): google.api.HttpRule;
/**
* Creates a plain object from a HttpRule message. Also converts values to other types if specified.
* @param message HttpRule
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this HttpRule to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CustomHttpPattern. */
interface ICustomHttpPattern {
/** CustomHttpPattern kind */
kind?: (string|null);
/** CustomHttpPattern path */
path?: (string|null);
}
/** Represents a CustomHttpPattern. */
class CustomHttpPattern implements ICustomHttpPattern {
/**
* Constructs a new CustomHttpPattern.
* @param [properties] Properties to set
*/
constructor(properties?: google.api.ICustomHttpPattern);
/** CustomHttpPattern kind. */
public kind: string;
/** CustomHttpPattern path. */
public path: string;
/**
* Creates a new CustomHttpPattern instance using the specified properties.
* @param [properties] Properties to set
* @returns CustomHttpPattern instance
*/
public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern;
/**
* Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages.
* @param message CustomHttpPattern message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages.
* @param message CustomHttpPattern message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CustomHttpPattern message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CustomHttpPattern
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern;
/**
* Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CustomHttpPattern
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern;
/**
* Verifies a CustomHttpPattern message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CustomHttpPattern
*/
public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern;
/**
* Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified.
* @param message CustomHttpPattern
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CustomHttpPattern to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace protobuf. */
namespace protobuf {
/** Properties of a FileDescriptorSet. */
interface IFileDescriptorSet {
/** FileDescriptorSet file */
file?: (google.protobuf.IFileDescriptorProto[]|null);
}
/** Represents a FileDescriptorSet. */
class FileDescriptorSet implements IFileDescriptorSet {
/**
* Constructs a new FileDescriptorSet.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFileDescriptorSet);
/** FileDescriptorSet file. */
public file: google.protobuf.IFileDescriptorProto[];
/**
* Creates a new FileDescriptorSet instance using the specified properties.
* @param [properties] Properties to set
* @returns FileDescriptorSet instance
*/
public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet;
/**
* Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages.
* @param message FileDescriptorSet message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages.
* @param message FileDescriptorSet message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FileDescriptorSet message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FileDescriptorSet
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet;
/**
* Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FileDescriptorSet
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet;
/**
* Verifies a FileDescriptorSet message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FileDescriptorSet
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet;
/**
* Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified.
* @param message FileDescriptorSet
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FileDescriptorSet to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FileDescriptorProto. */
interface IFileDescriptorProto {
/** FileDescriptorProto name */
name?: (string|null);
/** FileDescriptorProto package */
"package"?: (string|null);
/** FileDescriptorProto dependency */
dependency?: (string[]|null);
/** FileDescriptorProto publicDependency */
publicDependency?: (number[]|null);
/** FileDescriptorProto weakDependency */
weakDependency?: (number[]|null);
/** FileDescriptorProto messageType */
messageType?: (google.protobuf.IDescriptorProto[]|null);
/** FileDescriptorProto enumType */
enumType?: (google.protobuf.IEnumDescriptorProto[]|null);
/** FileDescriptorProto service */
service?: (google.protobuf.IServiceDescriptorProto[]|null);
/** FileDescriptorProto extension */
extension?: (google.protobuf.IFieldDescriptorProto[]|null);
/** FileDescriptorProto options */
options?: (google.protobuf.IFileOptions|null);
/** FileDescriptorProto sourceCodeInfo */
sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null);
/** FileDescriptorProto syntax */
syntax?: (string|null);
}
/** Represents a FileDescriptorProto. */
class FileDescriptorProto implements IFileDescriptorProto {
/**
* Constructs a new FileDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFileDescriptorProto);
/** FileDescriptorProto name. */
public name: string;
/** FileDescriptorProto package. */
public package: string;
/** FileDescriptorProto dependency. */
public dependency: string[];
/** FileDescriptorProto publicDependency. */
public publicDependency: number[];
/** FileDescriptorProto weakDependency. */
public weakDependency: number[];
/** FileDescriptorProto messageType. */
public messageType: google.protobuf.IDescriptorProto[];
/** FileDescriptorProto enumType. */
public enumType: google.protobuf.IEnumDescriptorProto[];
/** FileDescriptorProto service. */
public service: google.protobuf.IServiceDescriptorProto[];
/** FileDescriptorProto extension. */
public extension: google.protobuf.IFieldDescriptorProto[];
/** FileDescriptorProto options. */
public options?: (google.protobuf.IFileOptions|null);
/** FileDescriptorProto sourceCodeInfo. */
public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null);
/** FileDescriptorProto syntax. */
public syntax: string;
/**
* Creates a new FileDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns FileDescriptorProto instance
*/
public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto;
/**
* Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages.
* @param message FileDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages.
* @param message FileDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FileDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FileDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto;
/**
* Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FileDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto;
/**
* Verifies a FileDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FileDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto;
/**
* Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified.
* @param message FileDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FileDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DescriptorProto. */
interface IDescriptorProto {
/** DescriptorProto name */
name?: (string|null);
/** DescriptorProto field */
field?: (google.protobuf.IFieldDescriptorProto[]|null);
/** DescriptorProto extension */
extension?: (google.protobuf.IFieldDescriptorProto[]|null);
/** DescriptorProto nestedType */
nestedType?: (google.protobuf.IDescriptorProto[]|null);
/** DescriptorProto enumType */
enumType?: (google.protobuf.IEnumDescriptorProto[]|null);
/** DescriptorProto extensionRange */
extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null);
/** DescriptorProto oneofDecl */
oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null);
/** DescriptorProto options */
options?: (google.protobuf.IMessageOptions|null);
/** DescriptorProto reservedRange */
reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null);
/** DescriptorProto reservedName */
reservedName?: (string[]|null);
}
/** Represents a DescriptorProto. */
class DescriptorProto implements IDescriptorProto {
/**
* Constructs a new DescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IDescriptorProto);
/** DescriptorProto name. */
public name: string;
/** DescriptorProto field. */
public field: google.protobuf.IFieldDescriptorProto[];
/** DescriptorProto extension. */
public extension: google.protobuf.IFieldDescriptorProto[];
/** DescriptorProto nestedType. */
public nestedType: google.protobuf.IDescriptorProto[];
/** DescriptorProto enumType. */
public enumType: google.protobuf.IEnumDescriptorProto[];
/** DescriptorProto extensionRange. */
public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[];
/** DescriptorProto oneofDecl. */
public oneofDecl: google.protobuf.IOneofDescriptorProto[];
/** DescriptorProto options. */
public options?: (google.protobuf.IMessageOptions|null);
/** DescriptorProto reservedRange. */
public reservedRange: google.protobuf.DescriptorProto.IReservedRange[];
/** DescriptorProto reservedName. */
public reservedName: string[];
/**
* Creates a new DescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns DescriptorProto instance
*/
public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto;
/**
* Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages.
* @param message DescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages.
* @param message DescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto;
/**
* Decodes a DescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto;
/**
* Verifies a DescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto;
/**
* Creates a plain object from a DescriptorProto message. Also converts values to other types if specified.
* @param message DescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace DescriptorProto {
/** Properties of an ExtensionRange. */
interface IExtensionRange {
/** ExtensionRange start */
start?: (number|null);
/** ExtensionRange end */
end?: (number|null);
/** ExtensionRange options */
options?: (google.protobuf.IExtensionRangeOptions|null);
}
/** Represents an ExtensionRange. */
class ExtensionRange implements IExtensionRange {
/**
* Constructs a new ExtensionRange.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange);
/** ExtensionRange start. */
public start: number;
/** ExtensionRange end. */
public end: number;
/** ExtensionRange options. */
public options?: (google.protobuf.IExtensionRangeOptions|null);
/**
* Creates a new ExtensionRange instance using the specified properties.
* @param [properties] Properties to set
* @returns ExtensionRange instance
*/
public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages.
* @param message ExtensionRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages.
* @param message ExtensionRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExtensionRange message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExtensionRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Decodes an ExtensionRange message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExtensionRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Verifies an ExtensionRange message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExtensionRange
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange;
/**
* Creates a plain object from an ExtensionRange message. Also converts values to other types if specified.
* @param message ExtensionRange
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExtensionRange to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReservedRange. */
interface IReservedRange {
/** ReservedRange start */
start?: (number|null);
/** ReservedRange end */
end?: (number|null);
}
/** Represents a ReservedRange. */
class ReservedRange implements IReservedRange {
/**
* Constructs a new ReservedRange.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.DescriptorProto.IReservedRange);
/** ReservedRange start. */
public start: number;
/** ReservedRange end. */
public end: number;
/**
* Creates a new ReservedRange instance using the specified properties.
* @param [properties] Properties to set
* @returns ReservedRange instance
*/
public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange;
/**
* Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages.
* @param message ReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages.
* @param message ReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReservedRange message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange;
/**
* Decodes a ReservedRange message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange;
/**
* Verifies a ReservedRange message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReservedRange message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReservedRange
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange;
/**
* Creates a plain object from a ReservedRange message. Also converts values to other types if specified.
* @param message ReservedRange
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReservedRange to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an ExtensionRangeOptions. */
interface IExtensionRangeOptions {
/** ExtensionRangeOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an ExtensionRangeOptions. */
class ExtensionRangeOptions implements IExtensionRangeOptions {
/**
* Constructs a new ExtensionRangeOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IExtensionRangeOptions);
/** ExtensionRangeOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new ExtensionRangeOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns ExtensionRangeOptions instance
*/
public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions;
/**
* Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages.
* @param message ExtensionRangeOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages.
* @param message ExtensionRangeOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExtensionRangeOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExtensionRangeOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions;
/**
* Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExtensionRangeOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions;
/**
* Verifies an ExtensionRangeOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExtensionRangeOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions;
/**
* Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified.
* @param message ExtensionRangeOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExtensionRangeOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FieldDescriptorProto. */
interface IFieldDescriptorProto {
/** FieldDescriptorProto name */
name?: (string|null);
/** FieldDescriptorProto number */
number?: (number|null);
/** FieldDescriptorProto label */
label?: (google.protobuf.FieldDescriptorProto.Label|null);
/** FieldDescriptorProto type */
type?: (google.protobuf.FieldDescriptorProto.Type|null);
/** FieldDescriptorProto typeName */
typeName?: (string|null);
/** FieldDescriptorProto extendee */
extendee?: (string|null);
/** FieldDescriptorProto defaultValue */
defaultValue?: (string|null);
/** FieldDescriptorProto oneofIndex */
oneofIndex?: (number|null);
/** FieldDescriptorProto jsonName */
jsonName?: (string|null);
/** FieldDescriptorProto options */
options?: (google.protobuf.IFieldOptions|null);
}
/** Represents a FieldDescriptorProto. */
class FieldDescriptorProto implements IFieldDescriptorProto {
/**
* Constructs a new FieldDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFieldDescriptorProto);
/** FieldDescriptorProto name. */
public name: string;
/** FieldDescriptorProto number. */
public number: number;
/** FieldDescriptorProto label. */
public label: google.protobuf.FieldDescriptorProto.Label;
/** FieldDescriptorProto type. */
public type: google.protobuf.FieldDescriptorProto.Type;
/** FieldDescriptorProto typeName. */
public typeName: string;
/** FieldDescriptorProto extendee. */
public extendee: string;
/** FieldDescriptorProto defaultValue. */
public defaultValue: string;
/** FieldDescriptorProto oneofIndex. */
public oneofIndex: number;
/** FieldDescriptorProto jsonName. */
public jsonName: string;
/** FieldDescriptorProto options. */
public options?: (google.protobuf.IFieldOptions|null);
/**
* Creates a new FieldDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns FieldDescriptorProto instance
*/
public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto;
/**
* Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages.
* @param message FieldDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages.
* @param message FieldDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FieldDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FieldDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto;
/**
* Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FieldDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto;
/**
* Verifies a FieldDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FieldDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto;
/**
* Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified.
* @param message FieldDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FieldDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace FieldDescriptorProto {
/** Type enum. */
enum Type {
TYPE_DOUBLE = 1,
TYPE_FLOAT = 2,
TYPE_INT64 = 3,
TYPE_UINT64 = 4,
TYPE_INT32 = 5,
TYPE_FIXED64 = 6,
TYPE_FIXED32 = 7,
TYPE_BOOL = 8,
TYPE_STRING = 9,
TYPE_GROUP = 10,
TYPE_MESSAGE = 11,
TYPE_BYTES = 12,
TYPE_UINT32 = 13,
TYPE_ENUM = 14,
TYPE_SFIXED32 = 15,
TYPE_SFIXED64 = 16,
TYPE_SINT32 = 17,
TYPE_SINT64 = 18
}
/** Label enum. */
enum Label {
LABEL_OPTIONAL = 1,
LABEL_REQUIRED = 2,
LABEL_REPEATED = 3
}
}
/** Properties of an OneofDescriptorProto. */
interface IOneofDescriptorProto {
/** OneofDescriptorProto name */
name?: (string|null);
/** OneofDescriptorProto options */
options?: (google.protobuf.IOneofOptions|null);
}
/** Represents an OneofDescriptorProto. */
class OneofDescriptorProto implements IOneofDescriptorProto {
/**
* Constructs a new OneofDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IOneofDescriptorProto);
/** OneofDescriptorProto name. */
public name: string;
/** OneofDescriptorProto options. */
public options?: (google.protobuf.IOneofOptions|null);
/**
* Creates a new OneofDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns OneofDescriptorProto instance
*/
public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto;
/**
* Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages.
* @param message OneofDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages.
* @param message OneofDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OneofDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OneofDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto;
/**
* Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OneofDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto;
/**
* Verifies an OneofDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OneofDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto;
/**
* Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified.
* @param message OneofDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OneofDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EnumDescriptorProto. */
interface IEnumDescriptorProto {
/** EnumDescriptorProto name */
name?: (string|null);
/** EnumDescriptorProto value */
value?: (google.protobuf.IEnumValueDescriptorProto[]|null);
/** EnumDescriptorProto options */
options?: (google.protobuf.IEnumOptions|null);
/** EnumDescriptorProto reservedRange */
reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null);
/** EnumDescriptorProto reservedName */
reservedName?: (string[]|null);
}
/** Represents an EnumDescriptorProto. */
class EnumDescriptorProto implements IEnumDescriptorProto {
/**
* Constructs a new EnumDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumDescriptorProto);
/** EnumDescriptorProto name. */
public name: string;
/** EnumDescriptorProto value. */
public value: google.protobuf.IEnumValueDescriptorProto[];
/** EnumDescriptorProto options. */
public options?: (google.protobuf.IEnumOptions|null);
/** EnumDescriptorProto reservedRange. */
public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[];
/** EnumDescriptorProto reservedName. */
public reservedName: string[];
/**
* Creates a new EnumDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumDescriptorProto instance
*/
public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto;
/**
* Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages.
* @param message EnumDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages.
* @param message EnumDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto;
/**
* Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto;
/**
* Verifies an EnumDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto;
/**
* Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified.
* @param message EnumDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace EnumDescriptorProto {
/** Properties of an EnumReservedRange. */
interface IEnumReservedRange {
/** EnumReservedRange start */
start?: (number|null);
/** EnumReservedRange end */
end?: (number|null);
}
/** Represents an EnumReservedRange. */
class EnumReservedRange implements IEnumReservedRange {
/**
* Constructs a new EnumReservedRange.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange);
/** EnumReservedRange start. */
public start: number;
/** EnumReservedRange end. */
public end: number;
/**
* Creates a new EnumReservedRange instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumReservedRange instance
*/
public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages.
* @param message EnumReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages.
* @param message EnumReservedRange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumReservedRange message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Decodes an EnumReservedRange message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumReservedRange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Verifies an EnumReservedRange message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumReservedRange
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange;
/**
* Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified.
* @param message EnumReservedRange
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumReservedRange to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an EnumValueDescriptorProto. */
interface IEnumValueDescriptorProto {
/** EnumValueDescriptorProto name */
name?: (string|null);
/** EnumValueDescriptorProto number */
number?: (number|null);
/** EnumValueDescriptorProto options */
options?: (google.protobuf.IEnumValueOptions|null);
}
/** Represents an EnumValueDescriptorProto. */
class EnumValueDescriptorProto implements IEnumValueDescriptorProto {
/**
* Constructs a new EnumValueDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumValueDescriptorProto);
/** EnumValueDescriptorProto name. */
public name: string;
/** EnumValueDescriptorProto number. */
public number: number;
/** EnumValueDescriptorProto options. */
public options?: (google.protobuf.IEnumValueOptions|null);
/**
* Creates a new EnumValueDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumValueDescriptorProto instance
*/
public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto;
/**
* Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages.
* @param message EnumValueDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages.
* @param message EnumValueDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumValueDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumValueDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto;
/**
* Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumValueDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto;
/**
* Verifies an EnumValueDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumValueDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto;
/**
* Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified.
* @param message EnumValueDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumValueDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ServiceDescriptorProto. */
interface IServiceDescriptorProto {
/** ServiceDescriptorProto name */
name?: (string|null);
/** ServiceDescriptorProto method */
method?: (google.protobuf.IMethodDescriptorProto[]|null);
/** ServiceDescriptorProto options */
options?: (google.protobuf.IServiceOptions|null);
}
/** Represents a ServiceDescriptorProto. */
class ServiceDescriptorProto implements IServiceDescriptorProto {
/**
* Constructs a new ServiceDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IServiceDescriptorProto);
/** ServiceDescriptorProto name. */
public name: string;
/** ServiceDescriptorProto method. */
public method: google.protobuf.IMethodDescriptorProto[];
/** ServiceDescriptorProto options. */
public options?: (google.protobuf.IServiceOptions|null);
/**
* Creates a new ServiceDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns ServiceDescriptorProto instance
*/
public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto;
/**
* Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages.
* @param message ServiceDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages.
* @param message ServiceDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServiceDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServiceDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto;
/**
* Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServiceDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto;
/**
* Verifies a ServiceDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServiceDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto;
/**
* Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified.
* @param message ServiceDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServiceDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a MethodDescriptorProto. */
interface IMethodDescriptorProto {
/** MethodDescriptorProto name */
name?: (string|null);
/** MethodDescriptorProto inputType */
inputType?: (string|null);
/** MethodDescriptorProto outputType */
outputType?: (string|null);
/** MethodDescriptorProto options */
options?: (google.protobuf.IMethodOptions|null);
/** MethodDescriptorProto clientStreaming */
clientStreaming?: (boolean|null);
/** MethodDescriptorProto serverStreaming */
serverStreaming?: (boolean|null);
}
/** Represents a MethodDescriptorProto. */
class MethodDescriptorProto implements IMethodDescriptorProto {
/**
* Constructs a new MethodDescriptorProto.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IMethodDescriptorProto);
/** MethodDescriptorProto name. */
public name: string;
/** MethodDescriptorProto inputType. */
public inputType: string;
/** MethodDescriptorProto outputType. */
public outputType: string;
/** MethodDescriptorProto options. */
public options?: (google.protobuf.IMethodOptions|null);
/** MethodDescriptorProto clientStreaming. */
public clientStreaming: boolean;
/** MethodDescriptorProto serverStreaming. */
public serverStreaming: boolean;
/**
* Creates a new MethodDescriptorProto instance using the specified properties.
* @param [properties] Properties to set
* @returns MethodDescriptorProto instance
*/
public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto;
/**
* Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages.
* @param message MethodDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages.
* @param message MethodDescriptorProto message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MethodDescriptorProto message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MethodDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto;
/**
* Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MethodDescriptorProto
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto;
/**
* Verifies a MethodDescriptorProto message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MethodDescriptorProto
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto;
/**
* Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified.
* @param message MethodDescriptorProto
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MethodDescriptorProto to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FileOptions. */
interface IFileOptions {
/** FileOptions javaPackage */
javaPackage?: (string|null);
/** FileOptions javaOuterClassname */
javaOuterClassname?: (string|null);
/** FileOptions javaMultipleFiles */
javaMultipleFiles?: (boolean|null);
/** FileOptions javaGenerateEqualsAndHash */
javaGenerateEqualsAndHash?: (boolean|null);
/** FileOptions javaStringCheckUtf8 */
javaStringCheckUtf8?: (boolean|null);
/** FileOptions optimizeFor */
optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null);
/** FileOptions goPackage */
goPackage?: (string|null);
/** FileOptions ccGenericServices */
ccGenericServices?: (boolean|null);
/** FileOptions javaGenericServices */
javaGenericServices?: (boolean|null);
/** FileOptions pyGenericServices */
pyGenericServices?: (boolean|null);
/** FileOptions phpGenericServices */
phpGenericServices?: (boolean|null);
/** FileOptions deprecated */
deprecated?: (boolean|null);
/** FileOptions ccEnableArenas */
ccEnableArenas?: (boolean|null);
/** FileOptions objcClassPrefix */
objcClassPrefix?: (string|null);
/** FileOptions csharpNamespace */
csharpNamespace?: (string|null);
/** FileOptions swiftPrefix */
swiftPrefix?: (string|null);
/** FileOptions phpClassPrefix */
phpClassPrefix?: (string|null);
/** FileOptions phpNamespace */
phpNamespace?: (string|null);
/** FileOptions phpMetadataNamespace */
phpMetadataNamespace?: (string|null);
/** FileOptions rubyPackage */
rubyPackage?: (string|null);
/** FileOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents a FileOptions. */
class FileOptions implements IFileOptions {
/**
* Constructs a new FileOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFileOptions);
/** FileOptions javaPackage. */
public javaPackage: string;
/** FileOptions javaOuterClassname. */
public javaOuterClassname: string;
/** FileOptions javaMultipleFiles. */
public javaMultipleFiles: boolean;
/** FileOptions javaGenerateEqualsAndHash. */
public javaGenerateEqualsAndHash: boolean;
/** FileOptions javaStringCheckUtf8. */
public javaStringCheckUtf8: boolean;
/** FileOptions optimizeFor. */
public optimizeFor: google.protobuf.FileOptions.OptimizeMode;
/** FileOptions goPackage. */
public goPackage: string;
/** FileOptions ccGenericServices. */
public ccGenericServices: boolean;
/** FileOptions javaGenericServices. */
public javaGenericServices: boolean;
/** FileOptions pyGenericServices. */
public pyGenericServices: boolean;
/** FileOptions phpGenericServices. */
public phpGenericServices: boolean;
/** FileOptions deprecated. */
public deprecated: boolean;
/** FileOptions ccEnableArenas. */
public ccEnableArenas: boolean;
/** FileOptions objcClassPrefix. */
public objcClassPrefix: string;
/** FileOptions csharpNamespace. */
public csharpNamespace: string;
/** FileOptions swiftPrefix. */
public swiftPrefix: string;
/** FileOptions phpClassPrefix. */
public phpClassPrefix: string;
/** FileOptions phpNamespace. */
public phpNamespace: string;
/** FileOptions phpMetadataNamespace. */
public phpMetadataNamespace: string;
/** FileOptions rubyPackage. */
public rubyPackage: string;
/** FileOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new FileOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns FileOptions instance
*/
public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions;
/**
* Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages.
* @param message FileOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages.
* @param message FileOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FileOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FileOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions;
/**
* Decodes a FileOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FileOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions;
/**
* Verifies a FileOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FileOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FileOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions;
/**
* Creates a plain object from a FileOptions message. Also converts values to other types if specified.
* @param message FileOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FileOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace FileOptions {
/** OptimizeMode enum. */
enum OptimizeMode {
SPEED = 1,
CODE_SIZE = 2,
LITE_RUNTIME = 3
}
}
/** Properties of a MessageOptions. */
interface IMessageOptions {
/** MessageOptions messageSetWireFormat */
messageSetWireFormat?: (boolean|null);
/** MessageOptions noStandardDescriptorAccessor */
noStandardDescriptorAccessor?: (boolean|null);
/** MessageOptions deprecated */
deprecated?: (boolean|null);
/** MessageOptions mapEntry */
mapEntry?: (boolean|null);
/** MessageOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents a MessageOptions. */
class MessageOptions implements IMessageOptions {
/**
* Constructs a new MessageOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IMessageOptions);
/** MessageOptions messageSetWireFormat. */
public messageSetWireFormat: boolean;
/** MessageOptions noStandardDescriptorAccessor. */
public noStandardDescriptorAccessor: boolean;
/** MessageOptions deprecated. */
public deprecated: boolean;
/** MessageOptions mapEntry. */
public mapEntry: boolean;
/** MessageOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new MessageOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns MessageOptions instance
*/
public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions;
/**
* Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages.
* @param message MessageOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages.
* @param message MessageOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MessageOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MessageOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions;
/**
* Decodes a MessageOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MessageOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions;
/**
* Verifies a MessageOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MessageOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MessageOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions;
/**
* Creates a plain object from a MessageOptions message. Also converts values to other types if specified.
* @param message MessageOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MessageOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a FieldOptions. */
interface IFieldOptions {
/** FieldOptions ctype */
ctype?: (google.protobuf.FieldOptions.CType|null);
/** FieldOptions packed */
packed?: (boolean|null);
/** FieldOptions jstype */
jstype?: (google.protobuf.FieldOptions.JSType|null);
/** FieldOptions lazy */
lazy?: (boolean|null);
/** FieldOptions deprecated */
deprecated?: (boolean|null);
/** FieldOptions weak */
weak?: (boolean|null);
/** FieldOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents a FieldOptions. */
class FieldOptions implements IFieldOptions {
/**
* Constructs a new FieldOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IFieldOptions);
/** FieldOptions ctype. */
public ctype: google.protobuf.FieldOptions.CType;
/** FieldOptions packed. */
public packed: boolean;
/** FieldOptions jstype. */
public jstype: google.protobuf.FieldOptions.JSType;
/** FieldOptions lazy. */
public lazy: boolean;
/** FieldOptions deprecated. */
public deprecated: boolean;
/** FieldOptions weak. */
public weak: boolean;
/** FieldOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new FieldOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns FieldOptions instance
*/
public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions;
/**
* Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages.
* @param message FieldOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages.
* @param message FieldOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a FieldOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns FieldOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions;
/**
* Decodes a FieldOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns FieldOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions;
/**
* Verifies a FieldOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a FieldOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns FieldOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions;
/**
* Creates a plain object from a FieldOptions message. Also converts values to other types if specified.
* @param message FieldOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this FieldOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace FieldOptions {
/** CType enum. */
enum CType {
STRING = 0,
CORD = 1,
STRING_PIECE = 2
}
/** JSType enum. */
enum JSType {
JS_NORMAL = 0,
JS_STRING = 1,
JS_NUMBER = 2
}
}
/** Properties of an OneofOptions. */
interface IOneofOptions {
/** OneofOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an OneofOptions. */
class OneofOptions implements IOneofOptions {
/**
* Constructs a new OneofOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IOneofOptions);
/** OneofOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new OneofOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns OneofOptions instance
*/
public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions;
/**
* Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages.
* @param message OneofOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages.
* @param message OneofOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OneofOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OneofOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions;
/**
* Decodes an OneofOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OneofOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions;
/**
* Verifies an OneofOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OneofOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OneofOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions;
/**
* Creates a plain object from an OneofOptions message. Also converts values to other types if specified.
* @param message OneofOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OneofOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EnumOptions. */
interface IEnumOptions {
/** EnumOptions allowAlias */
allowAlias?: (boolean|null);
/** EnumOptions deprecated */
deprecated?: (boolean|null);
/** EnumOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an EnumOptions. */
class EnumOptions implements IEnumOptions {
/**
* Constructs a new EnumOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumOptions);
/** EnumOptions allowAlias. */
public allowAlias: boolean;
/** EnumOptions deprecated. */
public deprecated: boolean;
/** EnumOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new EnumOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumOptions instance
*/
public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions;
/**
* Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages.
* @param message EnumOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages.
* @param message EnumOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions;
/**
* Decodes an EnumOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions;
/**
* Verifies an EnumOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions;
/**
* Creates a plain object from an EnumOptions message. Also converts values to other types if specified.
* @param message EnumOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EnumValueOptions. */
interface IEnumValueOptions {
/** EnumValueOptions deprecated */
deprecated?: (boolean|null);
/** EnumValueOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents an EnumValueOptions. */
class EnumValueOptions implements IEnumValueOptions {
/**
* Constructs a new EnumValueOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEnumValueOptions);
/** EnumValueOptions deprecated. */
public deprecated: boolean;
/** EnumValueOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new EnumValueOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns EnumValueOptions instance
*/
public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions;
/**
* Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages.
* @param message EnumValueOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages.
* @param message EnumValueOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EnumValueOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EnumValueOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions;
/**
* Decodes an EnumValueOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EnumValueOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions;
/**
* Verifies an EnumValueOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EnumValueOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions;
/**
* Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified.
* @param message EnumValueOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EnumValueOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ServiceOptions. */
interface IServiceOptions {
/** ServiceOptions deprecated */
deprecated?: (boolean|null);
/** ServiceOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
}
/** Represents a ServiceOptions. */
class ServiceOptions implements IServiceOptions {
/**
* Constructs a new ServiceOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IServiceOptions);
/** ServiceOptions deprecated. */
public deprecated: boolean;
/** ServiceOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new ServiceOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns ServiceOptions instance
*/
public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions;
/**
* Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages.
* @param message ServiceOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages.
* @param message ServiceOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ServiceOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ServiceOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions;
/**
* Decodes a ServiceOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ServiceOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions;
/**
* Verifies a ServiceOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ServiceOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions;
/**
* Creates a plain object from a ServiceOptions message. Also converts values to other types if specified.
* @param message ServiceOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ServiceOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a MethodOptions. */
interface IMethodOptions {
/** MethodOptions deprecated */
deprecated?: (boolean|null);
/** MethodOptions idempotencyLevel */
idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null);
/** MethodOptions uninterpretedOption */
uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null);
/** MethodOptions .google.longrunning.operationInfo */
".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null);
/** MethodOptions .google.api.http */
".google.api.http"?: (google.api.IHttpRule|null);
}
/** Represents a MethodOptions. */
class MethodOptions implements IMethodOptions {
/**
* Constructs a new MethodOptions.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IMethodOptions);
/** MethodOptions deprecated. */
public deprecated: boolean;
/** MethodOptions idempotencyLevel. */
public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel;
/** MethodOptions uninterpretedOption. */
public uninterpretedOption: google.protobuf.IUninterpretedOption[];
/**
* Creates a new MethodOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns MethodOptions instance
*/
public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions;
/**
* Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages.
* @param message MethodOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages.
* @param message MethodOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MethodOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MethodOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions;
/**
* Decodes a MethodOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MethodOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions;
/**
* Verifies a MethodOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MethodOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MethodOptions
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions;
/**
* Creates a plain object from a MethodOptions message. Also converts values to other types if specified.
* @param message MethodOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MethodOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace MethodOptions {
/** IdempotencyLevel enum. */
enum IdempotencyLevel {
IDEMPOTENCY_UNKNOWN = 0,
NO_SIDE_EFFECTS = 1,
IDEMPOTENT = 2
}
}
/** Properties of an UninterpretedOption. */
interface IUninterpretedOption {
/** UninterpretedOption name */
name?: (google.protobuf.UninterpretedOption.INamePart[]|null);
/** UninterpretedOption identifierValue */
identifierValue?: (string|null);
/** UninterpretedOption positiveIntValue */
positiveIntValue?: (number|Long|null);
/** UninterpretedOption negativeIntValue */
negativeIntValue?: (number|Long|null);
/** UninterpretedOption doubleValue */
doubleValue?: (number|null);
/** UninterpretedOption stringValue */
stringValue?: (Uint8Array|null);
/** UninterpretedOption aggregateValue */
aggregateValue?: (string|null);
}
/** Represents an UninterpretedOption. */
class UninterpretedOption implements IUninterpretedOption {
/**
* Constructs a new UninterpretedOption.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IUninterpretedOption);
/** UninterpretedOption name. */
public name: google.protobuf.UninterpretedOption.INamePart[];
/** UninterpretedOption identifierValue. */
public identifierValue: string;
/** UninterpretedOption positiveIntValue. */
public positiveIntValue: (number|Long);
/** UninterpretedOption negativeIntValue. */
public negativeIntValue: (number|Long);
/** UninterpretedOption doubleValue. */
public doubleValue: number;
/** UninterpretedOption stringValue. */
public stringValue: Uint8Array;
/** UninterpretedOption aggregateValue. */
public aggregateValue: string;
/**
* Creates a new UninterpretedOption instance using the specified properties.
* @param [properties] Properties to set
* @returns UninterpretedOption instance
*/
public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption;
/**
* Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages.
* @param message UninterpretedOption message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages.
* @param message UninterpretedOption message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an UninterpretedOption message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UninterpretedOption
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption;
/**
* Decodes an UninterpretedOption message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UninterpretedOption
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption;
/**
* Verifies an UninterpretedOption message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UninterpretedOption
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption;
/**
* Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified.
* @param message UninterpretedOption
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UninterpretedOption to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace UninterpretedOption {
/** Properties of a NamePart. */
interface INamePart {
/** NamePart namePart */
namePart: string;
/** NamePart isExtension */
isExtension: boolean;
}
/** Represents a NamePart. */
class NamePart implements INamePart {
/**
* Constructs a new NamePart.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.UninterpretedOption.INamePart);
/** NamePart namePart. */
public namePart: string;
/** NamePart isExtension. */
public isExtension: boolean;
/**
* Creates a new NamePart instance using the specified properties.
* @param [properties] Properties to set
* @returns NamePart instance
*/
public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart;
/**
* Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages.
* @param message NamePart message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages.
* @param message NamePart message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NamePart message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NamePart
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart;
/**
* Decodes a NamePart message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NamePart
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart;
/**
* Verifies a NamePart message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NamePart message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NamePart
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart;
/**
* Creates a plain object from a NamePart message. Also converts values to other types if specified.
* @param message NamePart
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NamePart to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a SourceCodeInfo. */
interface ISourceCodeInfo {
/** SourceCodeInfo location */
location?: (google.protobuf.SourceCodeInfo.ILocation[]|null);
}
/** Represents a SourceCodeInfo. */
class SourceCodeInfo implements ISourceCodeInfo {
/**
* Constructs a new SourceCodeInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.ISourceCodeInfo);
/** SourceCodeInfo location. */
public location: google.protobuf.SourceCodeInfo.ILocation[];
/**
* Creates a new SourceCodeInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns SourceCodeInfo instance
*/
public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo;
/**
* Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages.
* @param message SourceCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages.
* @param message SourceCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SourceCodeInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SourceCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo;
/**
* Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SourceCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo;
/**
* Verifies a SourceCodeInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SourceCodeInfo
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo;
/**
* Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified.
* @param message SourceCodeInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SourceCodeInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace SourceCodeInfo {
/** Properties of a Location. */
interface ILocation {
/** Location path */
path?: (number[]|null);
/** Location span */
span?: (number[]|null);
/** Location leadingComments */
leadingComments?: (string|null);
/** Location trailingComments */
trailingComments?: (string|null);
/** Location leadingDetachedComments */
leadingDetachedComments?: (string[]|null);
}
/** Represents a Location. */
class Location implements ILocation {
/**
* Constructs a new Location.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.SourceCodeInfo.ILocation);
/** Location path. */
public path: number[];
/** Location span. */
public span: number[];
/** Location leadingComments. */
public leadingComments: string;
/** Location trailingComments. */
public trailingComments: string;
/** Location leadingDetachedComments. */
public leadingDetachedComments: string[];
/**
* Creates a new Location instance using the specified properties.
* @param [properties] Properties to set
* @returns Location instance
*/
public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location;
/**
* Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages.
* @param message Location message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages.
* @param message Location message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Location message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Location
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location;
/**
* Decodes a Location message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Location
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location;
/**
* Verifies a Location message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Location message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Location
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location;
/**
* Creates a plain object from a Location message. Also converts values to other types if specified.
* @param message Location
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Location to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a GeneratedCodeInfo. */
interface IGeneratedCodeInfo {
/** GeneratedCodeInfo annotation */
annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null);
}
/** Represents a GeneratedCodeInfo. */
class GeneratedCodeInfo implements IGeneratedCodeInfo {
/**
* Constructs a new GeneratedCodeInfo.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IGeneratedCodeInfo);
/** GeneratedCodeInfo annotation. */
public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[];
/**
* Creates a new GeneratedCodeInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns GeneratedCodeInfo instance
*/
public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo;
/**
* Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages.
* @param message GeneratedCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages.
* @param message GeneratedCodeInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GeneratedCodeInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GeneratedCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo;
/**
* Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GeneratedCodeInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo;
/**
* Verifies a GeneratedCodeInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GeneratedCodeInfo
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo;
/**
* Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified.
* @param message GeneratedCodeInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GeneratedCodeInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace GeneratedCodeInfo {
/** Properties of an Annotation. */
interface IAnnotation {
/** Annotation path */
path?: (number[]|null);
/** Annotation sourceFile */
sourceFile?: (string|null);
/** Annotation begin */
begin?: (number|null);
/** Annotation end */
end?: (number|null);
}
/** Represents an Annotation. */
class Annotation implements IAnnotation {
/**
* Constructs a new Annotation.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation);
/** Annotation path. */
public path: number[];
/** Annotation sourceFile. */
public sourceFile: string;
/** Annotation begin. */
public begin: number;
/** Annotation end. */
public end: number;
/**
* Creates a new Annotation instance using the specified properties.
* @param [properties] Properties to set
* @returns Annotation instance
*/
public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages.
* @param message Annotation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages.
* @param message Annotation message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Annotation message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Annotation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Decodes an Annotation message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Annotation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Verifies an Annotation message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Annotation message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Annotation
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation;
/**
* Creates a plain object from an Annotation message. Also converts values to other types if specified.
* @param message Annotation
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Annotation to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an Any. */
interface IAny {
/** Any type_url */
type_url?: (string|null);
/** Any value */
value?: (Uint8Array|null);
}
/** Represents an Any. */
class Any implements IAny {
/**
* Constructs a new Any.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IAny);
/** Any type_url. */
public type_url: string;
/** Any value. */
public value: Uint8Array;
/**
* Creates a new Any instance using the specified properties.
* @param [properties] Properties to set
* @returns Any instance
*/
public static create(properties?: google.protobuf.IAny): google.protobuf.Any;
/**
* Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Any message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any;
/**
* Decodes an Any message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any;
/**
* Verifies an Any message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Any message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Any
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Any;
/**
* Creates a plain object from an Any message. Also converts values to other types if specified.
* @param message Any
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Any to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Duration. */
interface IDuration {
/** Duration seconds */
seconds?: (number|Long|null);
/** Duration nanos */
nanos?: (number|null);
}
/** Represents a Duration. */
class Duration implements IDuration {
/**
* Constructs a new Duration.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IDuration);
/** Duration seconds. */
public seconds: (number|Long);
/** Duration nanos. */
public nanos: number;
/**
* Creates a new Duration instance using the specified properties.
* @param [properties] Properties to set
* @returns Duration instance
*/
public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration;
/**
* Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages.
* @param message Duration message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages.
* @param message Duration message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Duration message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Duration
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Duration;
/**
* Decodes a Duration message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Duration
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Duration;
/**
* Verifies a Duration message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Duration message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Duration
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Duration;
/**
* Creates a plain object from a Duration message. Also converts values to other types if specified.
* @param message Duration
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Duration to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Empty. */
interface IEmpty {
}
/** Represents an Empty. */
class Empty implements IEmpty {
/**
* Constructs a new Empty.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEmpty);
/**
* Creates a new Empty instance using the specified properties.
* @param [properties] Properties to set
* @returns Empty instance
*/
public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty;
/**
* Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @param message Empty message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @param message Empty message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Empty message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty;
/**
* Decodes an Empty message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty;
/**
* Verifies an Empty message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Empty message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Empty
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Empty;
/**
* Creates a plain object from an Empty message. Also converts values to other types if specified.
* @param message Empty
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Empty to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace rpc. */
namespace rpc {
/** Properties of a Status. */
interface IStatus {
/** Status code */
code?: (number|null);
/** Status message */
message?: (string|null);
/** Status details */
details?: (google.protobuf.IAny[]|null);
}
/** Represents a Status. */
class Status implements IStatus {
/**
* Constructs a new Status.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IStatus);
/** Status code. */
public code: number;
/** Status message. */
public message: string;
/** Status details. */
public details: google.protobuf.IAny[];
/**
* Creates a new Status instance using the specified properties.
* @param [properties] Properties to set
* @returns Status instance
*/
public static create(properties?: google.rpc.IStatus): google.rpc.Status;
/**
* Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages.
* @param message Status message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages.
* @param message Status message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Status message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status;
/**
* Decodes a Status message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status;
/**
* Verifies a Status message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Status message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Status
*/
public static fromObject(object: { [k: string]: any }): google.rpc.Status;
/**
* Creates a plain object from a Status message. Also converts values to other types if specified.
* @param message Status
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Status to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
} | the_stack |
import { Page } from 'puppeteer';
import { CreateConfig } from '../../config/create-config';
import { Id } from '../model';
import { RetrieverLayer } from './retriever.layer';
import { Scope, checkValuesSender } from '../helpers/layers-interface';
import {
base64MimeType,
fileToBase64,
downloadFileToBase64,
resizeImg
} from '../helpers';
import { GroupSettings } from '../model/enum';
let obj: Scope;
export class GroupLayer extends RetrieverLayer {
constructor(public page: Page, session?: string, options?: CreateConfig) {
super(page, session, options);
}
/**
* Parameters to change group image
* @param {string} groupId group number
* @param {string} path of image
*/
public async setGroupImage(groupId: string, path: string) {
let b64 = await downloadFileToBase64(path, [
'image/gif',
'image/png',
'image/jpg',
'image/jpeg',
'image/webp'
]);
if (!b64) {
b64 = await fileToBase64(path);
}
if (b64) {
const buff = Buffer.from(
b64.replace(/^data:image\/(png|jpe?g|webp);base64,/, ''),
'base64'
);
const mimeInfo = base64MimeType(b64);
if (!mimeInfo || mimeInfo.includes('image')) {
let _webb64_96 = await resizeImg(buff, { width: 96, height: 96 }),
_webb64_640 = await resizeImg(buff, { width: 640, height: 640 });
let obj = { a: _webb64_640, b: _webb64_96 };
return await this.page.evaluate(
({ obj, groupId }) => WAPI.setProfilePic(obj, groupId),
{
obj,
groupId
}
);
} else {
console.log('Not an image, allowed formats png, jpeg and webp');
return false;
}
}
}
/**
* Parameters to change group title
* @param {string} groupId group number
* @param {string} title group title
*/
public async setGroupTitle(groupId: string, title: string): Promise<Object> {
return new Promise(async (resolve, reject) => {
const typeFunction = 'setGroupTitle';
const type = 'string';
const check = [
{
param: 'groupId',
type: type,
value: groupId,
function: typeFunction,
isUser: true
},
{
param: 'title',
type: type,
value: title,
function: typeFunction,
isUser: true
}
];
const validating = checkValuesSender(check);
if (typeof validating === 'object') {
return reject(validating);
}
const result = await this.page.evaluate(
({ groupId, title }) => {
return WAPI.setGroupTitle(groupId, title);
},
{ groupId, title }
);
if (result['erro'] == true) {
return reject(result);
} else {
return resolve(result);
}
});
}
/**
* Parameters to change group description
* @param {string} groupId group number
* @param {string} description group description
*/
public async setGroupDescription(
groupId: string,
description: string
): Promise<Object> {
return new Promise(async (resolve, reject) => {
const typeFunction = 'setGroupDescription';
const type = 'string';
const check = [
{
param: 'groupId',
type: type,
value: groupId,
function: typeFunction,
isUser: true
},
{
param: 'description',
type: type,
value: description,
function: typeFunction,
isUser: true
}
];
const validating = checkValuesSender(check);
if (typeof validating === 'object') {
return reject(validating);
}
const result = await this.page.evaluate(
({ groupId, description }) => {
return WAPI.setGroupDescription(groupId, description);
},
{ groupId, description }
);
if (result['erro'] == true) {
return reject(result);
} else {
return resolve(result);
}
});
}
/**
* Parameters to change group settings, see {@link GroupSettings for details}
* @param {string} groupId group number
* @param {GroupSettings} settings
* @param {boolean} value
*/
public async setGroupSettings(
groupId: string,
settings: GroupSettings,
value: boolean
): Promise<Object> {
return new Promise(async (resolve, reject) => {
const typeFunction = 'setGroupSettings';
const type = 'string';
const check = [
{
param: 'groupId',
type: type,
value: groupId,
function: typeFunction,
isUser: true
},
{
param: 'settings',
type: type,
value: settings,
function: typeFunction,
isUser: true
},
{
param: 'value',
type: type,
value: value,
function: typeFunction,
isUser: true
}
];
const validating = checkValuesSender(check);
if (typeof validating === 'object') {
return reject(validating);
}
const result = await this.page.evaluate(
({ groupId, settings, value }) => {
return WAPI.setGroupSettings(groupId, settings, value);
},
{ groupId, settings, value }
);
if (result['erro'] == true) {
return reject(result);
} else {
return resolve(result);
}
});
}
/**
* Retrieve all groups
* @returns array of groups
* @param groupId Chat id ('0000000000-00000000@g.us')
*/
public async getAllChatsGroups(groupId: string) {
return await this.page.evaluate(() => {
const chats = WAPI.getAllChats();
return !groupId && !groupId.length && typeof groupId === 'string'
? chats.filter((chat) => chat.kind === 'group')
: chats.filter(
(chat) => chat.kind === 'group' && groupId === chat.id._serialized
);
});
}
/**
* Retrieve all groups new messages
* @returns array of groups
*/
public async getChatGroupNewMsg() {
return await this.page.evaluate(() => {
let chats = WAPI.getAllChatsWithNewMsg();
return chats.filter((chat) => chat.kind === 'group');
});
}
/**
* Removes the host device from the group
* @param groupId group id
*/
public async leaveGroup(groupId: string) {
return this.page.evaluate((groupId) => WAPI.leaveGroup(groupId), groupId);
}
/**
* Retrieves group members as [Id] objects
* @param groupId group id
*/
public async getGroupMembersIds(groupId: string): Promise<Id[]> {
return this.page.evaluate(
(groupId: string) => WAPI.getGroupParticipantIDs(groupId),
groupId
);
}
/**
* Returns group members [Contact] objects
* @param groupId
*/
public async getGroupMembers(groupId: string) {
const membersIds = await this.getGroupMembersIds(groupId);
const actions = membersIds.map((memberId) => {
return this.getContact(memberId._serialized);
});
return Promise.all(actions);
}
/**
* Reset group invitation link
* @param chatId
* @returns boolean
*/
public async revokeGroupInviteLink(chatId: string) {
return await this.page.evaluate(
(chatId) => WAPI.revokeGroupInviteLink(chatId),
chatId
);
}
/**
* Generates group-invite link
* @param chatId
* @returns Invitation link
*/
public async getGroupInviteLink(chatId: string) {
return await this.page.evaluate(
(chatId) => WAPI.getGroupInviteLink(chatId),
chatId
);
}
/**
* Generates group-invite link
* @param inviteCode
* @returns Invite code from group link. Example: CMJYfPFqRyE2GxrnkldYED
*/
public async getGroupInfoFromInviteLink(inviteCode: string) {
inviteCode = inviteCode.replace('chat.whatsapp.com/', '');
inviteCode = inviteCode.replace('invite/', '');
inviteCode = inviteCode.replace('https://', '');
inviteCode = inviteCode.replace('http://', '');
return await this.page.evaluate(
(inviteCode) => WAPI.getGroupInfoFromInviteLink(inviteCode),
inviteCode
);
}
/**
* Creates a new chat group
* @param groupName Group name
* @param contacts Contacts that should be added.
*/
public async createGroup(groupName: string, contacts: string | string[]) {
return await this.page.evaluate(
({ groupName, contacts }) => WAPI.createGroup(groupName, contacts),
{ groupName, contacts }
);
}
/**
* Removes participant from group
* @param groupId Chat id ('0000000000-00000000@g.us')
* @param participantId Participant id'000000000000@c.us'
*/
public async removeParticipant(
groupId: string,
participantId: string | string[]
) {
return await this.page.evaluate(
({ groupId, participantId }) =>
WAPI.removeParticipant(groupId, participantId),
{ groupId, participantId }
);
}
/**
* Adds participant to Group
* @param groupId Chat id ('0000000000-00000000@g.us')
* @param participantId Participant id'000000000000@c.us'
*/
public async addParticipant(
groupId: string,
participantId: string | string[]
) {
return await this.page.evaluate(
({ groupId, participantId }) =>
WAPI.addParticipant(groupId, participantId),
{ groupId, participantId }
);
}
/**
* Promotes participant as Admin in given group
* @param groupId Chat id ('0000000000-00000000@g.us')
* @param participantId Participant id'000000000000@c.us'
*/
public async promoteParticipant(
groupId: string,
participantId: string | string[]
) {
return await this.page.evaluate(
({ groupId, participantId }) =>
WAPI.promoteParticipant(groupId, participantId),
{ groupId, participantId }
);
}
/**
* Demotes admin privileges of participant
* @param groupId Chat id ('0000000000-00000000@g.us')
* @param participantId Participant id'000000000000@c.us'
*/
public async demoteParticipant(
groupId: string,
participantId: string | string[]
) {
return await this.page.evaluate(
({ groupId, participantId }) =>
WAPI.demoteParticipant(groupId, participantId),
{ groupId, participantId }
);
}
/**
* Retrieves group admins
* @param chatId Group/Chat id ('0000000000-00000000@g.us')
*/
public async getGroupAdmins(chatId: string) {
return await this.page.evaluate(
(chatId) => WAPI.getGroupAdmins(chatId),
chatId
);
}
/**
* Join a group with invite code
* @param inviteCode
*/
public async joinGroup(inviteCode: string) {
inviteCode = inviteCode.replace('chat.whatsapp.com/', '');
inviteCode = inviteCode.replace('invite/', '');
inviteCode = inviteCode.replace('https://', '');
inviteCode = inviteCode.replace('http://', '');
return await this.page.evaluate(
(inviteCode) => WAPI.joinGroup(inviteCode),
inviteCode
);
}
} | the_stack |
import { HardhatRuntimeEnvironment } from "hardhat/types";
import { DeployFunction } from "hardhat-deploy/types";
import { ethers, upgrades, network } from "hardhat";
import {
PancakeswapV2RestrictedStrategyAddBaseTokenOnly__factory,
PancakeswapV2RestrictedStrategyAddTwoSidesOptimal__factory,
PancakeswapV2RestrictedStrategyLiquidate__factory,
PancakeswapV2RestrictedStrategyWithdrawMinimizeTrading__factory,
Timelock__factory,
WaultSwapRestrictedStrategyAddBaseTokenOnly,
WaultSwapRestrictedStrategyAddBaseTokenOnly__factory,
WaultSwapRestrictedStrategyAddTwoSidesOptimal,
WaultSwapRestrictedStrategyAddTwoSidesOptimal__factory,
WaultSwapRestrictedStrategyLiquidate__factory,
WaultSwapRestrictedStrategyPartialCloseLiquidate__factory,
WaultSwapRestrictedStrategyPartialCloseMinimizeTrading__factory,
WaultSwapRestrictedStrategyWithdrawMinimizeTrading__factory,
WaultSwapWorker02,
WaultSwapWorker02__factory,
} from "../../../../typechain";
import { ConfigEntity } from "../../../entities";
interface IWorkerInput {
VAULT_SYMBOL: string;
WORKER_NAME: string;
REINVEST_BOT: string;
POOL_ID: number;
REINVEST_BOUNTY_BPS: string;
REINVEST_PATH: Array<string>;
REINVEST_THRESHOLD: string;
WORK_FACTOR: string;
KILL_FACTOR: string;
MAX_PRICE_DIFF: string;
EXACT_ETA: string;
}
interface IWaultWorkerInfo {
WORKER_NAME: string;
VAULT_CONFIG_ADDR: string;
WORKER_CONFIG_ADDR: string;
REINVEST_BOT: string;
POOL_ID: number;
VAULT_ADDR: string;
BASE_TOKEN_ADDR: string;
MASTER_CHEF_ADDR: string;
WSWAP_ROUTER_ADDR: string;
ADD_STRAT_ADDR: string;
LIQ_STRAT_ADDR: string;
TWO_SIDES_STRAT_ADDR: string;
MINIMIZE_TRADE_STRAT_ADDR: string;
PARTIAL_CLOSE_LIQ_ADDR: string;
PARTIAL_CLOSE_MINIMIZE_ADDR: string;
REINVEST_BOUNTY_BPS: string;
REINVEST_PATH: Array<string>;
REINVEST_THRESHOLD: string;
WORK_FACTOR: string;
KILL_FACTOR: string;
MAX_PRICE_DIFF: string;
TIMELOCK: string;
EXACT_ETA: string;
}
const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
/*
░██╗░░░░░░░██╗░█████╗░██████╗░███╗░░██╗██╗███╗░░██╗░██████╗░
░██║░░██╗░░██║██╔══██╗██╔══██╗████╗░██║██║████╗░██║██╔════╝░
░╚██╗████╗██╔╝███████║██████╔╝██╔██╗██║██║██╔██╗██║██║░░██╗░
░░████╔═████║░██╔══██║██╔══██╗██║╚████║██║██║╚████║██║░░╚██╗
░░╚██╔╝░╚██╔╝░██║░░██║██║░░██║██║░╚███║██║██║░╚███║╚██████╔╝
░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚══╝╚═╝╚═╝░░╚══╝░╚═════╝░
Check all variables below before execute the deployment script
*/
const shortWorkerInfos: IWorkerInput[] = [
{
VAULT_SYMBOL: "ibBUSD",
WORKER_NAME: "WUSD-BUSD WaultswapWorker",
REINVEST_BOT: "0xe45216Ac4816A5Ec5378B1D13dE8aA9F262ce9De",
POOL_ID: 58,
REINVEST_BOUNTY_BPS: "300",
REINVEST_PATH: ["WEX", "WBNB", "BUSD"],
REINVEST_THRESHOLD: "2000",
WORK_FACTOR: "7800",
KILL_FACTOR: "9000",
MAX_PRICE_DIFF: "10500",
EXACT_ETA: "1630467000",
},
];
const config = ConfigEntity.getConfig();
const workerInfos: IWaultWorkerInfo[] = shortWorkerInfos.map((n) => {
const vault = config.Vaults.find((v) => v.symbol === n.VAULT_SYMBOL);
if (vault === undefined) {
throw `error: unable to find vault from ${n.VAULT_SYMBOL}`;
}
const tokenList: any = config.Tokens;
const reinvestPath: Array<string> = n.REINVEST_PATH.map((p) => {
const addr = tokenList[p];
if (addr === undefined) {
throw `error: path: unable to find address of ${p}`;
}
return addr;
});
return {
WORKER_NAME: n.WORKER_NAME,
VAULT_CONFIG_ADDR: vault.config,
WORKER_CONFIG_ADDR: config.SharedConfig.WorkerConfig,
REINVEST_BOT: n.REINVEST_BOT,
POOL_ID: n.POOL_ID,
VAULT_ADDR: vault.address,
BASE_TOKEN_ADDR: vault.baseToken,
MASTER_CHEF_ADDR: config.Exchanges.Waultswap.WexMaster,
WSWAP_ROUTER_ADDR: config.Exchanges.Waultswap.WaultswapRouter,
ADD_STRAT_ADDR: config.SharedStrategies.Waultswap.StrategyAddBaseTokenOnly,
LIQ_STRAT_ADDR: config.SharedStrategies.Waultswap.StrategyLiquidate,
TWO_SIDES_STRAT_ADDR: vault.StrategyAddTwoSidesOptimal.Waultswap,
MINIMIZE_TRADE_STRAT_ADDR: config.SharedStrategies.Waultswap.StrategyWithdrawMinimizeTrading,
PARTIAL_CLOSE_LIQ_ADDR: config.SharedStrategies.Waultswap.StrategyPartialCloseLiquidate,
PARTIAL_CLOSE_MINIMIZE_ADDR: config.SharedStrategies.Waultswap.StrategyPartialCloseMinimizeTrading,
REINVEST_BOUNTY_BPS: n.REINVEST_BOUNTY_BPS,
REINVEST_PATH: reinvestPath,
REINVEST_THRESHOLD: ethers.utils.parseEther(n.REINVEST_THRESHOLD).toString(),
WORK_FACTOR: n.WORK_FACTOR,
KILL_FACTOR: n.KILL_FACTOR,
MAX_PRICE_DIFF: n.MAX_PRICE_DIFF,
TIMELOCK: config.Timelock,
EXACT_ETA: n.EXACT_ETA,
};
});
for (let i = 0; i < workerInfos.length; i++) {
console.log("===================================================================================");
console.log(`>> Deploying an upgradable WaultSwapWorker02 contract for ${workerInfos[i].WORKER_NAME}`);
const WaultSwapWorker02 = (await ethers.getContractFactory(
"WaultSwapWorker02",
(
await ethers.getSigners()
)[0]
)) as WaultSwapWorker02__factory;
const waultswapWorker02 = (await upgrades.deployProxy(WaultSwapWorker02, [
workerInfos[i].VAULT_ADDR,
workerInfos[i].BASE_TOKEN_ADDR,
workerInfos[i].MASTER_CHEF_ADDR,
workerInfos[i].WSWAP_ROUTER_ADDR,
workerInfos[i].POOL_ID,
workerInfos[i].ADD_STRAT_ADDR,
workerInfos[i].LIQ_STRAT_ADDR,
workerInfos[i].REINVEST_BOUNTY_BPS,
workerInfos[i].REINVEST_BOT,
workerInfos[i].REINVEST_PATH,
workerInfos[i].REINVEST_THRESHOLD,
])) as WaultSwapWorker02;
await waultswapWorker02.deployed();
console.log(`>> Deployed at ${waultswapWorker02.address}`);
console.log(`>> Adding REINVEST_BOT`);
await waultswapWorker02.setReinvestorOk([workerInfos[i].REINVEST_BOT], true);
console.log("✅ Done");
console.log(`>> Adding Strategies`);
await waultswapWorker02.setStrategyOk(
[
workerInfos[i].TWO_SIDES_STRAT_ADDR,
workerInfos[i].MINIMIZE_TRADE_STRAT_ADDR,
workerInfos[i].PARTIAL_CLOSE_LIQ_ADDR,
workerInfos[i].PARTIAL_CLOSE_MINIMIZE_ADDR,
],
true
);
console.log("✅ Done");
console.log(`>> Whitelisting a worker on strats`);
const addStrat = WaultSwapRestrictedStrategyAddBaseTokenOnly__factory.connect(
workerInfos[i].ADD_STRAT_ADDR,
(await ethers.getSigners())[0]
);
await addStrat.setWorkersOk([waultswapWorker02.address], true);
const liqStrat = WaultSwapRestrictedStrategyLiquidate__factory.connect(
workerInfos[i].LIQ_STRAT_ADDR,
(await ethers.getSigners())[0]
);
await liqStrat.setWorkersOk([waultswapWorker02.address], true);
const twoSidesStrat = WaultSwapRestrictedStrategyAddTwoSidesOptimal__factory.connect(
workerInfos[i].TWO_SIDES_STRAT_ADDR,
(await ethers.getSigners())[0]
);
await twoSidesStrat.setWorkersOk([waultswapWorker02.address], true);
const minimizeStrat = WaultSwapRestrictedStrategyWithdrawMinimizeTrading__factory.connect(
workerInfos[i].MINIMIZE_TRADE_STRAT_ADDR,
(await ethers.getSigners())[0]
);
await minimizeStrat.setWorkersOk([waultswapWorker02.address], true);
if (workerInfos[i].PARTIAL_CLOSE_LIQ_ADDR != "") {
console.log(">> partial close liquidate is deployed");
const partialCloseLiquidate = WaultSwapRestrictedStrategyPartialCloseLiquidate__factory.connect(
workerInfos[i].PARTIAL_CLOSE_LIQ_ADDR,
(await ethers.getSigners())[0]
);
await partialCloseLiquidate.setWorkersOk([waultswapWorker02.address], true);
}
if (workerInfos[i].PARTIAL_CLOSE_MINIMIZE_ADDR != "") {
console.log(">> partial close liquidate is deployed");
const partialCloseMinimize = WaultSwapRestrictedStrategyPartialCloseMinimizeTrading__factory.connect(
workerInfos[i].PARTIAL_CLOSE_MINIMIZE_ADDR,
(await ethers.getSigners())[0]
);
await partialCloseMinimize.setWorkersOk([waultswapWorker02.address], true);
}
console.log("✅ Done");
const timelock = Timelock__factory.connect(workerInfos[i].TIMELOCK, (await ethers.getSigners())[0]);
console.log(">> Timelock: Setting WorkerConfig via Timelock");
const setConfigsTx = await timelock.queueTransaction(
workerInfos[i].WORKER_CONFIG_ADDR,
"0",
"setConfigs(address[],(bool,uint64,uint64,uint64)[])",
ethers.utils.defaultAbiCoder.encode(
["address[]", "(bool acceptDebt,uint64 workFactor,uint64 killFactor,uint64 maxPriceDiff)[]"],
[
[waultswapWorker02.address],
[
{
acceptDebt: true,
workFactor: workerInfos[i].WORK_FACTOR,
killFactor: workerInfos[i].KILL_FACTOR,
maxPriceDiff: workerInfos[i].MAX_PRICE_DIFF,
},
],
]
),
workerInfos[i].EXACT_ETA
);
console.log(`queue setConfigs at: ${setConfigsTx.hash}`);
console.log("generate timelock.executeTransaction:");
console.log(
`await timelock.executeTransaction('${workerInfos[i].WORKER_CONFIG_ADDR}', '0', 'setConfigs(address[],(bool,uint64,uint64,uint64)[])', ethers.utils.defaultAbiCoder.encode(['address[]','(bool acceptDebt,uint64 workFactor,uint64 killFactor,uint64 maxPriceDiff)[]'],[['${waultswapWorker02.address}'], [{acceptDebt: true, workFactor: ${workerInfos[i].WORK_FACTOR}, killFactor: ${workerInfos[i].KILL_FACTOR}, maxPriceDiff: ${workerInfos[i].MAX_PRICE_DIFF}}]]), ${workerInfos[i].EXACT_ETA})`
);
console.log("✅ Done");
console.log(">> Timelock: Linking VaultConfig with WorkerConfig via Timelock");
const setWorkersTx = await timelock.queueTransaction(
workerInfos[i].VAULT_CONFIG_ADDR,
"0",
"setWorkers(address[],address[])",
ethers.utils.defaultAbiCoder.encode(
["address[]", "address[]"],
[[waultswapWorker02.address], [workerInfos[i].WORKER_CONFIG_ADDR]]
),
workerInfos[i].EXACT_ETA
);
console.log(`queue setWorkers at: ${setWorkersTx.hash}`);
console.log("generate timelock.executeTransaction:");
console.log(
`await timelock.executeTransaction('${workerInfos[i].VAULT_CONFIG_ADDR}', '0','setWorkers(address[],address[])', ethers.utils.defaultAbiCoder.encode(['address[]','address[]'],[['${waultswapWorker02.address}'], ['${workerInfos[i].WORKER_CONFIG_ADDR}']]), ${workerInfos[i].EXACT_ETA})`
);
console.log("✅ Done");
}
};
export default func;
func.tags = ["WaultSwapWorkers02"]; | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import { isNumber, times, identity, random } from 'lodash';
import angular, { IRootScopeService, IScope, ICompileService } from 'angular';
import $ from 'jquery';
import 'angular-sanitize';
import 'angular-mocks';
import { getAngularModule } from '../get_inner_angular';
import { initTableVisLegacyModule } from '../table_vis_legacy_module';
import { coreMock } from '../../../../core/public/mocks';
jest.mock('../../../opensearch_dashboards_legacy/public/angular/angular_config', () => ({
configureAppAngularModule: () => {},
}));
interface Sort {
columnIndex: number;
direction: string;
}
interface Row {
[key: string]: number | string;
}
interface Column {
id?: string;
title: string;
formatter?: {
convert?: (val: string) => string;
};
sortable?: boolean;
}
interface Table {
columns: Column[];
rows: Row[];
}
interface PaginatedTableScope extends IScope {
table?: Table;
cols?: Column[];
rows?: Row[];
perPage?: number;
sort?: Sort;
linkToTop?: boolean;
}
describe('Table Vis - Paginated table', () => {
let $el: JQuery<Element>;
let $rootScope: IRootScopeService;
let $compile: ICompileService;
let $scope: PaginatedTableScope;
const defaultPerPage = 10;
let paginatedTable: any;
const initLocalAngular = () => {
const tableVisModule = getAngularModule(
'opensearch-dashboards/table_vis',
coreMock.createStart(),
coreMock.createPluginInitializerContext()
);
initTableVisLegacyModule(tableVisModule);
};
beforeEach(initLocalAngular);
beforeEach(angular.mock.module('opensearch-dashboards/table_vis'));
beforeEach(
angular.mock.inject((_$rootScope_: IRootScopeService, _$compile_: ICompileService) => {
$rootScope = _$rootScope_;
$compile = _$compile_;
$scope = $rootScope.$new();
})
);
afterEach(() => {
$scope.$destroy();
});
const makeData = (colCount: number | Column[], rowCount: number | string[][]) => {
let columns: Column[] = [];
let rows: Row[] = [];
if (isNumber(colCount)) {
times(colCount, (i) => {
columns.push({ id: `${i}`, title: `column${i}`, formatter: { convert: identity } });
});
} else {
columns = colCount.map(
(col, i) =>
({
id: `${i}`,
title: col.title,
formatter: col.formatter || { convert: identity },
} as Column)
);
}
if (isNumber(rowCount)) {
times(rowCount, (row) => {
const rowItems: Row = {};
times(columns.length, (col) => {
rowItems[`${col}`] = `item-${col}-${row}`;
});
rows.push(rowItems);
});
} else {
rows = rowCount.map((row: string[]) => {
const newRow: Row = {};
row.forEach((v, i) => (newRow[i] = v));
return newRow;
});
}
return {
columns,
rows,
};
};
const renderTable = (
table: { columns: Column[]; rows: Row[] } | null,
cols: Column[],
rows: Row[],
perPage?: number,
sort?: Sort,
linkToTop?: boolean
) => {
$scope.table = table || { columns: [], rows: [] };
$scope.cols = cols || [];
$scope.rows = rows || [];
$scope.perPage = perPage || defaultPerPage;
$scope.sort = sort;
$scope.linkToTop = linkToTop;
const template = `
<paginated-table
table="table"
columns="cols"
rows="rows"
per-page="perPage"
sort="sort"
link-to-top="linkToTop">`;
const element = $compile(template)($scope);
$el = $(element);
$scope.$digest();
paginatedTable = element.controller('paginatedTable');
};
describe('rendering', () => {
test('should not display without rows', () => {
const cols: Column[] = [
{
id: 'col-1-1',
title: 'test1',
},
];
const rows: Row[] = [];
renderTable(null, cols, rows);
expect($el.children().length).toBe(0);
});
test('should render columns and rows', () => {
const data = makeData(2, 2);
const cols = data.columns;
const rows = data.rows;
renderTable(data, cols, rows);
expect($el.children().length).toBe(1);
const tableRows = $el.find('tbody tr');
// should contain the row data
expect(tableRows.eq(0).find('td').eq(0).text()).toBe(rows[0][0]);
expect(tableRows.eq(0).find('td').eq(1).text()).toBe(rows[0][1]);
expect(tableRows.eq(1).find('td').eq(0).text()).toBe(rows[1][0]);
expect(tableRows.eq(1).find('td').eq(1).text()).toBe(rows[1][1]);
});
test('should paginate rows', () => {
// note: paginate truncates pages, so don't make too many
const rowCount = random(16, 24);
const perPageCount = random(5, 8);
const data = makeData(3, rowCount);
const pageCount = Math.ceil(rowCount / perPageCount);
renderTable(data, data.columns, data.rows, perPageCount);
const tableRows = $el.find('tbody tr');
expect(tableRows.length).toBe(perPageCount);
// add 2 for the first and last page links
expect($el.find('paginate-controls button').length).toBe(pageCount + 2);
});
test('should not show blank rows on last page', () => {
const rowCount = 7;
const perPageCount = 10;
const data = makeData(3, rowCount);
renderTable(data, data.columns, data.rows, perPageCount);
const tableRows = $el.find('tbody tr');
expect(tableRows.length).toBe(rowCount);
});
test('should not show link to top when not set', () => {
const data = makeData(5, 5);
renderTable(data, data.columns, data.rows, 10);
const linkToTop = $el.find('[data-test-subj="paginateControlsLinkToTop"]');
expect(linkToTop.length).toBe(0);
});
test('should show link to top when set', () => {
const data = makeData(5, 5);
renderTable(data, data.columns, data.rows, 10, undefined, true);
const linkToTop = $el.find('[data-test-subj="paginateControlsLinkToTop"]');
expect(linkToTop.length).toBe(1);
});
});
describe('sorting', () => {
let data: Table;
let lastRowIndex: number;
beforeEach(() => {
data = makeData(3, [
['bbbb', 'aaaa', 'zzzz'],
['cccc', 'cccc', 'aaaa'],
['zzzz', 'bbbb', 'bbbb'],
['aaaa', 'zzzz', 'cccc'],
]);
lastRowIndex = data.rows.length - 1;
renderTable(data, data.columns, data.rows);
});
test('should not sort by default', () => {
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe(data.rows[0][0]);
expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe(data.rows[lastRowIndex][0]);
});
test('should do nothing when sorting by invalid column id', () => {
// sortColumn
paginatedTable.sortColumn(999);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe('bbbb');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa');
expect(tableRows.eq(0).find('td').eq(2).text()).toBe('zzzz');
});
test('should do nothing when sorting by non sortable column', () => {
data.columns[0].sortable = false;
// sortColumn
paginatedTable.sortColumn(0);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe('bbbb');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa');
expect(tableRows.eq(0).find('td').eq(2).text()).toBe('zzzz');
});
test("should set the sort direction to asc when it's not explicitly set", () => {
paginatedTable.sortColumn(1);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(2).find('td').eq(1).text()).toBe('cccc');
expect(tableRows.eq(1).find('td').eq(1).text()).toBe('bbbb');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa');
});
test('should allow you to explicitly set the sort direction', () => {
paginatedTable.sortColumn(1, 'desc');
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('zzzz');
expect(tableRows.eq(1).find('td').eq(1).text()).toBe('cccc');
expect(tableRows.eq(2).find('td').eq(1).text()).toBe('bbbb');
});
test('should sort ascending on first invocation', () => {
// sortColumn
paginatedTable.sortColumn(0);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe('aaaa');
expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe('zzzz');
});
test('should sort descending on second invocation', () => {
// sortColumn
paginatedTable.sortColumn(0);
paginatedTable.sortColumn(0);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe('zzzz');
expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe('aaaa');
});
test('should clear sorting on third invocation', () => {
// sortColumn
paginatedTable.sortColumn(0);
paginatedTable.sortColumn(0);
paginatedTable.sortColumn(0);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe(data.rows[0][0]);
expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe('aaaa');
});
test('should sort new column ascending', () => {
// sort by first column
paginatedTable.sortColumn(0);
$scope.$digest();
// sort by second column
paginatedTable.sortColumn(1);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa');
expect(tableRows.eq(lastRowIndex).find('td').eq(1).text()).toBe('zzzz');
});
});
describe('sorting duplicate columns', () => {
let data;
const colText = 'test row';
beforeEach(() => {
const cols: Column[] = [{ title: colText }, { title: colText }, { title: colText }];
const rows = [
['bbbb', 'aaaa', 'zzzz'],
['cccc', 'cccc', 'aaaa'],
['zzzz', 'bbbb', 'bbbb'],
['aaaa', 'zzzz', 'cccc'],
];
data = makeData(cols, rows);
renderTable(data, data.columns, data.rows);
});
test('should have duplicate column titles', () => {
const columns = $el.find('thead th span');
columns.each((i, col) => {
expect($(col).text()).toBe(colText);
});
});
test('should handle sorting on columns with the same name', () => {
// sort by the last column
paginatedTable.sortColumn(2);
$scope.$digest();
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe('cccc');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('cccc');
expect(tableRows.eq(0).find('td').eq(2).text()).toBe('aaaa');
expect(tableRows.eq(1).find('td').eq(2).text()).toBe('bbbb');
expect(tableRows.eq(2).find('td').eq(2).text()).toBe('cccc');
expect(tableRows.eq(3).find('td').eq(2).text()).toBe('zzzz');
});
test('should sort correctly between columns', () => {
// sort by the last column
paginatedTable.sortColumn(2);
$scope.$digest();
let tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe('cccc');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('cccc');
expect(tableRows.eq(0).find('td').eq(2).text()).toBe('aaaa');
// sort by the first column
paginatedTable.sortColumn(0);
$scope.$digest();
tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('td').eq(0).text()).toBe('aaaa');
expect(tableRows.eq(0).find('td').eq(1).text()).toBe('zzzz');
expect(tableRows.eq(0).find('td').eq(2).text()).toBe('cccc');
expect(tableRows.eq(1).find('td').eq(0).text()).toBe('bbbb');
expect(tableRows.eq(2).find('td').eq(0).text()).toBe('cccc');
expect(tableRows.eq(3).find('td').eq(0).text()).toBe('zzzz');
});
test('should not sort duplicate columns', () => {
paginatedTable.sortColumn(1);
$scope.$digest();
const sorters = $el.find('thead th i');
expect(sorters.eq(0).hasClass('fa-sort')).toBe(true);
expect(sorters.eq(1).hasClass('fa-sort')).toBe(false);
expect(sorters.eq(2).hasClass('fa-sort')).toBe(true);
});
});
describe('object rows', () => {
let cols: Column[];
let rows: any;
beforeEach(() => {
cols = [
{
title: 'object test',
id: '0',
formatter: {
convert: (val) => {
return val === 'zzz' ? '<h1>hello</h1>' : val;
},
},
},
];
rows = [['aaaa'], ['zzz'], ['bbbb']];
renderTable({ columns: cols, rows }, cols, rows);
});
test('should append object markup', () => {
const tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('h1').length).toBe(0);
expect(tableRows.eq(1).find('h1').length).toBe(1);
expect(tableRows.eq(2).find('h1').length).toBe(0);
});
test('should sort using object value', () => {
paginatedTable.sortColumn(0);
$scope.$digest();
let tableRows = $el.find('tbody tr');
expect(tableRows.eq(0).find('h1').length).toBe(0);
expect(tableRows.eq(1).find('h1').length).toBe(0);
// html row should be the last row
expect(tableRows.eq(2).find('h1').length).toBe(1);
paginatedTable.sortColumn(0);
$scope.$digest();
tableRows = $el.find('tbody tr');
// html row should be the first row
expect(tableRows.eq(0).find('h1').length).toBe(1);
expect(tableRows.eq(1).find('h1').length).toBe(0);
expect(tableRows.eq(2).find('h1').length).toBe(0);
});
});
}); | the_stack |
* CRUD actions spec
*/
import { DataManager, UrlAdaptor, Query } from '@syncfusion/ej2-data';
import { Kanban, KanbanModel, ActionEventArgs } from '../../src/kanban/index';
import { kanbanData } from './common/kanban-data.spec';
import { profile, inMB, getMemoryProfile } from './common/common.spec';
import * as util from './common/util.spec';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
Kanban.Inject();
describe('CRUD actions module', () => {
beforeAll(() => {
const isDef: (o: any) => boolean = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
// eslint-disable-next-line no-console
console.log('Unsupported environment, window.performance.memory is unavailable');
(this as any).skip(); //Skips test (in Chai)
return;
}
});
describe('Add action testing', () => {
let kanbanObj: Kanban;
const dataSource: Record<string, any>[] = kanbanData.slice(0, 10);
beforeAll((done: DoneFn) => {
kanbanObj = util.createKanban({}, dataSource, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
// it('action begin event testing in add card public method', () => {
// kanbanObj.actionBegin = (args: ActionEventArgs) => args.cancel = true;
// expect(kanbanObj.kanbanData.length).toEqual(10);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
// let cardData: { [key: string]: Object } = {
// Id: 76,
// Status: 'Close',
// Summary: 'Check test cases.',
// Type: 'Story',
// Priority: 'Release Breaker',
// Tags: 'Testing',
// Estimate: 0.5,
// Assignee: 'Nancy Davloio',
// RankId: 22
// };
// kanbanObj.addCard(cardData);
// expect(kanbanObj.kanbanData.length).toEqual(10);
// });
// it('action complete event testing in add card public method', () => {
// kanbanObj.actionBegin = (args: ActionEventArgs) => args.cancel = false;
// kanbanObj.actionComplete = (args: ActionEventArgs) => args.cancel = true;
// expect(kanbanObj.kanbanData.length).toEqual(10);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
// let cardData: { [key: string]: Object } = {
// Id: 76,
// Status: 'Close',
// Summary: 'Check test cases.',
// Type: 'Story',
// Priority: 'Release Breaker',
// Tags: 'Testing',
// Estimate: 0.5,
// Assignee: 'Nancy Davloio',
// RankId: 22
// };
// kanbanObj.addCard(cardData);
// expect(kanbanObj.kanbanData.length).toEqual(10);
// });
// it('add card public method testing', (done: DoneFn) => {
// kanbanObj.actionComplete = (args: ActionEventArgs) => args.cancel = false;
// kanbanObj.dataBound = () => {
// expect(kanbanObj.kanbanData.length).toEqual(11);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(10);
// done();
// };
// expect(kanbanObj.kanbanData.length).toEqual(10);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
// let cardData: { [key: string]: Object } = {
// Id: 77,
// Status: 'Close',
// Summary: 'Check test cases.',
// Type: 'Story',
// Priority: 'Release Breaker',
// Tags: 'Testing',
// Estimate: 0.5,
// Assignee: 'Nancy Davloio',
// RankId: 22
// };
// kanbanObj.addCard(cardData);
// });
// });
// describe('Update action testing', () => {
// let kanbanObj: Kanban;
// let dataSource: Object[] = kanbanData.slice(0, 10);
// beforeAll((done: DoneFn) => {
// kanbanObj = util.createKanban({}, dataSource, done);
// });
// afterAll(() => {
// util.destroy(kanbanObj);
// });
// it('action begin event testing in update card public method', () => {
// kanbanObj.actionBegin = (args: ActionEventArgs) => args.cancel = true;
// expect(kanbanObj.kanbanData.length).toEqual(10);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
// let cardData: { [key: string]: Object }[] = util.cloneDataSource(kanbanData.slice(1, 3)) as { [key: string]: Object }[];
// cardData[0].Status = 'Testing';
// cardData[1].Status = 'Close';
// kanbanObj.updateCard(cardData);
// expect(kanbanObj.kanbanData.length).toEqual(10);
// });
// it('action complete event testing in update card public method', () => {
// kanbanObj.actionBegin = (args: ActionEventArgs) => args.cancel = false;
// kanbanObj.actionComplete = (args: ActionEventArgs) => args.cancel = true;
// expect(kanbanObj.kanbanData.length).toEqual(10);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
// let cardData: { [key: string]: Object }[] = util.cloneDataSource(kanbanData.slice(1, 3)) as { [key: string]: Object }[];
// cardData[0].Status = 'Testing';
// cardData[1].Status = 'Close';
// kanbanObj.updateCard(cardData);
// expect(kanbanObj.kanbanData.length).toEqual(10);
// });
// it('update card public method testing', (done: DoneFn) => {
// kanbanObj.actionComplete = (args: ActionEventArgs) => args.cancel = false;
// kanbanObj.dataBound = () => {
// expect(kanbanObj.kanbanData.length).toEqual(10);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
// expect(cardData.Id).toEqual(1);
// expect(cardData.Status).toEqual('InProgress');
// done();
// };
// expect(kanbanObj.kanbanData.length).toEqual(10);
// expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
// let cardData: { [key: string]: Object } = util.cloneDataSource(kanbanData.slice(0, 1))[0] as { [key: string]: Object };
// expect(cardData.Id).toEqual(1);
// expect(cardData.Status).toEqual('Open');
// cardData.Status = 'InProgress';
// kanbanObj.updateCard(cardData);
// });
});
describe('Delete action testing', () => {
let kanbanObj: Kanban;
const dataSource: Record<string, any>[] = kanbanData.slice(0, 10);
beforeAll((done: DoneFn) => {
kanbanObj = util.createKanban({}, dataSource, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('action begin event testing in delete card public method', () => {
kanbanObj.actionBegin = (args: ActionEventArgs) => args.cancel = true;
expect(kanbanObj.kanbanData.length).toEqual(10);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
const cardData: Record<string, any>[] = util.cloneDataSource(kanbanData.slice(1, 2));
kanbanObj.deleteCard(cardData[0]);
expect(kanbanObj.kanbanData.length).toEqual(10);
});
it('action complete event testing in delete card public method', () => {
kanbanObj.actionBegin = (args: ActionEventArgs) => args.cancel = false;
kanbanObj.actionComplete = (args: ActionEventArgs) => args.cancel = true;
expect(kanbanObj.kanbanData.length).toEqual(10);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
const cardData: Record<string, any>[] = util.cloneDataSource(kanbanData.slice(1, 3));
kanbanObj.deleteCard(cardData);
expect(kanbanObj.kanbanData.length).toEqual(10);
});
it('delete card public method testing', (done: DoneFn) => {
kanbanObj.actionComplete = (args: ActionEventArgs) => args.cancel = false;
kanbanObj.dataBound = () => {
expect(kanbanObj.kanbanData.length).toEqual(9);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(8);
done();
};
expect(kanbanObj.kanbanData.length).toEqual(10);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(9);
kanbanObj.deleteCard(1);
});
});
xdescribe('Remote data success testing', () => {
let kanbanObj: Kanban;
const dataSource: Record<string, any>[] = kanbanData.slice(0, 10);
const cardData: Record<string, any>[] = [{
Id: 1,
Subject: 'Remote Data Testing',
StartTime: new Date(2019, 11, 2, 10),
EndTime: new Date(2019, 11, 2, 11, 30),
IsAllDay: false
}];
beforeAll(() => {
jasmine.Ajax.install();
const dataManager: DataManager = new DataManager({
url: 'api/Kanban/GetData/',
crudUrl: 'api/Kanban/UpdateData/',
adaptor: new UrlAdaptor()
});
const model: KanbanModel = { query: new Query() };
kanbanObj = util.createKanban(model, dataManager);
});
beforeEach((done: DoneFn) => {
const request: JasmineAjaxRequest = jasmine.Ajax.requests.at(1) || jasmine.Ajax.requests.mostRecent();
request.respondWith({ 'status': 200, 'responseText': JSON.stringify({ d: dataSource, __count: dataSource.length }) });
done();
});
it('add card using remote data', () => {
jasmine.Ajax.requests.reset();
expect(kanbanObj.kanbanData.length).toEqual(10);
kanbanObj.addCard(cardData);
});
it('event get action after adding new card', () => {
expect(kanbanObj.kanbanData.length).toEqual(11);
});
afterAll(() => {
util.destroy(kanbanObj);
jasmine.Ajax.uninstall();
});
});
xdescribe('Remote data success with kanban destroy testing', () => {
let kanbanObj: Kanban;
const dataSource: Record<string, any>[] = kanbanData.slice(0, 10);
const cardData: Record<string, any>[] = [{
Id: 1,
Subject: 'Remote Data Testing',
StartTime: new Date(2019, 11, 2, 10),
EndTime: new Date(2019, 11, 2, 11, 30),
IsAllDay: false
}];
beforeAll(() => {
jasmine.Ajax.install();
const dataManager: DataManager = new DataManager({
url: 'api/Kanban/GetData/',
crudUrl: 'api/Kanban/UpdateData/',
adaptor: new UrlAdaptor()
});
const model: KanbanModel = { query: new Query() };
kanbanObj = util.createKanban(model, dataManager);
});
beforeEach((done: DoneFn) => {
const request: JasmineAjaxRequest = jasmine.Ajax.requests.at(1) || jasmine.Ajax.requests.mostRecent();
request.respondWith({ 'status': 200, 'responseText': JSON.stringify({ d: dataSource, __count: dataSource.length }) });
done();
});
it('delete card using remote data', () => {
jasmine.Ajax.requests.reset();
expect(kanbanObj.kanbanData.length).toEqual(10);
kanbanObj.deleteCard(cardData);
util.destroy(kanbanObj);
});
it('action complete checking for delete action result', () => {
expect(kanbanObj.isDestroyed).toEqual(true);
});
afterAll(() => {
jasmine.Ajax.uninstall();
});
});
xdescribe('Remote data failure testing', () => {
let kanbanObj: Kanban;
let dataSource: Record<string, any>[] = kanbanData.slice(0, 10);
const cardData: Record<string, any>[] = [{
Id: 1,
Subject: 'Remote Data Testing',
StartTime: new Date(2019, 11, 2, 10),
EndTime: new Date(2019, 11, 2, 11, 30),
IsAllDay: false
}];
let isDataLoad: boolean = true;
let isChecking: boolean = false;
const actionFailedFunction: () => void = jasmine.createSpy('actionFailure');
beforeAll(() => {
jasmine.Ajax.install();
const dataManager: DataManager = new DataManager({
url: 'api/Kanban/GetData/',
crudUrl: 'api/Kanban/UpdateData/',
adaptor: new UrlAdaptor()
});
const model: KanbanModel = {
query: new Query(),
actionComplete: (args: ActionEventArgs) => {
if (args.requestType === 'cardCreated') {
args.cancel = isChecking;
jasmine.Ajax.requests.reset();
}
},
actionFailure: actionFailedFunction
};
kanbanObj = util.createKanban(model, dataManager);
});
beforeEach((done: DoneFn) => {
const request: JasmineAjaxRequest = jasmine.Ajax.requests.at(1) || jasmine.Ajax.requests.mostRecent();
if (isDataLoad) {
request.respondWith({ 'status': 200, 'responseText': JSON.stringify({ d: dataSource, __count: dataSource.length }) });
} else {
request.respondWith({ 'status': 404, 'contentType': 'application/json', 'responseText': 'Page not found' });
}
done();
});
it('action complete testing in add card using remote data', () => {
isChecking = true;
jasmine.Ajax.requests.reset();
expect(kanbanObj.kanbanData.length).toEqual(10);
dataSource = dataSource.concat(cardData);
kanbanObj.addCard(cardData);
expect(kanbanObj.kanbanData.length).toEqual(10);
});
it('add card actiusing remote data', () => {
isDataLoad = false;
isChecking = false;
expect(kanbanObj.kanbanData.length).toEqual(10);
kanbanObj.addCard(cardData);
});
it('action complete checking for add action result', () => {
expect(actionFailedFunction).toHaveBeenCalled();
});
afterAll(() => {
util.destroy(kanbanObj);
jasmine.Ajax.uninstall();
});
});
xdescribe('Remote data failure with kanban destroy testing', () => {
let kanbanObj: Kanban;
const dataSource: Record<string, any>[] = kanbanData.slice(0, 10);
const cardData: Record<string, any>[] = [{
Id: 1,
Subject: 'Remote Data Testing',
StartTime: new Date(2019, 11, 2, 10),
EndTime: new Date(2019, 11, 2, 11, 30),
IsAllDay: false
}];
let isDataLoad: boolean = true;
const actionFailedFunction: () => void = jasmine.createSpy('actionFailure');
beforeAll(() => {
jasmine.Ajax.install();
const dataManager: DataManager = new DataManager({
url: 'api/Kanban/GetData/',
crudUrl: 'api/Kanban/UpdateData/',
adaptor: new UrlAdaptor()
});
const model: KanbanModel = {
query: new Query(),
actionFailure: actionFailedFunction
};
kanbanObj = util.createKanban(model, dataManager);
});
beforeEach((done: DoneFn) => {
const request: JasmineAjaxRequest = jasmine.Ajax.requests.at(1) || jasmine.Ajax.requests.mostRecent();
if (isDataLoad) {
request.respondWith({ 'status': 200, 'responseText': JSON.stringify({ d: dataSource, __count: dataSource.length }) });
} else {
request.respondWith({ 'status': 404, 'contentType': 'application/json', 'responseText': 'Page not found' });
}
done();
});
it('action complete testing in update card using remote data', () => {
isDataLoad = false;
jasmine.Ajax.requests.reset();
expect(kanbanObj.kanbanData.length).toEqual(10);
kanbanObj.updateCard(cardData);
util.destroy(kanbanObj);
});
it('destroy checking for update card action result', () => {
expect(kanbanObj.isDestroyed).toEqual(true);
});
afterAll(() => {
jasmine.Ajax.uninstall();
});
});
describe('Add Card with Priority', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Ascending'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
// it('Passed one data', () => {
// kanbanObj.dataBound = () => {
// let openCards: Object[] = kanbanObj.layoutModule.getColumnCards().Open;
// expect(kanbanObj.kanbanData.length).toEqual(76);
// expect((openCards[0] as { [key: string]: Object }).Id).toEqual(101);
// expect((openCards[0] as { [key: string]: Object }).RankId).toEqual(1);
// expect((openCards[1] as { [key: string]: Object }).RankId).toEqual(2);
// expect((openCards[2] as { [key: string]: Object }).RankId).toEqual(3);
// expect((openCards[3] as { [key: string]: Object }).RankId).toEqual(4);
// expect((openCards[4] as { [key: string]: Object }).RankId).toEqual(5);
// expect((openCards[5] as { [key: string]: Object }).RankId).toEqual(6);
// expect((openCards[6] as { [key: string]: Object }).RankId).toEqual(7);
// };
// expect(kanbanObj.kanbanData.length).toEqual(75);
// kanbanObj.addCard({ Id: 101, Status: 'Open', Assignee: 'Andrew Fuller', RankId: 1 });
// });
// it('Passed two datas', () => {
// kanbanObj.dataBound = () => {
// let openCards: Object[] = kanbanObj.layoutModule.getColumnCards().Open;
// expect(kanbanObj.kanbanData.length).toEqual(78);
// expect((openCards[0] as { [key: string]: Object }).Id).toEqual(102);
// expect((openCards[0] as { [key: string]: Object }).RankId).toEqual(1);
// expect((openCards[1] as { [key: string]: Object }).RankId).toEqual(2);
// expect((openCards[2] as { [key: string]: Object }).RankId).toEqual(3);
// expect((openCards[2] as { [key: string]: Object }).Id).toEqual(103);
// expect((openCards[3] as { [key: string]: Object }).RankId).toEqual(4);
// expect((openCards[4] as { [key: string]: Object }).RankId).toEqual(5);
// expect((openCards[5] as { [key: string]: Object }).RankId).toEqual(6);
// expect((openCards[6] as { [key: string]: Object }).RankId).toEqual(7);
// };
// expect(kanbanObj.kanbanData.length).toEqual(76);
// kanbanObj.addCard([
// { Id: 102, Status: 'Open', Assignee: 'Andrew Fuller', RankId: 1 },
// { Id: 103, Status: 'Open', Assignee: 'Andrew Fuller', RankId: 3 }
// ]);
// });
// it('Passed different column datas', () => {
// kanbanObj.dataBound = () => {
// let cards: { [key: string]: Object[] } = kanbanObj.layoutModule.getColumnCards();
// expect(kanbanObj.kanbanData.length).toEqual(80);
// expect((cards.InProgress[0] as { [key: string]: Object }).Id).toEqual(104);
// expect((cards.InProgress[0] as { [key: string]: Object }).RankId).toEqual(1);
// expect((cards.InProgress[1] as { [key: string]: Object }).RankId).toEqual(2);
// expect((cards.InProgress[2] as { [key: string]: Object }).RankId).toEqual(3);
// expect((cards.Testing[2] as { [key: string]: Object }).Id).toEqual(105);
// expect((cards.Testing[2] as { [key: string]: Object }).RankId).toEqual(3);
// expect((cards.Testing[3] as { [key: string]: Object }).RankId).toEqual(4);
// expect((cards.Testing[4] as { [key: string]: Object }).RankId).toEqual(5);
// expect((cards.Testing[5] as { [key: string]: Object }).RankId).toEqual(6);
// expect((cards.Testing[6] as { [key: string]: Object }).RankId).toEqual(7);
// };
// expect(kanbanObj.kanbanData.length).toEqual(78);
// kanbanObj.addCard([
// { Id: 104, Status: 'InProgress', Assignee: 'Andrew Fuller', RankId: 1 },
// { Id: 105, Status: 'Testing', Assignee: 'Andrew Fuller', RankId: 3 }
// ]);
// });
});
describe('Add Card with Priority using swimlane', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Ascending'
},
swimlaneSettings: {
keyField: 'Assignee'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
// it('Passed one data', () => {
// kanbanObj.dataBound = () => {
// let openCards: Object[] = kanbanObj.layoutModule.getColumnCards().Open;
// expect(kanbanObj.kanbanData.length).toEqual(76);
// expect((openCards[1] as { [key: string]: Object }).Id).toEqual(101);
// expect((openCards[1] as { [key: string]: Object }).RankId).toEqual(1);
// expect((openCards[5] as { [key: string]: Object }).Id).toEqual(25);
// expect((openCards[5] as { [key: string]: Object }).RankId).toEqual(5);
// };
// expect(kanbanObj.kanbanData.length).toEqual(75);
// kanbanObj.addCard({ Id: 101, Status: 'Open', Assignee: 'Andrew Fuller', RankId: 1 });
// });
});
describe('Update Card with Priority', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Ascending'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
// it('Passed one data', () => {
// kanbanObj.dataBound = () => {
// let openCards: Object[] = kanbanObj.layoutModule.getColumnCards().Open;
// expect(kanbanObj.kanbanData.length).toEqual(75);
// expect((openCards[0] as { [key: string]: Object }).Id).toEqual(3);
// expect((openCards[0] as { [key: string]: Object }).RankId).toEqual(2);
// expect((openCards[1] as { [key: string]: Object }).Id).toEqual(13);
// expect((openCards[1] as { [key: string]: Object }).RankId).toEqual(3);
// expect((openCards[2] as { [key: string]: Object }).Id).toEqual(15);
// expect((openCards[2] as { [key: string]: Object }).RankId).toEqual(4);
// expect((openCards[3] as { [key: string]: Object }).Id).toEqual(1);
// expect((openCards[3] as { [key: string]: Object }).RankId).toEqual(5);
// };
// expect(kanbanObj.kanbanData.length).toEqual(75);
// kanbanObj.updateCard({ Id: 1, Status: 'Open', Assignee: 'Andrew Fuller', RankId: 5 });
// });
// it('Passed two datas', () => {
// kanbanObj.dataBound = () => {
// let openCards: Object[] = kanbanObj.layoutModule.getColumnCards().Open;
// expect(kanbanObj.kanbanData.length).toEqual(75);
// expect((openCards[0] as { [key: string]: Object }).Id).toEqual(16);
// expect((openCards[0] as { [key: string]: Object }).RankId).toEqual(1);
// expect((openCards[1] as { [key: string]: Object }).Id).toEqual(3);
// expect((openCards[1] as { [key: string]: Object }).RankId).toEqual(2);
// expect((openCards[2] as { [key: string]: Object }).Id).toEqual(13);
// expect((openCards[2] as { [key: string]: Object }).RankId).toEqual(3);
// expect((openCards[3] as { [key: string]: Object }).Id).toEqual(2);
// expect((openCards[3] as { [key: string]: Object }).RankId).toEqual(4);
// };
// expect(kanbanObj.kanbanData.length).toEqual(75);
// kanbanObj.updateCard([
// { Id: 2, Status: 'Open', Assignee: 'Andrew Fuller', RankId: 4 },
// { Id: 16, Status: 'Open', Assignee: 'Andrew Fuller', RankId: 1 }
// ]);
// });
// it('Passed different column datas', () => {
// kanbanObj.dataBound = () => {
// let cards: { [key: string]: Object[] } = kanbanObj.layoutModule.getColumnCards();
// let inProgressCards: Object[] = cards.InProgress;
// let testingCards: Object[] = cards.Testing;
// expect(kanbanObj.kanbanData.length).toEqual(75);
// expect((inProgressCards[0] as { [key: string]: Object }).Id).toEqual(8);
// expect((inProgressCards[0] as { [key: string]: Object }).RankId).toEqual(2);
// expect((inProgressCards[1] as { [key: string]: Object }).Id).toEqual(4);
// expect((inProgressCards[1] as { [key: string]: Object }).RankId).toEqual(3);
// expect((inProgressCards[2] as { [key: string]: Object }).Id).toEqual(14);
// expect((inProgressCards[2] as { [key: string]: Object }).RankId).toEqual(4);
// expect((testingCards[0] as { [key: string]: Object }).Id).toEqual(5);
// expect((testingCards[0] as { [key: string]: Object }).RankId).toEqual(1);
// expect((testingCards[1] as { [key: string]: Object }).Id).toEqual(3);
// expect((testingCards[1] as { [key: string]: Object }).RankId).toEqual(2);
// expect((testingCards[2] as { [key: string]: Object }).Id).toEqual(9);
// expect((testingCards[2] as { [key: string]: Object }).RankId).toEqual(3);
// };
// expect(kanbanObj.kanbanData.length).toEqual(75);
// kanbanObj.updateCard([
// { Id: 8, Status: 'InProgress', Assignee: 'Andrew Fuller', RankId: 2 },
// { Id: 3, Status: 'Testing', Assignee: 'Andrew Fuller', RankId: 2 }
// ]);
// });
});
describe('Drag and drop functionality', () => {
let kanbanObj: Kanban;
let dragElement: HTMLElement;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Ascending'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Dragged clone behavior testing', () => {
dragElement = (kanbanObj.element.querySelectorAll('.e-card[data-id="1"]') as NodeListOf<Element>).item(0) as HTMLElement;
expect(dragElement.classList.contains('e-draggable')).toBe(true);
util.triggerMouseEvent(dragElement, 'mousedown');
util.triggerMouseEvent(dragElement, 'mousemove', 100, 100);
});
it('Created Dropped clone on above the column testing and target is card', () => {
const element: Element = kanbanObj.element.querySelectorAll('.e-card[data-id="4"]').item(0);
util.triggerMouseEvent(element, 'mousemove', 250, 400);
});
it('Dropped clone testing', () => {
kanbanObj.dataBound = () => {
cards = kanbanObj.layoutModule.getColumnCards();
expect((cards.InProgress[0] as Record<string, any>).Id).toEqual(2);
expect((cards.InProgress[0] as Record<string, any>).RankId).toEqual(1);
expect((cards.InProgress[1] as Record<string, any>).Id).toEqual(4);
expect((cards.InProgress[1] as Record<string, any>).RankId).toEqual(2);
expect((cards.InProgress[2] as Record<string, any>).Id).toEqual(1);
expect((cards.InProgress[2] as Record<string, any>).RankId).toEqual(3);
expect((cards.InProgress[3] as Record<string, any>).Id).toEqual(14);
expect((cards.InProgress[3] as Record<string, any>).RankId).toEqual(4);
};
const droppedElement: Element = kanbanObj.element.querySelectorAll('.e-card[data-id="4"]').item(0);
let cards: Record<string, any[]> = kanbanObj.layoutModule.getColumnCards();
expect((cards.Open[0] as Record<string, any>).Id).toEqual(1);
expect((cards.Open[0] as Record<string, any>).RankId).toEqual(1);
expect((cards.InProgress[0] as Record<string, any>).Id).toEqual(2);
expect((cards.InProgress[0] as Record<string, any>).RankId).toEqual(1);
expect((cards.InProgress[1] as Record<string, any>).Id).toEqual(4);
expect((cards.InProgress[1] as Record<string, any>).RankId).toEqual(2);
expect((cards.InProgress[2] as Record<string, any>).Id).toEqual(14);
expect((cards.InProgress[2] as Record<string, any>).RankId).toEqual(3);
util.triggerMouseEvent(droppedElement, 'mouseup', 250, 400);
});
});
describe('Drag and drop functionality', () => {
let kanbanObj: Kanban;
let dragElement: HTMLElement;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Ascending'
},
swimlaneSettings: {
keyField: 'Assignee'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Dragged clone behavior testing', () => {
dragElement = (kanbanObj.element.querySelectorAll('.e-card[data-id="2"]') as NodeListOf<Element>).item(0) as HTMLElement;
util.triggerMouseEvent(dragElement, 'mousedown');
util.triggerMouseEvent(dragElement, 'mousemove', 250, 400);
});
it('Created Dropped clone on above the column testing and target is card', () => {
const element: Element = kanbanObj.element.querySelectorAll('.e-card[data-id="45"]').item(0);
util.triggerMouseEvent(element, 'mousemove', 250, 550);
});
it('Dropped clone testing', () => {
const droppedElement: Element = kanbanObj.element.querySelectorAll('.e-card[data-id="45"]').item(0);
kanbanObj.dataBound = () => {
const testingCards: Record<string, any>[] =
kanbanObj.layoutModule.getColumnCards().Testing as Record<string, any>[];
expect((testingCards[10] as Record<string, any>).Id).toEqual(2);
expect((testingCards[10] as Record<string, any>).RankId).toEqual(11);
expect((testingCards[9] as Record<string, any>).Id).toEqual(45);
expect((testingCards[9] as Record<string, any>).RankId).toEqual(10);
};
util.triggerMouseEvent(droppedElement, 'mouseup', 250, 550);
});
it('Dragged clone behavior testing', () => {
dragElement = (kanbanObj.element.querySelectorAll('.e-card[data-id="45"]') as NodeListOf<Element>).item(0) as HTMLElement;
util.triggerMouseEvent(dragElement, 'mousedown');
util.triggerMouseEvent(dragElement, 'mousemove', 250, 100);
});
it('Created Dropped clone on above the column testing and target is card', () => {
const element: Element = (kanbanObj.element.querySelectorAll('.e-card-wrapper') as NodeListOf<Element>).item(1);
util.triggerMouseEvent(element, 'mousemove', 250, 150);
});
it('Dropped clone testing', () => {
const droppedElement: Element = (kanbanObj.element.querySelectorAll('.e-card-wrapper') as NodeListOf<Element>).item(1);
kanbanObj.dataBound = () => {
const inProgressCards: Record<string, any>[] =
kanbanObj.layoutModule.getColumnCards().InProgress as Record<string, any>[];
expect((inProgressCards[8] as Record<string, any>).Id).toEqual(45);
expect((inProgressCards[8] as Record<string, any>).RankId).toEqual(10);
};
util.triggerMouseEvent(droppedElement, 'mouseup', 250, 100);
});
});
describe('Adding and Updating the card data as Ascending order', () => {
let kanbanObj: Kanban;
let card: Record<string, any>;
let length: number;
beforeAll((done: DoneFn) => {
let model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Ascending'
},
swimlaneSettings: {
keyField: 'Assignee'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Add card as array type', () => {
card = kanbanObj.kanbanData[0];
length = kanbanObj.kanbanData.length;
(card as any).Summary = "Card_Update";
expect([card] instanceof Array).toBeTruthy;
kanbanObj.addCard([card], 0);
expect(length + 1 == kanbanObj.kanbanData.length).toBe(true);
});
it('Add card as object type', () => {
card = kanbanObj.kanbanData[0];
length = kanbanObj.kanbanData.length;
(card as any).Summary = "UpdatingCard";
expect(card instanceof Array).toBe(false);
kanbanObj.addCard(card, 0);
expect(length + 1 == kanbanObj.kanbanData.length).toBe(true);
});
it('Update card in [] type', () => {
card = kanbanObj.kanbanData[0];
length = kanbanObj.kanbanData.length;
(card as any).Summary = "NewCard";
expect([card] instanceof Array).toBe(true);
kanbanObj.updateCard([card], 0);
expect((kanbanObj.kanbanData[0] as any).Summary).toEqual("NewCard");
expect(length == kanbanObj.kanbanData.length).toBe(true);
});
});
describe('sortSettings as descending order to update priority order', () => {
let kanbanObj: Kanban;
let card: Record<string, any>;
let length: number;
beforeAll((done: DoneFn) => {
let model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Descending'
},
swimlaneSettings: {
keyField: 'Assignee'
},
cardSettings: {
headerField: 'Summary'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Add new card along the order in desecnding order', () => {
card = kanbanObj.kanbanData[0];
length = kanbanObj.kanbanData.length;
(card as any).Summary = "Descending card";
kanbanObj.addCard([card], 1);
expect(isNullOrUndefined(kanbanObj.cardSettings.headerField)).toBe(false);
expect((card as any).Summary).toEqual('Descending card');
expect(kanbanObj.kanbanData.length == length + 1).toBe(true);
});
});
describe('EJ2CORE-555 - Descending order the cards to the column does not work properly when adding a new card', () => {
let kanbanObj: Kanban;
let card: Record<string, any>;
let length: number;
beforeAll((done: DoneFn) => {
let model: KanbanModel = {
sortSettings: {
sortBy: 'Index',
field: 'RankId',
direction: 'Descending'
},
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Check cards are alinged in descending order', () => {
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.sortSettings.field]).toBe(14);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.cardSettings.headerField]).toBe(74);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.sortSettings.field]).toBe(13);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.cardSettings.headerField]).toBe(69);
expect(kanbanObj.getColumnData('Open')[kanbanObj.getColumnData('Open').length - 1][kanbanObj.sortSettings.field]).toBe(1);
expect(kanbanObj.getColumnData('Open')[kanbanObj.getColumnData('Open').length - 1][kanbanObj.cardSettings.headerField]).toBe(1);
});
it('Check the descending order after adding the card', () => {
expect(kanbanObj.kanbanData.length).toEqual(75);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(64);
let cardData: { [key: string]: Object } = {
Id: 76,
Status: 'Open',
Summary: 'Check test cases.',
Type: 'Story',
Priority: 'Release Breaker',
Tags: 'Testing',
Estimate: 0.5,
Assignee: 'Nancy Davloio',
RankId: 22
};
kanbanObj.addCard(cardData);
expect(kanbanObj.kanbanData.length).toEqual(76);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(65);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.sortSettings.field]).toBe(22);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.cardSettings.headerField]).toBe(76);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.sortSettings.field]).toBe(14);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.cardSettings.headerField]).toBe(74);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.sortSettings.field]).toBe(13);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.cardSettings.headerField]).toBe(69);
});
it('Pass without sorting field with add card in descending order', () => {
expect(kanbanObj.kanbanData.length).toEqual(76);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(65);
let cardData: { [key: string]: Object } = {
Id: 77,
Status: 'Open',
Summary: 'Check test cases.',
Type: 'Story',
Priority: 'Release Breaker',
Tags: 'Testing',
Estimate: 0.5,
Assignee: 'Nancy Davloio'
};
kanbanObj.addCard(cardData);
expect(kanbanObj.kanbanData.length).toEqual(77);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(66);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.sortSettings.field]).toBe(23);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.cardSettings.headerField]).toBe(77);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.sortSettings.field]).toBe(22);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.cardSettings.headerField]).toBe(76);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.sortSettings.field]).toBe(14);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.cardSettings.headerField]).toBe(74);
});
it('Pass field with inbetween cards with add card in descending order', () => {
expect(kanbanObj.kanbanData.length).toEqual(77);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(66);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.sortSettings.field]).toBe(23);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.cardSettings.headerField]).toBe(77);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.sortSettings.field]).toBe(22);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.cardSettings.headerField]).toBe(76);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.sortSettings.field]).toBe(14);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.cardSettings.headerField]).toBe(74);
expect(kanbanObj.getColumnData('Open')[3][kanbanObj.sortSettings.field]).toBe(13);
expect(kanbanObj.getColumnData('Open')[3][kanbanObj.cardSettings.headerField]).toBe(69);
expect(kanbanObj.getColumnData('Open')[4][kanbanObj.sortSettings.field]).toBe(12);
expect(kanbanObj.getColumnData('Open')[4][kanbanObj.cardSettings.headerField]).toBe(64);
expect(kanbanObj.getColumnData('Open')[5][kanbanObj.sortSettings.field]).toBe(11);
expect(kanbanObj.getColumnData('Open')[5][kanbanObj.cardSettings.headerField]).toBe(63);
expect(kanbanObj.getColumnData('Open')[6][kanbanObj.sortSettings.field]).toBe(10);
expect(kanbanObj.getColumnData('Open')[6][kanbanObj.cardSettings.headerField]).toBe(61);
expect(kanbanObj.getColumnData('Open')[7][kanbanObj.sortSettings.field]).toBe(9);
expect(kanbanObj.getColumnData('Open')[7][kanbanObj.cardSettings.headerField]).toBe(51);
let cardData: { [key: string]: Object } = {
Id: 78,
Status: 'Open',
Summary: 'Check test cases.',
Type: 'Story',
Priority: 'Release Breaker',
Tags: 'Testing',
Estimate: 0.5,
Assignee: 'Nancy Davloio',
RankId: 10
};
kanbanObj.addCard(cardData);
expect(kanbanObj.kanbanData.length).toEqual(78);
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(67);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.sortSettings.field]).toBe(17);
expect(kanbanObj.getColumnData('Open')[0][kanbanObj.cardSettings.headerField]).toBe(77);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.sortSettings.field]).toBe(16);
expect(kanbanObj.getColumnData('Open')[1][kanbanObj.cardSettings.headerField]).toBe(76);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.sortSettings.field]).toBe(15);
expect(kanbanObj.getColumnData('Open')[2][kanbanObj.cardSettings.headerField]).toBe(74);
expect(kanbanObj.getColumnData('Open')[3][kanbanObj.sortSettings.field]).toBe(14);
expect(kanbanObj.getColumnData('Open')[3][kanbanObj.cardSettings.headerField]).toBe(69);
expect(kanbanObj.getColumnData('Open')[4][kanbanObj.sortSettings.field]).toBe(13);
expect(kanbanObj.getColumnData('Open')[4][kanbanObj.cardSettings.headerField]).toBe(64);
expect(kanbanObj.getColumnData('Open')[5][kanbanObj.sortSettings.field]).toBe(12);
expect(kanbanObj.getColumnData('Open')[5][kanbanObj.cardSettings.headerField]).toBe(63);
expect(kanbanObj.getColumnData('Open')[6][kanbanObj.sortSettings.field]).toBe(11);
expect(kanbanObj.getColumnData('Open')[6][kanbanObj.cardSettings.headerField]).toBe(61);
expect(kanbanObj.getColumnData('Open')[7][kanbanObj.sortSettings.field]).toBe(10);
expect(kanbanObj.getColumnData('Open')[7][kanbanObj.cardSettings.headerField]).toBe(78);
expect(kanbanObj.getColumnData('Open')[8][kanbanObj.sortSettings.field]).toBe(9);
expect(kanbanObj.getColumnData('Open')[8][kanbanObj.cardSettings.headerField]).toBe(51);
});
});
it('memory leak', () => {
profile.sample();
const average: number = inMB(profile.averageChange);
expect(average).toBeLessThan(10); //Check average change in memory samples to not be over 10MB
const memory: number = inMB(getMemoryProfile());
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import { Action } from 'redux'
import { ApplicationState } from '../index'
import { ThunkAction } from 'redux-thunk'
import moment from 'moment';
import { setUserInfo } from "../application/actions";
import NetatmoNAMain from '../../models/NetatmoNAMain';
import NetatmoUserInformation from "../../models/NetatmoUserInformation";
import NetatmoChartsData from "../../models/NetatmoChartsData";
import { NetatmoActionTypes } from "./types";
import {ChartScales, DataTypes, Timelapse} from "../../types/netatmo";
const CALL_DELAY = 10;
export const requestAuth = () => {
return {
type: NetatmoActionTypes.AUTH_REQUEST
}
};
export const successAuth = (json: any) => {
return {
type: NetatmoActionTypes.AUTH_SUCCESS,
payload: json,
receivedAt: Date.now()
}
};
export const failureAuth = (error: any) => {
return {
type: NetatmoActionTypes.AUTH_FAILURE,
error: error
}
};
export const fetchAuth = (username: string, password: string, secret: string): ThunkAction<void, ApplicationState, null, Action<string>> => {
return (dispatch, getState) => {
dispatch(requestAuth());
const params = new URLSearchParams();
params.append('username', username);
params.append('password', password);
params.append('secret', secret);
return fetch('/netatmo-auth', {method: 'POST', body: params})
.then(response => {
if (!response.ok) throw response;
return response.json()
})
.then(json => {
window.localStorage.setItem('NetatmoRefreshToken', json.refresh_token);
window.localStorage.setItem('NetatmoExpireIn', moment().unix() + json.expire_in);
//window.localStorage.setItem('appIsConfigured', 'true');
dispatch(successAuth(json));
//dispatch(appConfigured(true));
console.log('Fetch station data')
dispatch(fetchStationData());
})
.catch(error => {
// Todo types
error.json().then((errorMessage: any) => {
dispatch(failureAuth(errorMessage))
})
});
}
};
export const requestRefreshToken = () => {
return {
type: NetatmoActionTypes.REFRESH_TOKEN_REQUEST
}
};
export const successRefreshToken = (json: any) => {
return {
type: NetatmoActionTypes.REFRESH_TOKEN_SUCCESS,
payload: json,
receivedAt: Date.now()
}
};
export const failureRefreshToken = (error: any) => {
return {
type: NetatmoActionTypes.REFRESH_TOKEN_FAILURE,
error: error
}
};
export const fetchRefreshToken = (): ThunkAction<void, ApplicationState, null, Action<string>> => {
return (dispatch, getState) => {
dispatch(requestRefreshToken());
const current_refresh_token = window.localStorage.getItem('NetatmoRefreshToken');
const params = new URLSearchParams();
params.append('refresh_token', current_refresh_token ? current_refresh_token : '');
return fetch('/netatmo-refresh-token', {method: 'POST', body: params})
.then(response => {
if (!response.ok) throw response;
return response.json()
})
.then(json => {
window.localStorage.setItem('NetatmoRefreshToken', json.refresh_token);
window.localStorage.setItem('NetatmoExpireIn', moment().unix() + json.expire_in);
dispatch(successRefreshToken(json));
dispatch(fetchStationData());
})
.catch(error => {
// Todo types
error.json().then((errorMessage: any) => {
dispatch(failureRefreshToken(errorMessage))
})
});
}
};
export const requestStationData = () => {
return {
type: NetatmoActionTypes.STATION_DATA_REQUEST
}
};
export const successStationData = (json: any) => {
return {
type: NetatmoActionTypes.STATION_DATA_SUCCESS,
payload: json,
receivedAt: Date.now()
}
};
export const failureStationData = (error: any) => {
return {
type: NetatmoActionTypes.STATION_DATA_FAILURE,
error: error
}
};
export const fetchStationData = (): ThunkAction<void, ApplicationState, null, Action<string>> => {
return (dispatch, getState) => {
// If no access token or refresh token is soon expired
if (!getState().netatmo.access_token || moment.unix(Number(getState().netatmo.access_token_expire_in)).diff(moment(), 'minute') < CALL_DELAY) {
// Fetch a new access token from refresh token and then fetch station data
dispatch(fetchRefreshToken());
} else {
// Fetch new data only if last data stored is bigger than 10 minutes
if (getState().netatmo.station_data_last_updated === 0 || moment().diff(moment.unix(Number(getState().netatmo.station_data?.last_status_store)), 'minute') > CALL_DELAY) {
dispatch(requestStationData());
const params = new URLSearchParams();
params.append('access_token', getState().netatmo.access_token as string);
return fetch('/netatmo-station-data', {method: 'POST', body: params})
.then(response => {
if (!response.ok) throw response;
return response.json()
})
.then(json => {
const data = new NetatmoNAMain(json.body.devices[0], json.body.user);
const user = new NetatmoUserInformation(json.body.user);
dispatch(successStationData(data))
dispatch(setUserInfo(user))
})
.catch(error => {
// Todo types
error.json().then((errorMessage: any) => {
dispatch(failureStationData(errorMessage))
})
});
} else {
console.debug('No new Netatmo station data to fetch')
}
}
}
};
export const requestMeasure = () => {
return {
type: NetatmoActionTypes.MEASURE_REQUEST
}
};
export const successMeasure = (data: any, module: string, types: string[], timelapse: Timelapse) => {
return {
type: NetatmoActionTypes.MEASURE_SUCCESS,
payload: data,
module: module,
types: types,
timelapse: timelapse,
receivedAt: Date.now()
}
};
export const failureMeasure = (error: any) => {
return {
type: NetatmoActionTypes.MEASURE_FAILURE,
error: error
}
};
export const fetchMeasure = (device: string, module: string, types: string[], timelapse: Timelapse): ThunkAction<void, ApplicationState, null, Action<string>> => {
return (dispatch, getState) => {
// Get measure only if we have no data or if the last fetch is bigger than 10 minutes
if (getState().netatmo.measure_data.length === 0 ||
(getState().netatmo.selected_types[0] !== types[0] ||
getState().netatmo.selected_module !== module) ||
getState().netatmo.selected_timelapse !== timelapse ||
moment().diff(moment.unix(Number(getState().netatmo.station_data?.last_status_store)), 'minute') > CALL_DELAY) {
dispatch(requestMeasure());
let date_begin: number;
let scale: ChartScales;
switch (timelapse) {
case "12h":
date_begin = moment().subtract(720, 'minutes').unix();
scale = '30min';
break;
case "1d":
date_begin = moment().subtract(1440, 'minutes').unix();
scale = '1hour';
break;
case "1m":
date_begin = moment().subtract(1, 'months').unix();
scale = '1day';
break;
}
const date_end = moment().unix();
const params = new URLSearchParams();
params.append('access_token', getState().netatmo.access_token as string);
params.append('device_id', device);
params.append('module_id', module);
params.append('scale', scale);
params.append('type', types.toString());
params.append('date_begin', date_begin.toString());
params.append('date_end', date_end.toString());
return fetch('/netatmo-measure', {method: 'POST', body: params})
.then(response => {
if (!response.ok) throw response;
return response.json()
})
.then(json => {
const dataChart = new NetatmoChartsData(json.body, types, getState().application.user);
dispatch(successMeasure(dataChart.data, module, types, timelapse))
})
.catch(error => {
// Todo types
error.json().then((errorMessage: any) => {
dispatch(failureMeasure(errorMessage))
})
});
} else {
console.debug('No new Netatmo measure data to fetch')
}
}
};
export const requestRainMeasure = () => {
return {
type: NetatmoActionTypes.MEASURE_RAIN_REQUEST
}
};
export const successRainMeasure = (data: any) => {
return {
type: NetatmoActionTypes.MEASURE_RAIN_SUCCESS,
payload: data,
receivedAt: Date.now()
}
};
export const failureNRainMeasure = (error: any) => {
return {
type: NetatmoActionTypes.MEASURE_RAIN_FAILURE,
error: error
}
};
export const fetchRainMeasure = (device: string, module: string): ThunkAction<void, ApplicationState, null, Action<string>> => {
return (dispatch, getState) => {
// Get measure only if we have no data or if the last fetch is bigger than 10 minutes
if (getState().netatmo.measure_rain_data.length === 0 || moment().diff(moment.unix(Number(getState().netatmo.station_data?.last_status_store)), 'minute') > CALL_DELAY) {
dispatch(requestRainMeasure());
const params = new URLSearchParams();
params.append('access_token', getState().netatmo.access_token as string);
params.append('device_id', device);
params.append('module_id', module);
params.append('scale', '1hour');
params.append('type', 'Rain');
params.append('date_begin', moment().subtract(1440, 'minutes').unix().toString());
params.append('date_end', moment().unix().toString());
return fetch('/netatmo-measure', {method: 'POST', body: params})
.then(response => {
if (!response.ok) throw response;
return response.json()
})
.then(json => {
const dataChart = new NetatmoChartsData(json.body, ['Rain'], getState().application.user);
dispatch(successRainMeasure(dataChart.data))
})
.catch(error => {
// Todo types
error.json().then((errorMessage: any) => {
dispatch(failureNRainMeasure(errorMessage))
})
});
} else {
console.debug('No new Netatmo rain measure data to fetch')
}
}
};
export const requestMeasures = (module: string) => {
return {
type: NetatmoActionTypes.MEASURES_REQUEST,
module: module
}
};
export const successMeasures = (data: any, module: string, timelapse: Timelapse) => {
return {
type: NetatmoActionTypes.MEASURES_SUCCESS,
payload: data,
receivedAt: Date.now(),
module: module
}
};
export const failureMeasures = (error: any, module: string) => {
return {
type: NetatmoActionTypes.MEASURES_FAILURE,
error: error,
module: module
}
};
export const fetchMeasures = (device: string, module: string, types: DataTypes[], timelapse: '12h'|'1d'|'1m', module_name: string): ThunkAction<void, ApplicationState, null, Action<string>> => {
return (dispatch, getState) => {
// Get measure only if we have no data or if the last fetch is bigger than 10 minutes
if ((getState().netatmo.measure_station_data.length === 0 &&
getState().netatmo.measure_outdoor_data.length === 0 &&
getState().netatmo.measure_indoor_data.length === 0 &&
getState().netatmo.measure_indoor_second_data.length === 0 &&
getState().netatmo.measure_indoor_third_data.length === 0) ||
moment().diff(moment.unix(Number(getState().netatmo.station_data?.last_status_store)), 'minute') > CALL_DELAY) {
dispatch(requestMeasures(module_name));
let date_begin: number;
let scale: ChartScales;
switch (timelapse) {
case "12h":
date_begin = moment().subtract(720, 'minutes').unix();
scale = '30min';
break;
case "1d":
date_begin = moment().subtract(1440, 'minutes').unix();
scale = '30min';
break;
case "1m":
date_begin = moment().subtract(1, 'months').unix();
scale = '1day';
break;
}
const params = new URLSearchParams();
params.append('access_token', getState().netatmo.access_token as string);
params.append('device_id', device);
params.append('module_id', module);
params.append('scale', scale);
params.append('type', types.toString());
params.append('date_begin', date_begin.toString());
params.append('date_end', moment().unix().toString());
return fetch('/netatmo-measure', {method: 'POST', body: params})
.then(response => {
if (!response.ok) throw response;
return response.json()
})
.then(json => {
const dataChart = new NetatmoChartsData(json.body, types, getState().application.user);
dispatch(successMeasures(dataChart.data, module_name, timelapse))
})
.catch(error => {
// Todo types
error.json().then((errorMessage: any) => {
dispatch(failureMeasures(errorMessage, module_name))
})
});
}
}
};
export const onChangeSelectedType = (type: DataTypes, module: string) => {
return {
type: NetatmoActionTypes.CHANGE_SELECTED_TYPE,
payload: type,
module: module
}
}
export const onChangeSelectedInsideModule = (module: number) => {
return {
type: NetatmoActionTypes.CHANGE_SELECTED_INSIDE_MODULE,
payload: module,
}
} | the_stack |
import React, { useState } from "react";
import { BindComponentRenderProp, Form, BindComponent } from "@webiny/form";
import {
FbFormModelField,
FormLayoutComponent,
FormRenderFbFormModelField
} from "@webiny/app-form-builder/types";
import { validation } from "@webiny/validation";
import { RichTextRenderer } from "@webiny/react-rich-text-renderer";
import Input from "./fields/Input";
import Select from "./fields/Select";
import Radio from "./fields/Radio";
import Checkbox from "./fields/Checkbox";
import Textarea from "./fields/Textarea";
import HelperMessage from "./components/HelperMessage";
import { FormRenderPropParamsSubmit } from "@webiny/form";
/**
* This is the default form layout component, in which we render all the form fields. We also render terms of service
* and reCAPTCHA (if enabled in form settings), and at the bottom, the submit button. Note that we also utilized
* the "webiny-form" package, which makes working with forms and form fields a walk in the park.
*
* Feel free to use this component as your starting point for your own form layouts. Add or remove things as you like!
*/
const DefaultFormLayout: FormLayoutComponent = ({
getFields,
getDefaultValues,
submit,
formData,
ReCaptcha,
TermsOfService
}) => {
// Is the form in loading (submitting) state?
const [loading, setLoading] = useState(false);
// Is the form successfully submitted?
const [formSuccess, setFormSuccess] = useState(false);
// All form fields - an array of rows where each row is an array that contain fields.
const fields = getFields();
/**
* Once the data is successfully submitted, we show a success message.
*/
const submitForm = async (data: Record<string, any>): Promise<void> => {
setLoading(true);
const result = await submit(data);
setLoading(false);
if (result.error === null) {
setFormSuccess(true);
}
};
/**
* Renders a field cell with a field element inside.
*/
const renderFieldCell = (field: FormRenderFbFormModelField, Bind: BindComponent) => {
return (
<div
key={field._id}
className={
"webiny-pb-base-page-element-style webiny-pb-layout-column webiny-fb-form-layout-column"
}
>
<Bind name={field.fieldId} validators={field.validators}>
{bind => (
<React.Fragment>
{/* Render element */}
{renderFieldElement({
field,
bind
})}
</React.Fragment>
)}
</Bind>
</div>
);
};
/**
* Renders hidden fields.
*/
const renderHiddenField = (field: FormRenderFbFormModelField, Bind: BindComponent) => {
return (
<Bind name={field.fieldId} validators={field.validators}>
{bind => (
<React.Fragment>
{/* Render input */}
{renderFieldElement({
field,
bind
})}
</React.Fragment>
)}
</Bind>
);
};
/**
* Renders a single form field. You can add additional handling of other field types if needed.
* All of these components are located in the "./fields" folder.
*/
const renderFieldElement = (props: {
field: FbFormModelField;
bind: BindComponentRenderProp;
}) => {
switch (props.field.type) {
case "text":
return <Input {...props} />;
case "textarea":
return <Textarea {...props} />;
case "number":
return <Input {...props} type="number" />;
case "select":
return <Select {...props} />;
case "radio":
return <Radio {...props} />;
case "checkbox":
return <Checkbox {...props} />;
case "hidden":
return <input type="hidden" value={props.bind.value} />;
default:
return <span>Cannot render field.</span>;
}
};
/**
* Renders Google reCAPTCHA field (checkbox) - to protect us from spam and bots.
* For this we use the provided ReCaptcha component, which is a render prop component and a regular component
* at the same time, depending if the function was passed as its children. If no children are present, then
* it will render the actual Google reCAPTCHA field.
* Note that you don't have to worry if the reCAPTCHA was actually enabled via the Form Editor - the component
* does necessary checks internally and will not render anything if it isn't supposed to.
*/
const renderReCaptcha = (Bind: BindComponent) => {
return (
<ReCaptcha>
{({ errorMessage }) => (
<div className="webiny-fb-form-recaptcha">
<Bind name={"reCaptcha"} validators={validation.create("required")}>
{({ onChange, validation }) => (
<>
<ReCaptcha onChange={onChange} />
<HelperMessage
isValid={validation.isValid}
errorMessage={errorMessage}
/>
</>
)}
</Bind>
</div>
)}
</ReCaptcha>
);
};
/**
* Renders the Terms of Service checkbox - which forces the user to agree to our Terms of Service
* before actually submitting the form.
* For this we use the provided TermsOfService component, which is a simple render prop component.
* Note that you don't have to worry if the terms of service option was actually enabled via the Form Editor -
* the component does necessary checks internally and will not render anything if it isn't supposed to.
*/
const renderTermsOfService = (Bind: BindComponent) => {
return (
<TermsOfService>
{({ message, errorMessage, onChange }) => (
<div className="webiny-fb-form-tos">
<Bind
name={"tosAccepted"}
validators={validation.create("required")}
afterChange={onChange}
>
{({ onChange, value, validation }) => (
<div className="webiny-fb-form-field webiny-fb-form-field--checkbox">
<div className="webiny-fb-form-field__checkbox-group">
<div className="webiny-fb-form-field__checkbox">
<input
className="webiny-fb-form-field__checkbox-input"
type={"checkbox"}
name="webiny-tos-checkbox"
id="webiny-tos-checkbox"
checked={Boolean(value)}
onChange={() => onChange(!value)}
/>
<label
htmlFor={"webiny-tos-checkbox"}
className="webiny-fb-form-field__checkbox-label"
>
<RichTextRenderer data={message} />
</label>
</div>
</div>
<HelperMessage
isValid={validation.isValid}
errorMessage={errorMessage}
/>
</div>
)}
</Bind>
</div>
)}
</TermsOfService>
);
};
/**
* Renders the success message.
*/
const renderSuccessMessage = () => {
return (
<div
className={
"webiny-pb-base-page-element-style webiny-pb-layout-row webiny-fb-form-layout-row"
}
>
<div
className={
"webiny-pb-base-page-element-style webiny-pb-layout-column webiny-fb-form-layout-column"
}
>
<div className="webiny-fb-form-form__success-message">
<div className="webiny-fb-form-field__label webiny-pb-typography-h3">
{formData.settings.successMessage ? (
<RichTextRenderer data={formData.settings.successMessage} />
) : (
"Thanks!"
)}
</div>
</div>
</div>
</div>
);
};
/**
* Renders the form submit button. We disable the button if the form is in the loading state.
*/
const renderSubmitButton = (
submit: FormRenderPropParamsSubmit,
loading: boolean,
buttonLabel: string
) => {
return (
<div className="webiny-fb-form-submit-button">
<button
className={
"webiny-fb-form-page-element-button webiny-pb-page-element-button webiny-pb-page-element-button--primary" +
(loading ? " webiny-pb-element-button--loading" : "")
}
onClick={submit}
disabled={loading}
>
{buttonLabel || "Submit"}
</button>
</div>
);
};
return (
/* "onSubmit" callback gets triggered once all of the fields are valid. */
/* We also pass the default values for all fields via the getDefaultValues callback. */
<Form onSubmit={submitForm} data={getDefaultValues()}>
{({ submit, Bind }) => (
<div className={"webiny-fb-form"}>
{formSuccess ? (
renderSuccessMessage()
) : (
<>
{/* Let's render all form fields. */}
<div>
{fields.map((row, rowIndex) => (
<div
key={rowIndex}
className={
"webiny-pb-base-page-element-style webiny-pb-layout-row webiny-fb-form-layout-row"
}
>
{/* render form fields */}
{row.map(field =>
field.type !== "hidden"
? renderFieldCell(field, Bind)
: renderHiddenField(field, Bind)
)}
</div>
))}
</div>
{/*
At the bottom of the Form, we render the terms of service,
the reCAPTCHA field and the submit button.
*/}
{renderTermsOfService(Bind)}
{renderReCaptcha(Bind)}
{renderSubmitButton(
submit,
loading,
formData.settings.submitButtonLabel
)}
</>
)}
</div>
)}
</Form>
);
};
export default DefaultFormLayout; | the_stack |
import { createLogger } from '@surgio/logger';
import assert from 'assert';
import fs from 'fs-extra';
import _ from 'lodash';
import os from 'os';
import { join } from 'path';
import queryString from 'query-string';
import { JsonObject } from 'type-fest';
import { URL, URLSearchParams } from 'url';
import URLSafeBase64 from 'urlsafe-base64';
import YAML from 'yaml';
import net from 'net';
import {
NodeFilterType,
NodeNameFilterType,
NodeTypeEnum,
PlainObjectOf,
PossibleNodeConfigType,
ProxyGroupModifier,
ShadowsocksNodeConfig,
ShadowsocksrNodeConfig,
SimpleNodeConfig,
SortedNodeNameFilterType,
VmessNodeConfig,
} from '../types';
import { ERR_INVALID_FILTER, OBFS_UA } from '../constant';
import { validateFilter, applyFilter } from './filter';
import { formatVmessUri } from './v2ray';
export * from './surge';
export * from './clash';
export * from './quantumult';
const logger = createLogger({ service: 'surgio:utils' });
export const getDownloadUrl = (
baseUrl = '/',
artifactName: string,
inline = true,
accessToken?: string,
): string => {
let urlSearchParams: URLSearchParams;
let name: string;
if (artifactName.includes('?')) {
urlSearchParams = new URLSearchParams(artifactName.split('?')[1]);
name = artifactName.split('?')[0];
} else {
urlSearchParams = new URLSearchParams();
name = artifactName;
}
if (accessToken) {
urlSearchParams.set('access_token', accessToken);
}
if (!inline) {
urlSearchParams.set('dl', '1');
}
const query = urlSearchParams.toString();
return `${baseUrl}${name}${query ? '?' + query : ''}`;
};
export const getUrl = (
baseUrl: string,
path: string,
accessToken?: string,
): string => {
path = path.replace(/^\//, '');
const url = new URL(path, baseUrl);
if (accessToken) {
url.searchParams.set('access_token', accessToken);
}
return url.toString();
};
export const getMellowNodes = function (
list: ReadonlyArray<VmessNodeConfig | ShadowsocksNodeConfig>,
filter?: NodeFilterType | SortedNodeNameFilterType,
): string {
// istanbul ignore next
if (arguments.length === 2 && typeof filter === 'undefined') {
throw new Error(ERR_INVALID_FILTER);
}
const result = applyFilter(list, filter)
.map((nodeConfig) => {
switch (nodeConfig.type) {
case NodeTypeEnum.Vmess: {
const uri = formatVmessUri(nodeConfig, { isMellow: true });
return [
nodeConfig.nodeName,
'vmess1',
uri.trim().replace('vmess://', 'vmess1://'),
].join(', ');
}
case NodeTypeEnum.Shadowsocks: {
const uri = getShadowsocksNodes([nodeConfig]);
return [nodeConfig.nodeName, 'ss', uri.trim()].join(', ');
}
// istanbul ignore next
default:
logger.warn(
`不支持为 Mellow 生成 ${(nodeConfig as any).type} 的节点,节点 ${
(nodeConfig as any).nodeName
} 会被省略`,
);
return null;
}
})
.filter((item) => !!item);
return result.join('\n');
};
// istanbul ignore next
export const toUrlSafeBase64 = (str: string): string =>
URLSafeBase64.encode(Buffer.from(str, 'utf8'));
// istanbul ignore next
export const fromUrlSafeBase64 = (str: string): string => {
if (URLSafeBase64.validate(str)) {
return URLSafeBase64.decode(str).toString();
}
return fromBase64(str);
};
// istanbul ignore next
export const toBase64 = (str: string): string =>
Buffer.from(str, 'utf8').toString('base64');
// istanbul ignore next
export const fromBase64 = (str: string): string =>
Buffer.from(str, 'base64').toString('utf8');
/**
* @see https://github.com/shadowsocks/shadowsocks-org/wiki/SIP002-URI-Scheme
*/
export const getShadowsocksNodes = (
list: ReadonlyArray<ShadowsocksNodeConfig>,
groupName = 'Surgio',
): string => {
const result: ReadonlyArray<any> = list
.map((nodeConfig) => {
// istanbul ignore next
if (nodeConfig.enable === false) {
return null;
}
switch (nodeConfig.type) {
case NodeTypeEnum.Shadowsocks: {
const config = _.cloneDeep(nodeConfig);
const query: {
readonly plugin?: string;
readonly group?: string;
} = {
...(config.obfs
? {
plugin: `${encodeURIComponent(
`obfs-local;obfs=${config.obfs};obfs-host=${config['obfs-host']}`,
)}`,
}
: null),
...(groupName ? { group: encodeURIComponent(groupName) } : null),
};
return [
'ss://',
toUrlSafeBase64(`${config.method}:${config.password}`),
'@',
config.hostname,
':',
config.port,
'/?',
queryString.stringify(query, {
encode: false,
sort: false,
}),
'#',
encodeURIComponent(config.nodeName),
].join('');
}
// istanbul ignore next
default:
logger.warn(
`在生成 Shadowsocks 节点时出现了 ${nodeConfig.type} 节点,节点 ${nodeConfig.nodeName} 会被省略`,
);
return null;
}
})
.filter((item) => !!item);
return result.join('\n');
};
export const getShadowsocksrNodes = (
list: ReadonlyArray<ShadowsocksrNodeConfig>,
groupName: string,
): string => {
const result: ReadonlyArray<string | undefined> = list
.map((nodeConfig) => {
// istanbul ignore next
if (nodeConfig.enable === false) {
return void 0;
}
switch (nodeConfig.type) {
case NodeTypeEnum.Shadowsocksr: {
const baseUri = [
nodeConfig.hostname,
nodeConfig.port,
nodeConfig.protocol,
nodeConfig.method,
nodeConfig.obfs,
toUrlSafeBase64(nodeConfig.password),
].join(':');
const query = {
obfsparam: toUrlSafeBase64(nodeConfig.obfsparam),
protoparam: toUrlSafeBase64(nodeConfig.protoparam),
remarks: toUrlSafeBase64(nodeConfig.nodeName),
group: toUrlSafeBase64(groupName),
udpport: 0,
uot: 0,
};
return (
'ssr://' +
toUrlSafeBase64(
[
baseUri,
'/?',
queryString.stringify(query, {
encode: false,
}),
].join(''),
)
);
}
// istanbul ignore next
default:
logger.warn(
`在生成 Shadowsocksr 节点时出现了 ${nodeConfig.type} 节点,节点 ${nodeConfig.nodeName} 会被省略`,
);
return void 0;
}
})
.filter((item) => item !== undefined);
return result.join('\n');
};
export const getV2rayNNodes = (
list: ReadonlyArray<VmessNodeConfig>,
): string => {
const result: ReadonlyArray<string> = list
.map((nodeConfig): string | undefined => {
// istanbul ignore next
if (nodeConfig.enable === false) {
return void 0;
}
switch (nodeConfig.type) {
case NodeTypeEnum.Vmess: {
const json = {
v: '2',
ps: nodeConfig.nodeName,
add: nodeConfig.hostname,
port: `${nodeConfig.port}`,
id: nodeConfig.uuid,
aid: nodeConfig.alterId,
net: nodeConfig.network,
type: 'none',
host: nodeConfig.host,
path: nodeConfig.path,
tls: nodeConfig.tls ? 'tls' : '',
};
return 'vmess://' + toBase64(JSON.stringify(json));
}
// istanbul ignore next
default:
logger.warn(
`在生成 V2Ray 节点时出现了 ${nodeConfig.type} 节点,节点 ${nodeConfig.nodeName} 会被省略`,
);
return void 0;
}
})
.filter((item): item is string => item !== undefined);
return result.join('\n');
};
// istanbul ignore next
export const getShadowsocksNodesJSON = (
list: ReadonlyArray<ShadowsocksNodeConfig>,
): string => {
const nodes: ReadonlyArray<any> = list
.map((nodeConfig) => {
// istanbul ignore next
if (nodeConfig.enable === false) {
return null;
}
switch (nodeConfig.type) {
case NodeTypeEnum.Shadowsocks: {
const useObfs = Boolean(nodeConfig.obfs && nodeConfig['obfs-host']);
return {
remarks: nodeConfig.nodeName,
server: nodeConfig.hostname,
server_port: nodeConfig.port,
method: nodeConfig.method,
remarks_base64: toUrlSafeBase64(nodeConfig.nodeName),
password: nodeConfig.password,
tcp_over_udp: false,
udp_over_tcp: false,
enable: true,
...(useObfs
? {
plugin: 'obfs-local',
'plugin-opts': `obfs=${nodeConfig.obfs};obfs-host=${nodeConfig['obfs-host']}`,
}
: null),
};
}
// istanbul ignore next
default:
logger.warn(
`在生成 Shadowsocks 节点时出现了 ${nodeConfig.type} 节点,节点 ${nodeConfig.nodeName} 会被省略`,
);
return undefined;
}
})
.filter((item) => item !== undefined);
return JSON.stringify(nodes, null, 2);
};
export const getNodeNames = function (
list: ReadonlyArray<SimpleNodeConfig>,
filter?: NodeNameFilterType | SortedNodeNameFilterType,
separator?: string,
): string {
// istanbul ignore next
if (arguments.length === 2 && typeof filter === 'undefined') {
throw new Error(ERR_INVALID_FILTER);
}
return applyFilter(list, filter)
.map((item) => item.nodeName)
.join(separator || ', ');
};
export const generateClashProxyGroup = (
ruleName: string,
ruleType: 'select' | 'url-test' | 'fallback' | 'load-balance',
nodeNameList: ReadonlyArray<SimpleNodeConfig>,
options: {
readonly filter?: NodeNameFilterType | SortedNodeNameFilterType;
readonly existingProxies?: ReadonlyArray<string>;
readonly proxyTestUrl?: string;
readonly proxyTestInterval?: number;
},
): {
readonly type: string;
readonly name: string;
readonly proxies: readonly string[];
readonly url?: string;
readonly interval?: number;
} => {
let proxies;
if (options.existingProxies) {
if (options.filter) {
const nodes = applyFilter(nodeNameList, options.filter);
proxies = ([] as string[]).concat(
options.existingProxies,
nodes.map((item) => item.nodeName),
);
} else {
proxies = options.existingProxies;
}
} else {
const nodes = applyFilter(nodeNameList, options.filter);
proxies = nodes.map((item) => item.nodeName);
}
return {
type: ruleType,
name: ruleName,
proxies,
...(['url-test', 'fallback', 'load-balance'].includes(ruleType)
? {
url: options.proxyTestUrl,
interval: options.proxyTestInterval,
}
: null),
};
};
export const toYaml = (obj: JsonObject): string => YAML.stringify(obj);
export const pickAndFormatStringList = (
obj: any,
keyList: readonly string[],
): readonly string[] => {
const result: string[] = [];
keyList.forEach((key) => {
if (obj.hasOwnProperty(key)) {
result.push(`${key}=${obj[key]}`);
}
});
return result;
};
export const decodeStringList = <T = Record<string, string | boolean>>(
stringList: ReadonlyArray<string>,
): T => {
const result = {};
stringList.forEach((item) => {
if (item.includes('=')) {
const match = item.match(/^(.*?)=(.*?)$/);
if (match) {
result[match[1].trim()] = match[2].trim() || true;
}
} else {
result[item.trim()] = true;
}
});
return result as T;
};
export const normalizeClashProxyGroupConfig = (
nodeList: ReadonlyArray<PossibleNodeConfigType>,
customFilters: PlainObjectOf<NodeNameFilterType | SortedNodeNameFilterType>,
proxyGroupModifier: ProxyGroupModifier,
options: {
readonly proxyTestUrl?: string;
readonly proxyTestInterval?: number;
} = {},
): ReadonlyArray<any> => {
const proxyGroup = proxyGroupModifier(nodeList, customFilters);
return proxyGroup.map((item) => {
if (item.hasOwnProperty('filter')) {
// istanbul ignore next
if (!item.filter || !validateFilter(item.filter)) {
throw new Error(
`过滤器 ${item.filter} 无效,请检查 proxyGroupModifier`,
);
}
return generateClashProxyGroup(item.name, item.type, nodeList, {
filter: item.filter,
existingProxies: item.proxies,
proxyTestUrl: options.proxyTestUrl,
proxyTestInterval: options.proxyTestInterval,
});
} else {
return generateClashProxyGroup(item.name, item.type, nodeList, {
existingProxies: item.proxies,
proxyTestUrl: options.proxyTestUrl,
proxyTestInterval: options.proxyTestInterval,
});
}
});
};
export const ensureConfigFolder = (dir: string = os.homedir()): string => {
let baseDir;
try {
fs.accessSync(dir, fs.constants.W_OK);
baseDir = dir;
} catch (err) {
// if the user do not have write permission
// istanbul ignore next
baseDir = '/tmp';
}
const configDir = join(baseDir, '.config/surgio');
fs.mkdirpSync(configDir);
return configDir;
};
export const formatV2rayConfig = (
localPort: number,
nodeConfig: VmessNodeConfig,
): JsonObject => {
const config: any = {
log: {
loglevel: 'warning',
},
inbound: {
port: Number(localPort),
listen: '127.0.0.1',
protocol: 'socks',
settings: {
auth: 'noauth',
},
},
outbound: {
protocol: 'vmess',
settings: {
vnext: [
{
address: nodeConfig.hostname,
port: Number(nodeConfig.port),
users: [
{
id: nodeConfig.uuid,
alterId: Number(nodeConfig.alterId),
security: nodeConfig.method,
level: 0,
},
],
},
],
},
streamSettings: {
security: 'none',
},
},
};
if (nodeConfig.tls) {
config.outbound.streamSettings = {
...config.outbound.streamSettings,
security: 'tls',
tlsSettings: {
serverName: nodeConfig.host || nodeConfig.hostname,
...(typeof nodeConfig.skipCertVerify === 'boolean'
? {
allowInsecure: nodeConfig.skipCertVerify,
}
: null),
...(typeof nodeConfig.tls13 === 'boolean'
? {
allowInsecureCiphers: !nodeConfig.tls13,
}
: null),
},
};
}
if (nodeConfig.network === 'ws') {
config.outbound.streamSettings = {
...config.outbound.streamSettings,
network: nodeConfig.network,
wsSettings: {
path: nodeConfig.path,
headers: {
Host: nodeConfig.host,
'User-Agent': OBFS_UA,
},
},
};
}
return config;
};
export const lowercaseHeaderKeys = (
headers: Record<string, string>,
): Record<string, string> => {
const wsHeaders = {};
Object.keys(headers).forEach((key) => {
wsHeaders[key.toLowerCase()] = headers[key];
});
return wsHeaders;
};
export const msToSeconds = (ms: number): number => Math.floor(ms / 1000);
// istanbul ignore next
export const isIp = (str: string): boolean =>
net.isIPv4(str) || net.isIPv6(str);
// istanbul ignore next
export const isNow = (): boolean =>
typeof process.env.NOW_REGION !== 'undefined' ||
typeof process.env.VERCEL_REGION !== 'undefined';
// istanbul ignore next
export const isVercel = (): boolean => isNow();
// istanbul ignore next
export const isHeroku = (): boolean => typeof process.env.DYNO !== 'undefined';
// istanbul ignore next
export const isGitHubActions = (): boolean =>
typeof process.env.GITHUB_ACTIONS !== 'undefined';
// istanbul ignore next
export const isGitLabCI = (): boolean =>
typeof process.env.GITLAB_CI !== 'undefined';
// istanbul ignore next
export const isPkgBundle = (): boolean => __dirname.startsWith('/snapshot');
// istanbul ignore next
export const isRailway = (): boolean =>
typeof process.env.RAILWAY_STATIC_URL !== 'undefined';
// istanbul ignore next
export const isNetlify = (): boolean =>
typeof process.env.NETLIFY !== 'undefined'; | the_stack |
import React from 'react';
import { EventType } from "matrix-js-sdk/src/@types/event";
import { RoomMember } from "matrix-js-sdk/src/models/room-member";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { RoomState } from "matrix-js-sdk/src/models/room-state";
import { logger } from "matrix-js-sdk/src/logger";
import { _t, _td } from "../../../../../languageHandler";
import { MatrixClientPeg } from "../../../../../MatrixClientPeg";
import AccessibleButton from "../../../elements/AccessibleButton";
import Modal from "../../../../../Modal";
import { replaceableComponent } from "../../../../../utils/replaceableComponent";
import { compare } from "../../../../../utils/strings";
import ErrorDialog from '../../../dialogs/ErrorDialog';
import PowerSelector from "../../../elements/PowerSelector";
import SettingsFieldset from '../../SettingsFieldset';
import SettingsStore from "../../../../../settings/SettingsStore";
interface IEventShowOpts {
isState?: boolean;
hideForSpace?: boolean;
hideForRoom?: boolean;
}
interface IPowerLevelDescriptor {
desc: string;
defaultValue: number;
hideForSpace?: boolean;
}
const plEventsToShow: Record<string, IEventShowOpts> = {
// If an event is listed here, it will be shown in the PL settings. Defaults will be calculated.
[EventType.RoomAvatar]: { isState: true },
[EventType.RoomName]: { isState: true },
[EventType.RoomCanonicalAlias]: { isState: true },
[EventType.SpaceChild]: { isState: true, hideForRoom: true },
[EventType.RoomHistoryVisibility]: { isState: true, hideForSpace: true },
[EventType.RoomPowerLevels]: { isState: true },
[EventType.RoomTopic]: { isState: true },
[EventType.RoomTombstone]: { isState: true, hideForSpace: true },
[EventType.RoomEncryption]: { isState: true, hideForSpace: true },
[EventType.RoomServerAcl]: { isState: true, hideForSpace: true },
[EventType.RoomPinnedEvents]: { isState: true, hideForSpace: true },
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
"im.vector.modular.widgets": { isState: true, hideForSpace: true },
};
// parse a string as an integer; if the input is undefined, or cannot be parsed
// as an integer, return a default.
function parseIntWithDefault(val, def) {
const res = parseInt(val);
return isNaN(res) ? def : res;
}
interface IBannedUserProps {
canUnban?: boolean;
member: RoomMember;
by: string;
reason?: string;
}
export class BannedUser extends React.Component<IBannedUserProps> {
private onUnbanClick = (e) => {
MatrixClientPeg.get().unban(this.props.member.roomId, this.props.member.userId).catch((err) => {
logger.error("Failed to unban: " + err);
Modal.createTrackedDialog('Failed to unban', '', ErrorDialog, {
title: _t('Error'),
description: _t('Failed to unban'),
});
});
};
render() {
let unbanButton;
if (this.props.canUnban) {
unbanButton = (
<AccessibleButton className='mx_RolesRoomSettingsTab_unbanBtn'
kind='danger_sm'
onClick={this.onUnbanClick}
>
{ _t('Unban') }
</AccessibleButton>
);
}
const userId = this.props.member.name === this.props.member.userId ? null : this.props.member.userId;
return (
<li>
{ unbanButton }
<span title={_t("Banned by %(displayName)s", { displayName: this.props.by })}>
<strong>{ this.props.member.name }</strong> { userId }
{ this.props.reason ? " " + _t('Reason') + ": " + this.props.reason : "" }
</span>
</li>
);
}
}
interface IProps {
roomId: string;
}
@replaceableComponent("views.settings.tabs.room.RolesRoomSettingsTab")
export default class RolesRoomSettingsTab extends React.Component<IProps> {
componentDidMount() {
MatrixClientPeg.get().on("RoomState.members", this.onRoomMembership);
}
componentWillUnmount() {
const client = MatrixClientPeg.get();
if (client) {
client.removeListener("RoomState.members", this.onRoomMembership);
}
}
private onRoomMembership = (event: MatrixEvent, state: RoomState, member: RoomMember) => {
if (state.roomId !== this.props.roomId) return;
this.forceUpdate();
};
private populateDefaultPlEvents(eventsSection: Record<string, number>, stateLevel: number, eventsLevel: number) {
for (const desiredEvent of Object.keys(plEventsToShow)) {
if (!(desiredEvent in eventsSection)) {
eventsSection[desiredEvent] = (plEventsToShow[desiredEvent].isState ? stateLevel : eventsLevel);
}
}
}
private onPowerLevelsChanged = (value: number, powerLevelKey: string) => {
const client = MatrixClientPeg.get();
const room = client.getRoom(this.props.roomId);
const plEvent = room.currentState.getStateEvents(EventType.RoomPowerLevels, '');
let plContent = plEvent ? (plEvent.getContent() || {}) : {};
// Clone the power levels just in case
plContent = Object.assign({}, plContent);
const eventsLevelPrefix = "event_levels_";
if (powerLevelKey.startsWith(eventsLevelPrefix)) {
// deep copy "events" object, Object.assign itself won't deep copy
plContent["events"] = Object.assign({}, plContent["events"] || {});
plContent["events"][powerLevelKey.slice(eventsLevelPrefix.length)] = value;
} else {
const keyPath = powerLevelKey.split('.');
let parentObj;
let currentObj = plContent;
for (const key of keyPath) {
if (!currentObj[key]) {
currentObj[key] = {};
}
parentObj = currentObj;
currentObj = currentObj[key];
}
parentObj[keyPath[keyPath.length - 1]] = value;
}
client.sendStateEvent(this.props.roomId, EventType.RoomPowerLevels, plContent).catch(e => {
logger.error(e);
Modal.createTrackedDialog('Power level requirement change failed', '', ErrorDialog, {
title: _t('Error changing power level requirement'),
description: _t(
"An error occurred changing the room's power level requirements. Ensure you have sufficient " +
"permissions and try again.",
),
});
});
};
private onUserPowerLevelChanged = (value: number, powerLevelKey: string) => {
const client = MatrixClientPeg.get();
const room = client.getRoom(this.props.roomId);
const plEvent = room.currentState.getStateEvents(EventType.RoomPowerLevels, '');
let plContent = plEvent ? (plEvent.getContent() || {}) : {};
// Clone the power levels just in case
plContent = Object.assign({}, plContent);
// powerLevelKey should be a user ID
if (!plContent['users']) plContent['users'] = {};
plContent['users'][powerLevelKey] = value;
client.sendStateEvent(this.props.roomId, EventType.RoomPowerLevels, plContent).catch(e => {
logger.error(e);
Modal.createTrackedDialog('Power level change failed', '', ErrorDialog, {
title: _t('Error changing power level'),
description: _t(
"An error occurred changing the user's power level. Ensure you have sufficient " +
"permissions and try again.",
),
});
});
};
render() {
const client = MatrixClientPeg.get();
const room = client.getRoom(this.props.roomId);
const isSpaceRoom = room.isSpaceRoom();
const plEvent = room.currentState.getStateEvents(EventType.RoomPowerLevels, '');
const plContent = plEvent ? (plEvent.getContent() || {}) : {};
const canChangeLevels = room.currentState.mayClientSendStateEvent(EventType.RoomPowerLevels, client);
const plEventsToLabels = {
// These will be translated for us later.
[EventType.RoomAvatar]: isSpaceRoom ? _td("Change space avatar") : _td("Change room avatar"),
[EventType.RoomName]: isSpaceRoom ? _td("Change space name") : _td("Change room name"),
[EventType.RoomCanonicalAlias]: isSpaceRoom
? _td("Change main address for the space")
: _td("Change main address for the room"),
[EventType.SpaceChild]: _td("Manage rooms in this space"),
[EventType.RoomHistoryVisibility]: _td("Change history visibility"),
[EventType.RoomPowerLevels]: _td("Change permissions"),
[EventType.RoomTopic]: isSpaceRoom ? _td("Change description") : _td("Change topic"),
[EventType.RoomTombstone]: _td("Upgrade the room"),
[EventType.RoomEncryption]: _td("Enable room encryption"),
[EventType.RoomServerAcl]: _td("Change server ACLs"),
// TODO: Enable support for m.widget event type (https://github.com/vector-im/element-web/issues/13111)
"im.vector.modular.widgets": isSpaceRoom ? null : _td("Modify widgets"),
};
if (SettingsStore.getValue("feature_pinning")) {
plEventsToLabels[EventType.RoomPinnedEvents] = _td("Manage pinned events");
}
const powerLevelDescriptors: Record<string, IPowerLevelDescriptor> = {
"users_default": {
desc: _t('Default role'),
defaultValue: 0,
},
"events_default": {
desc: _t('Send messages'),
defaultValue: 0,
hideForSpace: true,
},
"invite": {
desc: _t('Invite users'),
defaultValue: 50,
},
"state_default": {
desc: _t('Change settings'),
defaultValue: 50,
},
"kick": {
desc: _t('Kick users'),
defaultValue: 50,
},
"ban": {
desc: _t('Ban users'),
defaultValue: 50,
},
"redact": {
desc: _t('Remove messages sent by others'),
defaultValue: 50,
hideForSpace: true,
},
"notifications.room": {
desc: _t('Notify everyone'),
defaultValue: 50,
hideForSpace: true,
},
};
const eventsLevels = plContent.events || {};
const userLevels = plContent.users || {};
const banLevel = parseIntWithDefault(plContent.ban, powerLevelDescriptors.ban.defaultValue);
const defaultUserLevel = parseIntWithDefault(
plContent.users_default,
powerLevelDescriptors.users_default.defaultValue,
);
let currentUserLevel = userLevels[client.getUserId()];
if (currentUserLevel === undefined) {
currentUserLevel = defaultUserLevel;
}
this.populateDefaultPlEvents(
eventsLevels,
parseIntWithDefault(plContent.state_default, powerLevelDescriptors.state_default.defaultValue),
parseIntWithDefault(plContent.events_default, powerLevelDescriptors.events_default.defaultValue),
);
let privilegedUsersSection = <div>{ _t('No users have specific privileges in this room') }</div>;
let mutedUsersSection;
if (Object.keys(userLevels).length) {
const privilegedUsers = [];
const mutedUsers = [];
Object.keys(userLevels).forEach((user) => {
if (!Number.isInteger(userLevels[user])) { return; }
const canChange = userLevels[user] < currentUserLevel && canChangeLevels;
if (userLevels[user] > defaultUserLevel) { // privileged
privilegedUsers.push(
<PowerSelector
value={userLevels[user]}
disabled={!canChange}
label={user}
key={user}
powerLevelKey={user} // Will be sent as the second parameter to `onChange`
onChange={this.onUserPowerLevelChanged}
/>,
);
} else if (userLevels[user] < defaultUserLevel) { // muted
mutedUsers.push(
<PowerSelector
value={userLevels[user]}
disabled={!canChange}
label={user}
key={user}
powerLevelKey={user} // Will be sent as the second parameter to `onChange`
onChange={this.onUserPowerLevelChanged}
/>,
);
}
});
// comparator for sorting PL users lexicographically on PL descending, MXID ascending. (case-insensitive)
const comparator = (a, b) => {
const plDiff = userLevels[b.key] - userLevels[a.key];
return plDiff !== 0 ? plDiff : compare(a.key.toLocaleLowerCase(), b.key.toLocaleLowerCase());
};
privilegedUsers.sort(comparator);
mutedUsers.sort(comparator);
if (privilegedUsers.length) {
privilegedUsersSection =
<SettingsFieldset legend={_t('Privileged Users')}>
{ privilegedUsers }
</SettingsFieldset>;
}
if (mutedUsers.length) {
mutedUsersSection =
<SettingsFieldset legend={_t('Muted Users')}>
{ mutedUsers }
</SettingsFieldset>;
}
}
const banned = room.getMembersWithMembership("ban");
let bannedUsersSection;
if (banned.length) {
const canBanUsers = currentUserLevel >= banLevel;
bannedUsersSection =
<SettingsFieldset legend={_t('Banned users')}>
<ul>
{ banned.map((member) => {
const banEvent = member.events.member.getContent();
const sender = room.getMember(member.events.member.getSender());
let bannedBy = member.events.member.getSender(); // start by falling back to mxid
if (sender) bannedBy = sender.name;
return (
<BannedUser
key={member.userId}
canUnban={canBanUsers}
member={member}
reason={banEvent.reason}
by={bannedBy}
/>
);
}) }
</ul>
</SettingsFieldset>;
}
const powerSelectors = Object.keys(powerLevelDescriptors).map((key, index) => {
const descriptor = powerLevelDescriptors[key];
if (isSpaceRoom && descriptor.hideForSpace) {
return null;
}
const keyPath = key.split('.');
let currentObj = plContent;
for (const prop of keyPath) {
if (currentObj === undefined) {
break;
}
currentObj = currentObj[prop];
}
const value = parseIntWithDefault(currentObj, descriptor.defaultValue);
return <div key={index} className="">
<PowerSelector
label={descriptor.desc}
value={value}
usersDefault={defaultUserLevel}
disabled={!canChangeLevels || currentUserLevel < value}
powerLevelKey={key} // Will be sent as the second parameter to `onChange`
onChange={this.onPowerLevelsChanged}
/>
</div>;
}).filter(Boolean);
// hide the power level selector for enabling E2EE if it the room is already encrypted
if (client.isRoomEncrypted(this.props.roomId)) {
delete eventsLevels[EventType.RoomEncryption];
}
const eventPowerSelectors = Object.keys(eventsLevels).map((eventType, i) => {
if (isSpaceRoom && plEventsToShow[eventType]?.hideForSpace) {
return null;
} else if (!isSpaceRoom && plEventsToShow[eventType]?.hideForRoom) {
return null;
}
let label = plEventsToLabels[eventType];
if (label) {
label = _t(label);
} else {
label = _t("Send %(eventType)s events", { eventType });
}
return (
<div className="" key={eventType}>
<PowerSelector
label={label}
value={eventsLevels[eventType]}
usersDefault={defaultUserLevel}
disabled={!canChangeLevels || currentUserLevel < eventsLevels[eventType]}
powerLevelKey={"event_levels_" + eventType}
onChange={this.onPowerLevelsChanged}
/>
</div>
);
}).filter(Boolean);
return (
<div className="mx_SettingsTab mx_RolesRoomSettingsTab">
<div className="mx_SettingsTab_heading">{ _t("Roles & Permissions") }</div>
{ privilegedUsersSection }
{ mutedUsersSection }
{ bannedUsersSection }
<SettingsFieldset
legend={_t("Permissions")}
description={
isSpaceRoom
? _t('Select the roles required to change various parts of the space')
: _t('Select the roles required to change various parts of the room')
}
>
{ powerSelectors }
{ eventPowerSelectors }
</SettingsFieldset>
</div>
);
}
} | the_stack |
import { mkdtemp as original_mkdtemp } from 'fs'
import * as os from 'os'
import * as path from 'path'
import { promisify } from 'util'
import Octokit from '@octokit/rest'
import commandExists from 'command-exists'
import execa from 'execa'
import * as semver from 'semver'
import { readLine, formatDate, timezoneLink, cacheFolder } from './util'
const mkdtemp = promisify(original_mkdtemp)
export async function getAuthenticatedGitHubClient(): Promise<Octokit> {
const githubPAT = await readLine(
'Enter a GitHub personal access token with "repo" scope (https://github.com/settings/tokens/new): ',
`${cacheFolder}/github.txt`
)
const trimmedGithubPAT = githubPAT.trim()
return new Octokit({ auth: trimmedGithubPAT })
}
/**
* releaseName generates a standardized format for referring to releases.
*/
export function releaseName(release: semver.SemVer): string {
return `${release.major}.${release.minor}${release.patch !== 0 ? `.${release.patch}` : ''}`
}
export enum IssueLabel {
// https://github.com/sourcegraph/sourcegraph/labels/release-tracking
RELEASE_TRACKING = 'release-tracking',
// https://github.com/sourcegraph/sourcegraph/labels/patch-release-request
PATCH_REQUEST = 'patch-release-request',
// New labels to better distinguish release-tracking issues
RELEASE = 'release',
PATCH = 'patch',
MANAGED = 'managed-instances',
}
enum IssueTitleSuffix {
RELEASE_TRACKING = 'release tracking issue',
PATCH_TRACKING = 'patch release tracking issue',
MANAGED_TRACKING = 'upgrade managed instances tracking issue',
}
/**
* Template used to generate tracking issue
*/
interface IssueTemplate {
owner: string
repo: string
/**
* Relative path to markdown file containing template body.
*
* Template bodies can leverage arguments as described in `IssueTemplateArguments` docstrings.
*/
path: string
/**
* Title for issue.
*/
titleSuffix: IssueTitleSuffix
/**
* Labels to apply on issues.
*/
labels: string[]
}
/**
* Arguments available for rendering IssueTemplate
*/
interface IssueTemplateArguments {
/**
* Available as `$MAJOR`, `$MINOR`, and `$PATCH`
*/
version: semver.SemVer
/**
* Available as `$ONE_WORKING_DAY_BEFORE_RELEASE`
*/
oneWorkingDayBeforeRelease: Date
/**
* Available as `$RELEASE_DATE`
*/
releaseDate: Date
/**
* Available as `$ONE_WORKING_DAY_AFTER_RELEASE`
*/
oneWorkingDayAfterRelease: Date
}
/**
* Configure templates for the release tool to generate issues with.
*
* Ensure these templates are up to date with the state of the tooling and release processes.
*/
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const getTemplates = () => {
const releaseIssue: IssueTemplate = {
owner: 'sourcegraph',
repo: 'about',
path: 'handbook/engineering/releases/release_issue_template.md',
titleSuffix: IssueTitleSuffix.RELEASE_TRACKING,
labels: [IssueLabel.RELEASE_TRACKING, IssueLabel.RELEASE],
}
const patchReleaseIssue: IssueTemplate = {
owner: 'sourcegraph',
repo: 'about',
path: 'handbook/engineering/releases/patch_release_issue_template.md',
titleSuffix: IssueTitleSuffix.PATCH_TRACKING,
labels: [IssueLabel.RELEASE_TRACKING, IssueLabel.PATCH],
}
const upgradeManagedInstanceIssue: IssueTemplate = {
owner: 'sourcegraph',
repo: 'about',
path: 'handbook/engineering/releases/upgrade_managed_issue_template.md',
titleSuffix: IssueTitleSuffix.MANAGED_TRACKING,
labels: [IssueLabel.RELEASE_TRACKING, IssueLabel.MANAGED],
}
return { releaseIssue, patchReleaseIssue, upgradeManagedInstanceIssue }
}
async function execTemplate(
octokit: Octokit,
template: IssueTemplate,
{ version, oneWorkingDayBeforeRelease, releaseDate, oneWorkingDayAfterRelease }: IssueTemplateArguments
): Promise<string> {
console.log(`Preparing issue from ${JSON.stringify(template)}`)
const name = releaseName(version)
const content = await getContent(octokit, template)
return content
.replace(/\$MAJOR/g, version.major.toString())
.replace(/\$MINOR/g, version.minor.toString())
.replace(/\$PATCH/g, version.patch.toString())
.replace(
/\$ONE_WORKING_DAY_BEFORE_RELEASE/g,
dateMarkdown(oneWorkingDayBeforeRelease, `One working day before ${name} release`)
)
.replace(/\$RELEASE_DATE/g, dateMarkdown(releaseDate, `${name} release date`))
.replace(
/\$ONE_WORKING_DAY_AFTER_RELEASE/g,
dateMarkdown(oneWorkingDayAfterRelease, `One working day after ${name} release`)
)
}
interface MaybeIssue {
title: string
url: string
number: number
created: boolean
}
/**
* Ensures tracking issues for the given release.
*
* The first returned issue is considered the parent issue.
*/
export async function ensureTrackingIssues({
version,
assignees,
releaseDate,
oneWorkingDayBeforeRelease,
oneWorkingDayAfterRelease,
dryRun,
}: {
version: semver.SemVer
assignees: string[]
releaseDate: Date
oneWorkingDayBeforeRelease: Date
oneWorkingDayAfterRelease: Date
dryRun: boolean
}): Promise<MaybeIssue[]> {
const octokit = await getAuthenticatedGitHubClient()
const templates = getTemplates()
const release = releaseName(version)
// Determine what issues to generate. The first issue is considered the "main"
// tracking issue, and subsequent issues will contain references to it.
let issueTemplates: IssueTemplate[]
if (version.patch === 0) {
issueTemplates = [templates.releaseIssue, templates.upgradeManagedInstanceIssue]
} else {
issueTemplates = [templates.patchReleaseIssue, templates.upgradeManagedInstanceIssue]
}
// Release milestones are not as emphasised now as they used to be, since most teams
// use sprints shorter than releases to track their work. For reference, if one is
// available we apply it to this tracking issue, otherwise just leave it without a
// milestone.
let milestoneNumber: number | undefined
const milestone = await getReleaseMilestone(octokit, version)
if (!milestone) {
console.log(`Milestone ${release} is closed or not found — omitting from issue.`)
} else {
milestoneNumber = milestone ? milestone.number : undefined
}
// Create issues
let parentIssue: MaybeIssue | undefined
const created: MaybeIssue[] = []
for (const template of issueTemplates) {
const body = await execTemplate(octokit, template, {
version,
releaseDate,
oneWorkingDayBeforeRelease,
oneWorkingDayAfterRelease,
})
const issue = await ensureIssue(
octokit,
{
title: trackingIssueTitle(version, template),
labels: template.labels,
body: parentIssue ? `${body}\n\n---\n\nAlso see [${parentIssue.title}](${parentIssue.url})` : body,
assignees,
owner: 'sourcegraph',
repo: 'sourcegraph',
milestone: milestoneNumber,
},
dryRun
)
// if this is the first issue, we treat it as the parent issue
if (!parentIssue) {
parentIssue = { ...issue }
}
created.push({ ...issue })
// close previous iterations of this issue
const previous = await queryIssues(octokit, template.titleSuffix, template.labels)
for (const previousIssue of previous) {
if (previousIssue.number === issue.number) {
// don't close self
continue
}
if (dryRun) {
console.log(`dryRun enabled, skipping closure of #${previousIssue.number} '${previousIssue.title}'`)
continue
}
const comment = await commentOnIssue(octokit, previousIssue, `Superseded by #${issue.number}`)
console.log(
`Closing #${previousIssue.number} '${previousIssue.title}' - commented with an update: ${comment}`
)
await closeIssue(octokit, previousIssue)
}
}
return created
}
async function getContent(
octokit: Octokit,
parameters: {
owner: string
repo: string
path: string
}
): Promise<string> {
const response = await octokit.repos.getContents(parameters)
if (Array.isArray(response.data)) {
throw new TypeError(`${parameters.path} is a directory`)
}
return Buffer.from(response.data.content as string, 'base64').toString()
}
async function ensureIssue(
octokit: Octokit,
{
title,
owner,
repo,
assignees,
body,
milestone,
labels,
}: {
title: string
owner: string
repo: string
assignees: string[]
body: string
milestone?: number
labels: string[]
},
dryRun: boolean
): Promise<MaybeIssue> {
const issueData = {
title,
owner,
repo,
assignees,
milestone,
labels,
}
const issue = await getIssueByTitle(octokit, title, labels)
if (issue) {
return { title, url: issue.url, number: issue.number, created: false }
}
if (dryRun) {
console.log('Dry run enabled, skipping issue creation')
console.log(`Issue that would have been created:\n${JSON.stringify(issueData, null, 1)}`)
console.log(`With body: ${body}`)
return { title, url: '', number: 0, created: false }
}
const createdIssue = await octokit.issues.create({ body, ...issueData })
return { title, url: createdIssue.data.html_url, number: createdIssue.data.number, created: true }
}
export async function listIssues(
octokit: Octokit,
query: string
): Promise<Octokit.SearchIssuesAndPullRequestsResponseItemsItem[]> {
return (await octokit.search.issuesAndPullRequests({ per_page: 100, q: query })).data.items
}
export interface Issue {
title: string
number: number
url: string
// Repository
owner: string
repo: string
}
export async function getTrackingIssue(client: Octokit, release: semver.SemVer): Promise<Issue | null> {
const templates = getTemplates()
const template = release.patch ? templates.patchReleaseIssue : templates.releaseIssue
return getIssueByTitle(client, trackingIssueTitle(release, template), template.labels)
}
function trackingIssueTitle(release: semver.SemVer, template: IssueTemplate): string {
return `${release.version} ${template.titleSuffix}`
}
export async function commentOnIssue(client: Octokit, issue: Issue, body: string): Promise<string> {
const comment = await client.issues.createComment({
body,
issue_number: issue.number,
owner: issue.owner,
repo: issue.repo,
})
return comment.data.url
}
async function closeIssue(client: Octokit, issue: Issue): Promise<void> {
await client.issues.update({
state: 'closed',
issue_number: issue.number,
owner: issue.owner,
repo: issue.repo,
})
}
interface Milestone {
number: number
url: string
// Repository
owner: string
repo: string
}
async function getReleaseMilestone(client: Octokit, release: semver.SemVer): Promise<Milestone | null> {
const owner = 'sourcegraph'
const repo = 'sourcegraph'
const milestoneTitle = releaseName(release)
const milestones = await client.issues.listMilestonesForRepo({
owner,
repo,
per_page: 100,
direction: 'desc',
})
const milestone = milestones.data.filter(milestone => milestone.title === milestoneTitle)
return milestone.length > 0
? {
number: milestone[0].number,
url: milestone[0].html_url,
owner,
repo,
}
: null
}
export async function queryIssues(octokit: Octokit, titleQuery: string, labels: string[]): Promise<Issue[]> {
const owner = 'sourcegraph'
const repo = 'sourcegraph'
const response = await octokit.search.issuesAndPullRequests({
per_page: 100,
q: `type:issue repo:${owner}/${repo} is:open ${labels
.map(label => `label:${label}`)
.join(' ')} ${JSON.stringify(titleQuery)}`,
})
return response.data.items.map(item => ({
title: item.title,
number: item.number,
url: item.html_url,
owner,
repo,
}))
}
async function getIssueByTitle(octokit: Octokit, title: string, labels: string[]): Promise<Issue | null> {
const matchingIssues = (await queryIssues(octokit, title, labels)).filter(issue => issue.title === title)
if (matchingIssues.length === 0) {
return null
}
if (matchingIssues.length > 1) {
throw new Error(`Multiple issues matched issue title ${JSON.stringify(title)}`)
}
return matchingIssues[0]
}
export type EditFunc = (d: string) => void
export type Edit = string | EditFunc
export interface CreateBranchWithChangesOptions {
owner: string
repo: string
base: string
head: string
commitMessage: string
edits: Edit[]
dryRun?: boolean
}
export interface ChangesetsOptions {
requiredCommands: string[]
changes: (Octokit.PullsCreateParams & CreateBranchWithChangesOptions)[]
dryRun?: boolean
}
export interface CreatedChangeset {
repository: string
branch: string
pullRequestURL: string
pullRequestNumber: number
}
export async function createChangesets(options: ChangesetsOptions): Promise<CreatedChangeset[]> {
for (const command of options.requiredCommands) {
try {
await commandExists(command)
} catch {
throw new Error(`Required command ${command} does not exist`)
}
}
const octokit = await getAuthenticatedGitHubClient()
if (options.dryRun) {
console.log('Changesets dry run enabled - diffs and pull requests will be printed instead')
} else {
console.log('Generating changes and publishing as pull requests')
}
// Generate and push changes. We abort here if a repo fails because it should be safe
// to re-run changesets, which force push changes to a PR branch.
for (const change of options.changes) {
const repository = `${change.owner}/${change.repo}`
console.log(`${repository}: Preparing change for on '${change.base}' to '${change.head}'`)
await createBranchWithChanges(octokit, { ...change, dryRun: options.dryRun })
}
// Publish changes as pull requests only if all changes are successfully created. We
// continue on error for errors when publishing.
const results: CreatedChangeset[] = []
let publishChangesFailed = false
for (const change of options.changes) {
const repository = `${change.owner}/${change.repo}`
console.log(`${repository}: Preparing pull request for change from '${change.base}' to '${change.head}':
Title: ${change.title}
Body: ${change.body || 'none'}`)
let pullRequest: { url: string; number: number } = { url: '', number: -1 }
try {
if (!options.dryRun) {
pullRequest = await createPR(octokit, change)
}
results.push({
repository,
branch: change.base,
pullRequestURL: pullRequest.url,
pullRequestNumber: pullRequest.number,
})
} catch (error) {
publishChangesFailed = true
console.error(error)
console.error(`Failed to create pull request for change in ${repository}`, { change })
}
}
// Log results
for (const result of results) {
console.log(`${result.repository} (${result.branch}): created pull request ${result.pullRequestURL}`)
}
if (publishChangesFailed) {
throw new Error('Error occured applying some changes - please check log output')
}
return results
}
async function cloneRepo(
octokit: Octokit,
owner: string,
repo: string,
checkout: {
revision: string
revisionMustExist?: boolean
}
): Promise<{
workdir: string
}> {
const tmpdir = await mkdtemp(path.join(os.tmpdir(), `sg-release-${owner}-${repo}-`))
console.log(`Created temp directory ${tmpdir}`)
const fetchFlags = '--depth 10'
// Determine whether or not to create the base branch, or use the existing one
let revisionExists = true
if (!checkout.revisionMustExist) {
try {
await octokit.repos.getBranch({ branch: checkout.revision, owner, repo })
} catch (error) {
if (error.status === 404) {
console.log(`Target revision ${checkout.revision} does not exist, this branch will be created`)
revisionExists = false
} else {
throw error
}
}
}
const checkoutCommand =
revisionExists === true
? // for an existing branch - fetch fails if we are already checked out, so ignore errors optimistically
`git fetch ${fetchFlags} origin ${checkout.revision}:${checkout.revision} || true ; git checkout ${checkout.revision}`
: // create from HEAD and publish base branch if it does not yet exist
`git checkout -b ${checkout.revision} ; git push origin ${checkout.revision}:${checkout.revision}`
// Set up repository
const setupScript = `set -ex
git clone ${fetchFlags} git@github.com:${owner}/${repo} || git clone ${fetchFlags} https://github.com/${owner}/${repo};
cd ${repo};
${checkoutCommand};`
await execa('bash', ['-c', setupScript], { stdio: 'inherit', cwd: tmpdir })
return {
workdir: path.join(tmpdir, repo),
}
}
async function createBranchWithChanges(
octokit: Octokit,
{ owner, repo, base: baseRevision, head: headBranch, commitMessage, edits, dryRun }: CreateBranchWithChangesOptions
): Promise<void> {
// Set up repository
const { workdir } = await cloneRepo(octokit, owner, repo, { revision: baseRevision })
// Apply edits
for (const edit of edits) {
switch (typeof edit) {
case 'function':
edit(workdir)
break
case 'string': {
const editScript = `set -ex
${edit};`
await execa('bash', ['-c', editScript], { stdio: 'inherit', cwd: workdir })
}
}
}
if (dryRun) {
console.warn('Dry run enabled - printing diff instead of publishing')
const showChangesScript = `set -ex
git --no-pager diff;`
await execa('bash', ['-c', showChangesScript], { stdio: 'inherit', cwd: workdir })
} else {
// Publish changes. We force push to ensure that the generated changes are applied.
const publishScript = `set -ex
git add :/;
git commit -a -m ${JSON.stringify(commitMessage)};
git push --force origin HEAD:${headBranch};`
await execa('bash', ['-c', publishScript], { stdio: 'inherit', cwd: workdir })
}
}
async function createPR(
octokit: Octokit,
options: {
owner: string
repo: string
head: string
base: string
title: string
body?: string
}
): Promise<{ url: string; number: number }> {
const response = await octokit.pulls.create(options)
return {
url: response.data.html_url,
number: response.data.number,
}
}
export interface TagOptions {
owner: string
repo: string
branch: string
tag: string
}
/**
* Creates a tag on a remote branch for the given repository.
*
* The target branch must exist on the remote.
*/
export async function createTag(
octokit: Octokit,
{ owner, repo, branch: rawBranch, tag: rawTag }: TagOptions,
dryRun: boolean
): Promise<void> {
const { workdir } = await cloneRepo(octokit, owner, repo, { revision: rawBranch, revisionMustExist: true })
const branch = JSON.stringify(rawBranch)
const tag = JSON.stringify(rawTag)
const finalizeTag = dryRun ? `git --no-pager show ${tag} --no-patch` : `git push origin ${tag}`
console.log(
dryRun
? `Dry-run enabled - creating and printing tag ${tag} on ${owner}/${repo}@${branch}`
: `Creating and pushing tag ${tag} on ${owner}/${repo}@${branch}`
)
await execa('bash', ['-c', `git tag -a ${tag} -m ${tag} && ${finalizeTag}`], { stdio: 'inherit', cwd: workdir })
}
function dateMarkdown(date: Date, name: string): string {
return `[${formatDate(date)}](${timezoneLink(date, name)})`
} | the_stack |
// based on v12.69.43.15
// see https://openfin.co/support/technical-faq/#what-do-the-numbers-in-the-runtime-version-mean
/**
* JavaScript API
* The JavaScript API allows you to create an HTML/JavaScript application that has access to the native windowing environment,
* can communicate with other applications and has access to sandboxed system-level features.
*
* API Ready
* When using the OpenFin API, it is important to ensure that it has been fully loaded before making any API calls. To verify
* that the API is in fact ready, be sure to make any API calls either from within the fin.desktop.main() method or explicitly
* after it has returned. This avoids the situation of trying to access methods that are not yet fully injected.
*
* Overview
* When running within the OpenFin Runtime your web applications have access to the "fin" namespace and all the modules within the API
* without the need to include additional source files. You can treat the "fin" namespace as you would the "window", "navigator" or "document" objects.
*/
declare namespace fin {
var Application: import('./_v2/api/application/application').default;
var Clipboard: import('./_v2/api/clipboard/clipboard').default;
var ExternalApplication: import('./_v2/api/external-application/external-application').default
var ExternalWindow: import('./_v2/api/external-window/external-window').default;
var Frame: import('./_v2/api/frame/frame').default;
var GlobalHotkey: import('./_v2/api/global-hotkey/index').default;
var InterApplicationBus: import('./_v2/api/interappbus/interappbus').default;
var Notification: import('./_v2/api/notification/notification').default;
var System: import('./_v2/api/system/system').default;
var Window: import('./_v2/api/window/window').default;
// v2 shapes
type applicationLogInfo = import('./_v2/api/application/application').LogInfo;
type ApplicationOption = import('./_v2/api/application/applicationOption').ApplicationOption;
type ApplicationInfo = import('./_v2/api/system/application').ApplicationInfo;
type AppAssetInfo = import('./_v2/api/system/download-asset').AppAssetInfo;
type AppAssetRequest = import('./_v2/api/system/download-asset').AppAssetRequest;
type AnchorType = import('./_v2/shapes').AnchorType
type Bounds = import('./_v2/shapes').Bounds;
type ClearCacheOption = import('./_v2/api/system/clearCacheOption').ClearCacheOption;
type CookieInfo = import('./_v2/api/system/cookie').CookieInfo;
type CookieOption = import('./_v2/api/system/cookie').CookieOption;
type CrashReporterOption = import('./_v2/api/system/crashReporterOption').CrashReporterOption;
type ContextMenuSettings = import('./_v2/shapes').ContextMenuSettings;
type DownloadPreloadInfo = import('./_v2/api/system/download-preload').DownloadPreloadInfo;
type DownloadPreloadOption = import('./_v2/api/system/download-preload').DownloadPreloadOption;
type EntityInfo = import('./_v2/api/system/entity').EntityInfo;
type ExternalApplicationInfo = import('./_v2/api/external-application/external-application').ExternalApplicationInfo;
type ExternalProcessRequestType = import('./_v2/api/system/external-process').ExternalProcessRequestType;
type ExternalProcessInfo = import('./_v2/api/system/external-process').ExternalProcessInfo;
type FrameInfo = import('./_v2/api/window/window').FrameInfo;
type HostSpecs = import('./_v2/api/system/host-specs').HostSpecs;
type Identity = import('./_v2/identity').Identity;
type LaunchInfo = import('./_v2/api/application/application').ApplicationInfo;
type LogInfo = import('./_v2/api/system/log').LogInfo;
type MonitorInfo = import('./_v2/api/system/monitor').MonitorInfo;
type Opacity = import('./_v2/shapes').Opacity;
type PointTopLeft = import('./_v2/api/system/point').PointTopLeft;
type Position = import('./_v2/shapes').Position;
type ProcessInfo = import('./_v2/api/system/process').ProcessInfo;
type ProxyInfo = import('./_v2/api/system/proxy').ProxyInfo;
type RegistryInfo = import('./_v2/api/system/registry-info').RegistryInfo;
type RuntimeInfo = import('./_v2/api/system/runtime-info').RuntimeInfo;
type RVMInfo = import('./_v2/api/system/rvm').RVMInfo;
type RGB = import('./_v2/shapes').RGB;
type RuntimeDownloadOptions = import('./_v2/api/system/download-asset').RuntimeDownloadOptions;
type RuntimeDownloadProgress = import('./_v2/api/system/download-asset').RuntimeDownloadProgress;
type ShortCutConfig = import('./_v2/api/application/application').ShortCutConfig;
type SystemWindowInfo = import('./_v2/api/system/window').WindowInfo;
type Size = import('./_v2/shapes').Size;
type TrayInfo = import('./_v2/api/application/application').TrayInfo;
type Transition = import('./_v2/shapes').Transition;
type TransitionOptions = import('./_v2/shapes').TransitionOptions;
type TransitionBase = import('./_v2/shapes').TransitionBase;
type WindowDetail = import('./_v2/api/system/window').WindowDetail;
type WindowOption = import('./_v2/api/window/windowOption').WindowOption;
type WindowInfo = import('./_v2/api/window/window').WindowInfo;
const desktop: OpenFinDesktop;
interface OpenFinDesktop {
main(f: () => any): void;
Application: OpenFinApplicationStatic;
ExternalApp: OpenFinExternalApplicationStatic;
GlobalHotkey: OpenFinGlobalHotkey;
InterApplicationBus: OpenFinInterApplicationBus;
Notification: OpenFinNotificationStatic;
System: OpenFinSystem;
Window: OpenFinWindowStatic;
ExternalWin: OpenFinExternalWindowStatic;
Frame: OpenFinFrameStatic;
}
interface OpenFinApplicationStatic {
/**
* Creates a new Application.
* An object representing an application. Allows the developer to create, execute, show/close an application as well as listen to application events.
*/
new (
options: ApplicationOption,
callback?: (successObj: { httpResponseCode: number }) => void,
errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinApplication;
/**
* Launches the given Application manifest.
*/
createFromManifest(manifestUrl: string, callback?: (app: OpenFinApplication) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Returns an Application object that represents an existing application.
*/
getCurrent(): OpenFinApplication;
/**
* Returns an Application object that represents an existing application.
*/
wrap(uuid: string): OpenFinApplication;
}
/**
* Application
* An object representing an application. Allows the developer to create, execute, show / close an application as well as listen to application events.
*/
interface OpenFinApplication {
/**
* Returns an instance of the main Window of the application
*/
getWindow(): OpenFinWindow;
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinApplicationEventType,
listener: (event: ApplicationBaseEvent
| TrayIconClickedEvent
| WindowEvent
| WindowAlertRequestedEvent
| WindowAuthRequested
| WindowNavigationRejectedEvent
| WindowEndLoadEvent) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Closes the application and any child windows created by the application.
*/
close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of wrapped fin.desktop.Windows for each of the application's child windows.
*/
getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of active window groups for all of the application's windows. Each group is represented as an array of wrapped fin.desktop.Windows.
*/
getGroups(callback?: (groups: OpenFinWindow[][]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves information about the application.
*/
getInfo(callback?: (info: LaunchInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the JSON manifest that was used to create the application. Invokes the error callback if the application was not created from a manifest.
*/
getManifest(callback?: (manifest: any) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves UUID of the application that launches this application. Invokes the error callback if the application was created from a manifest.
*/
getParentUuid(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves current configuration of application's shortcuts.
*/
getShortcuts(callback?: (config: ShortCutConfig) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves information about the system tray.
*/
getTrayIconInfo(callback?: (trayInfo: TrayInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns the current zoom level of the application.
*/
getZoomLevel(callback?: (level: number) => void, errorCallback?: (reason: string) => void): void;
/**
* Determines if the application is currently running.
*/
isRunning(callback?: (running: boolean) => void, errorCallback?: (reason: string) => void): void;
/**
* Registers a username and an app name for licensing purposes.
*/
registerUser(userName: string, appName: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinApplicationEventType,
previouslyRegisteredListener: (event: ApplicationBaseEvent
| TrayIconClickedEvent
| WindowEvent
| WindowAlertRequestedEvent
| WindowAuthRequested
| WindowNavigationRejectedEvent
| WindowEndLoadEvent) => any,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Removes the application's icon from the tray.
*/
removeTrayIcon(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Restarts the application.
*/
restart(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Runs the application. When the application is created, run must be called.
*/
run(callback?: (successObj: SuccessObj) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void;
/**
* Tells the rvm to relaunch the main application once upon a complete shutdown
*/
scheduleRestart(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sends a message to the RVM to upload the application's logs. On success, an object containing logId is returned.
*/
sendApplicationLog(callback?: (logInfo: applicationLogInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Sets an associated username with that app for Application Log Management use
*/
setAppLogUsername(username: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sets new shortcut configuration for current application.
* Application has to be launched with a manifest and has to have shortcut configuration (icon url, name, etc.) in its manifest to
* be able to change shortcut states.
*/
setShortcuts(config: ShortCutConfig, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Adds a customizable icon in the system tray and notifies the application when clicked.
*/
setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sets the zoom level of the application. The original size is 0 and each increment above or below represents zooming 20%
* larger or smaller to default limits of 300% and 50% of original size, respectively.
*/
setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Closes the application by terminating its process.
*/
terminate(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Waits for a hanging application. This method can be called in response to an application "not-responding" to allow the application
* to continue and to generate another "not-responding" message after a certain period of time.
*/
wait(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* The Application's uuid
*/
uuid: string;
}
interface SuccessObj {
httpResponseCode: number;
}
interface NetworkErrorInfo extends ErrorInfo {
networkErrorCode: number;
}
interface ErrorInfo {
stack: string;
message: string;
}
/**
* Clipboard
* Clipboard API allows reading and writting to the clipboard in multiple formats.
*/
interface OpenFinClipboard {
/**
* Reads available formats for the clipboard type
*/
availableFormats(type: string | null, callback?: (formats: string[]) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Reads available formats for the clipboard type
*/
readHtml(type: string | null, callback?: (html: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Read the content of the clipboard as Rtf
*/
readRtf(type: string | null, callback?: (rtf: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Read the content of the clipboard as plain text
*/
readText(type: string | null, callback?: (text: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard
*/
write(data: any, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as Html
*/
writeHtml(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as Rtf
*/
writeRtf(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as plain text
*/
writeText(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
}
interface OpenFinExternalApplicationStatic {
/**
* Returns an External Application object that represents an existing external application.
*/
wrap(uuid: string): OpenFinExternalApplication;
}
/**
* ExternalApplication
* An object representing an application. Allows the developer to create, execute, show and close an application, as well as listen to application events.
*/
interface OpenFinExternalApplication {
/**
* Retrieves information about the application.
*/
getInfo(callback?: (info: ExternalApplicationInfo) => void,
errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinExternalApplicationEventType,
listener: () => void,
callback?: () => void,
errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinExternalApplicationEventType,
listener: () => void,
callback?: () => void,
errorCallback?: (reason: string, error: ErrorInfo) => void): void;
}
/**
* GlobalHotkey
* The Global Hotkey allows the registration and unregistration of given hotkeys at the OS level, meaning a Window/Application will receive the events regardless of focused state.
*/
interface OpenFinGlobalHotkey {
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinGlobalHotkeyEventType,
listener: (event: GlobalHotkeyEvent) => void,
callback?: () => void,
errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Checks if a given hotkey has been registered
*/
isRegistered(hotkey: string, callback?: (registered: boolean) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Registers a global hotkey with the operating system.
*/
register(hotkey: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinGlobalHotkeyEventType,
listener: (event: GlobalHotkeyEvent) => void,
callback?: () => void,
errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Unregisters a global hotkey with the operating system.
*/
unregister(hotkey: string, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Unregisters all global hotkeys for the current application.
*/
unregisterAll(callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
}
/**
* InterApplicationBus
* A messaging bus that allows for pub/sub messaging between different applications.
*/
interface OpenFinInterApplicationBus {
/**
* Adds a listener that gets called when applications subscribe to the current application's messages.
*/
addSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Adds a listener that gets called when applications unsubscribe to the current application's messages.
*/
addUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Removes a previously registered subscribe listener.
*/
removeSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Removes a previously registered unsubscribe listener.
*/
removeUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Publishes a message to all applications running on OpenFin Runtime that are subscribed to the specified topic.
*/
publish(topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sends a message to a specific application on a specific topic.
*/
send(destinationUuid: string, name: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
send(destinationUuid: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Subscribes to messages from the specified application on the specified topic. If the subscription is for a uuid, [name],
* topic combination that has already been published to upon subscription you will receive the last 20 missed messages in the order they were published.
*/
subscribe(
senderUuid: string,
name: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
subscribe(
senderUuid: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Unsubscribes to messages from the specified application on the specified topic.
*/
unsubscribe(
senderUuid: string,
name: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
unsubscribe(
senderUuid: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
}
interface OpenFinNotificationStatic {
/**
* ctor
*/
new (options: NotificationOptions, callback?: () => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinNotification;
/**
* Gets an instance of the current notification. For use within a notification window to close the window or send a message back to its parent application.
*/
getCurrent(): OpenFinNotification;
}
/**
* Notification
* Notification represents a window on OpenFin Runtime which is shown briefly to the user on the bottom-right corner of the primary monitor.
* A notification is typically used to alert the user of some important event which requires their attention.
* Notifications are a child or your application that are controlled by the runtime.
*/
interface OpenFinNotification {
/**
* Closes the notification.
*/
close(callback?: () => void): void;
/**
* Sends a message to the notification.
*/
sendMessage(message: any, callback?: () => void): void;
/**
* Sends a message from the notification to the application that created the notification. The message is handled by the notification's onMessage callback.
*/
sendMessageToApplication(message: any, callback?: () => void): void;
}
interface NotificationOptions {
/**
* A boolean that will force dismissal even if the mouse is hovering over the notification
*/
ignoreMouseOver?: boolean;
/**
* A message of any primitive or composite-primitive type to be passed to the notification upon creation.
*/
message?: any;
/**
* The timeout for displaying a notification.Can be in milliseconds or "never".
*/
timeout?: number | "never";
/**
* The url of the notification
*/
url?: string;
/**
* A function that is called when a notification is clicked.
*/
onClick?(callback: () => void): void;
/**
* Invoked when the notification is closed via .close() method on the created notification instance
* or the by the notification itself via fin.desktop.Notification.getCurrent().close().
* NOTE: this is not invoked when the notification is dismissed via a swipe. For the swipe dismissal callback see onDismiss
*/
onClose?(callback: () => void): void;
/**
* Invoked when a the notification is dismissed by swiping it off the screen to the right. NOTE: this is no fired on a programmatic close.
*/
onDismiss?(callback: () => void): void;
/**
* A function that is called when an error occurs.The reason for the error is passed as an argument.
*/
onError?(errorCallback: (reason: string, errorObj: NetworkErrorInfo) => void): void;
/**
* The onMessage function will respond to messages sent from notification.sendMessageToApplication.
* The function is passed the message, which can be of any primitive or composite-primitive type.
*/
onMessage?(callback: (message: any) => void): void;
/**
* A function that is called when a notification is shown.
*/
onShow?(callback: (successObj: SuccessObj) => void): void;
}
/**
* System
* An object representing the core of OpenFin Runtime.
* Allows the developer to perform system-level actions, such as accessing logs, viewing processes, clearing the cache and exiting the runtime.
*/
interface OpenFinSystem {
Clipboard: OpenFinClipboard;
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinSystemEventType,
listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Clears cached data containing window state/positions,
* application resource files (images, HTML, JavaScript files), cookies, and items stored in the Local Storage.
*/
clearCache(options: ClearCacheOption, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Clears all cached data when OpenFin Runtime exits.
*/
deleteCacheOnExit(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Downloads the given application asset
*/
downloadAsset(
assetObj: AppAssetInfo,
progressListener?: (progress: { downloadedBytes: number, totalBytes: number }) => void,
callback?: (successObj: { path: string }) => void,
errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void;
/**
* Download preload scripts from given URLs
*/
downloadPreloadScripts(scripts: DownloadPreloadOption[], callback?: (downloadInfo: DownloadPreloadInfo[]) => void,
errorCallback?: (reason: string) => void): void;
/**
* Downloads the given OpenFin Runtime.
*/
downloadRuntime(options: RuntimeDownloadOptions, onProgress?: (progress: RuntimeDownloadProgress) => void, onComplete?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Exits the Runtime.
*/
exit(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Writes any unwritten cookies data to disk.
*/
flushCookieStore(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of data for all applications.
*/
getAllApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of data for all external applications.
*/
getAllExternalApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of data (name, ids, bounds) for all application windows.
*/
getAllWindows(callback?: (windowInfoList: SystemWindowInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns information about the app asset.
*/
getAppAssetInfo(options: AppAssetRequest, callback?: (appAssetInfo: AppAssetInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the command line argument string that started OpenFin Runtime.
*/
getCommandLineArguments(callback?: (args: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Get additional info of cookies.
*/
getCookies(option: CookieOption, callback?: (info: CookieInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Get the current state of the crash reporter.
*/
getCrashReporterState(callback?: (state: CrashReporterOption) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the configuration object that started the OpenFin Runtime.
*/
getDeviceId(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns a hex encoded hash of the mac address and the currently logged in user name
*/
getDeviceUserId(callback?: (id: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns an Entity info object relating to the entity specified by the uuid and name passed in. The possible types are 'window', 'iframe', 'external connection' or 'unknown'.
*/
getEntityInfo(uuid: string, name: string, callback?: (info: EntityInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the value of a given environment variable on the computer on which the runtime is installed.
*/
getEnvironmentVariable(envVar: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves currently focused window identity.
*/
getFocusedWindow(callback?: (focusedWindowIdentity: Identity) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves system information.
*/
getHostSpecs(callback?: (info: HostSpecs) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the contents of the log with the specified filename.
*/
getLog(logFileName: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array containing information for each log file.
*/
getLogList(callback?: (logInfoList: LogInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns a unique identifier (UUID) provided by the machine.
*/
getMachineId(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the minimum (inclusive) logging level that is currently being written to the logs.
*/
getMinLogLevel(callback?: (logLevel: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an object that contains data about the about the monitor setup of the computer that the runtime is running on.
*/
getMonitorInfo(callback?: (monitorInfo: MonitorInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns the mouse in virtual screen coordinates (left, top).
*/
getMousePosition(callback?: (mousePosition: PointTopLeft) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of all of the runtime processes that are currently running.
* Each element in the array is an object containing the uuid and the name of the application to which the process belongs.
*/
getProcessList(callback?: (processInfoList: ProcessInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the Proxy settings.
*/
getProxySettings(callback?: (proxy: ProxyInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns information about the running Runtime in an object.
*/
getRuntimeInfo(callback?: (rvmInfo: RuntimeInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns information about the running RVM in an object.
*/
getRvmInfo(callback?: (rvmInfo: RVMInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns the version of the runtime. The version contains the major, minor, build and revision numbers.
*/
getVersion(callback?: (version: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Runs an executable or batch file.
*/
launchExternalProcess(options: ExternalProcessRequestType, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void;
/**
* Writes the passed message into both the log file and the console.
*/
log(level: "debug" | "info" | "warn" | "error", message: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Monitors a running process.
*/
monitorExternalProcess(options: ExternalProcessInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void;
/**
* Opens the passed URL in the default web browser.
*/
openUrlWithBrowser(url: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Opens the passed URL in the default web browser.
*/
readRegistryValue(rootKey: string, subkey: string, value: string, callback?: (info: RegistryInfo) => void,
errorCallback?: (reason: string) => void): void;
/**
* This function call will register a unique id and produce a token. The token can be used to broker an external connection.
*/
registerExternalConnection(
uuid: string,
callback?: (detail: {
/**
* this will be unique each time
*/
token: string;
/**
* "remote-connection-uuid"
*/
uuid: string;
}) => void,
errorCallback?: (reason: string) => void): void;
/**
* Removes the process entry for the passed UUID obtained from a prior call of fin.desktop.System.launchExternalProcess().
*/
releaseExternalProcess(processUuid: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinSystemEventType,
listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void,
callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Set the minimum log level above which logs will be written to the OpenFin log
*/
setMinLogLevel(logLevel: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Shows the Chrome Developer Tools for the specified window.
*/
showDeveloperTools(uuid: string, name: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Start the crash reporter for the browser process if not already running.
* You can optionally specify `diagnosticMode` to have the logs sent to
* OpenFin on runtime close
*/
startCrashReporter(options: CrashReporterOption, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Attempt to close an external process. The process will be terminated if it has not closed after the elapsed timeout in milliseconds.
*/
terminateExternalProcess(
processUuid: string,
timeout: number,
killTree: boolean,
callback?: (info: { result: "clean" | "terminated" | "failed" }) => void,
errorCallback?: (reason: string) => void): void;
/**
* Update the OpenFin Runtime Proxy settings.
*/
updateProxySettings(type: string, address: string, port: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
}
interface OpenFinWindowStatic {
/**
* Class: Window
*
* new Window(options, callbackopt, errorCallbackopt)
*
* Creates a new OpenFin Window
*
* A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize,
* maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually.
* The new window appears in the same process as the parent window.
* @param options - The options of the window
* @param [callback] - Called if the window creation was successful
* @param [callback.successObj] - httpResponseCode
*/
new (
options: WindowOption,
callback?: (successObj: { httpResponseCode: number }) => void,
errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinWindow;
/**
* Returns an instance of the current window.
* @returns Current window
*/
getCurrent(): OpenFinWindow;
/**
* Returns a Window object that wraps an existing window.
*/
wrap(appUuid: string, windowName: string): OpenFinWindow;
}
/**
* Window
* A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize,
* maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually.
* The new window appears in the same process as the parent window.
*/
interface OpenFinWindow {
/**
* uuid of the application that the window belongs to.
*/
uuid: string;
/**
* Name of window
*/
name: string;
/**
* Returns the native JavaScript "window" object for the window. This method can only be used by the parent application or the window itself,
* otherwise it will return undefined. The same Single-Origin-Policy (SOP) rules apply for child windows created by window.open(url) in that the
* contents of the window object are only accessible if the URL has the same origin as the invoking window. See example below.
* Also, will not work with fin.desktop.Window objects created with fin.desktop.Window.wrap().
* @returns Native window
*/
getNativeWindow(): Window;
/**
* Gets the parent application.
* @returns Parent application
*/
getParentApplication(): OpenFinApplication;
/**
* Gets the parent window.
*/
getParentWindow(): OpenFinWindow;
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinWindowEventType,
listener: (event: WindowBaseEvent
| WindowAuthRequestedEvent
| WindowBoundsEvent
| WindowExternalProcessStartedEvent
| WindowExternalProcessExited
| WindowGroupChangedEvent
| WindowHiddenEvent
| Window_NavigationRejectedEvent) => void,
callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Performs the specified window transitions
*/
animate(transitions: Transition, options: TransitionOptions, callback?: (event: any) => void, errorCallback?: (reason: string) => void): void;
/**
* Provides credentials to authentication requests
*/
authenticate(userName: string, password: string, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Removes focus from the window.
*/
blur(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Brings the window to the front of the OpenFin window stack.
*/
bringToFront(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Closes the window.
* @param Close will be prevented from closing when force is false and 'close-requested' has been subscribed to for application's main window.
*/
close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Executes Javascript on the window, restricted to windows you own or windows owned by applications you have created.
* @param code JavaScript code to be executed on the window.
*/
executeJavaScript(code: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Prevents a user from changing a window's size/position when using the window's frame.
* 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation.
* 'disabled-frame-bounds-changed' is generated after a user move/size operation.
* The events provide the bounds that would have been applied if the frame was enabled.
* 'frame-disabled' is generated when an enabled frame becomes disabled.
*/
disableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Re-enables user changes to a window's size/position when using the window's frame.
* 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation.
* 'disabled-frame-bounds-changed' is generated after a user move/size operation.
* The events provide the bounds that would have been applied if the frame was enabled.
* 'frame-enabled' is generated when a disabled frame has becomes enabled.
*/
enableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Flashes the window's frame and taskbar icon until the window is activated.
*/
flash(options?: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Gives focus to the window.
*/
focus(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of frame info objects representing the main frame and any
* iframes that are currently on the page.
*/
getAllFrames(callback?: (frames: FrameInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the current bounds (top, left, width, height) of the window.
*/
getBounds(callback?: (bounds: Bounds) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this window. If a window is not in a group an empty array is returned.
* Please note that calling window is included in the result array.
*/
getGroup(callback?: (group: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets an information object for the window.
*/
getInfo(callback?: (info: WindowInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the current settings of the window.
*/
getOptions(callback?: (options: WindowOption) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets a base64 encoded PNG snapshot of the window.
*/
getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the current state ("minimized", "maximized", or "normal") of the window.
*/
getState(callback?: (state: "minimized" | "maximized" | "normal") => void, errorCallback?: (reason: string) => void): void;
/**
* Returns the zoom level of the window.
*/
getZoomLevel(callback?: (level: number) => void, errorCallback?: (reason: string) => void): void;
/**
* Hides the window.
*/
hide(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Determines if the window is currently showing.
*/
isShowing(callback?: (showing: boolean) => void, errorCallback?: (reason: string) => void): void;
/**
* Joins the same window group as the specified window.
*/
joinGroup(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Leaves the current window group so that the window can be move independently of those in the group.
*/
leaveGroup(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Maximizes the window.
*/
maximize(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Merges the instance's window group with the same window group as the specified window
*/
mergeGroups(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Minimizes the window.
*/
minimize(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Moves the window by a specified amount.
*/
moveBy(deltaLeft: number, deltaTop: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Moves the window to a specified location.
*/
moveTo(left: number, top: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Navigates the window to a specified URL.
*/
navigate(url: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Navigates the window back one page.
*/
navigateBack(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Navigates the window forward one page.
*/
navigateForward(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Reloads the window current page.
*/
reload(ignoreCacheopt?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinWindowEventType,
listener: (event: WindowBaseEvent
| WindowAuthRequestedEvent
| WindowBoundsEvent
| WindowExternalProcessStartedEvent
| WindowExternalProcessExited
| WindowGroupChangedEvent
| WindowHiddenEvent
| Window_NavigationRejectedEvent) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Resizes the window by a specified amount.
*/
resizeBy(deltaWidth: number, deltaHeight: number, anchor: AnchorType, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Resizes the window by a specified amount.
*/
resizeTo(width: number, height: number, anchor: AnchorType, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Restores the window to its normal state (i.e., unminimized, unmaximized).
*/
restore(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Will bring the window to the front of the entire stack and give it focus.
*/
setAsForeground(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sets the window's size and position
*/
setBounds(left: number, top: number, width: number, height: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sets the zoom level of the window.
*/
setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Shows the window if it is hidden.
* @param Show will be prevented from closing when force is false and 'show-requested' has been subscribed to for application's main window.
*/
show(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Shows the window if it is hidden at the specified location. If the toggle parameter is set to true, the window will alternate between showing and hiding.
*/
showAt(left: number, top: number, force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Stops the taskbar icon from flashing.
*/
stopFlashing(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Stops any current navigation the window is performing.
*/
stopNavigation(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Updates the window using the passed options
*/
updateOptions(options: WindowOption, callback?: () => void, errorCallback?: (reason: string) => void): void;
}
interface OpenFinExternalWindowStatic {
/**
* Returns an External Window object that wraps an existing window.
*/
wrap(appUuid: string, windowName: string): Promise<OpenFinExternalWindow>;
/**
* Synchronously returns an External Window object that wraps an existing window.
*/
wrapSync(appUuid: string, windowName: string): OpenFinExternalWindow;
}
/**
* Class: ExternalWindow
* An ExternalWindow is an OpenFin object representing a window that belongs to a non-openfin application.<br>
* While External Windows don't have the complete functionality of an OpenFin Window object,
* they can be used to tap into any application that is currently running in the OS.<br>
* External Windows are useful for grouping, moving and resizing non-openfin applications
* as well as listening to events that are dispatched by these applications.<br>
* They are also compatible with OpenFin's Layouts service to facilitate
* a complete positional control over all running applications.<br>
*/
interface OpenFinExternalWindow {
/**
* The external window's id
*/
uuid: string;
/**
* The external window's name
*/
name: string;
/**
* Brings the external window to the front of the window stack.
* @return {Promise.<void>}
* @experimental
*/
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinExternalWindowEventType,
listener: (event: ExternalWindowBaseEvent) => void,
callback?: () => void, errorCallback?: (reason: string) => void): void;
bringToFront(): Promise<void>;
/**
* Closes the external window.
* @return {Promise.<void>}
* @experimental
*/
close(): Promise<void>;
/**
* Prevents a user from changing an external window's size/position
* when using the window's frame.
* @return {Promise.<void>}
* @experimental
*/
disableUserMovement(): Promise<void>;
/**
* Re-enables user changes to an external window's size/position
* when using the window's frame.
* @return {Promise.<void>}
* @experimental
*/
enableUserMovement(): Promise<void>;
/**
* Flashes the external window’s frame and taskbar icon until stopFlashing is called.
* @return {Promise.<void>}
* @experimental
*/
flash(): Promise<void>;
/**
* Gives focus to the external window.
* @return {Promise.<void>}
* @emits ExternalWindow#focused
* @experimental
*/
focus(): Promise<void>;
/**
* Gets the current bounds (top, left, etc.) of the external window.
* @return {Promise.<Bounds>}
* @experimental
*/
getBounds(): Promise<Bounds>;
/**
* Retrieves an array containing wrapped external windows that are grouped
* with this external window. If a window is not in a group an empty array
* is returned.
* @return {Promise.<Array<ExternalWindow|_Window>>}
* @experimental
*/
getGroup(): Promise<Array<OpenFinExternalWindow | OpenFinWindow>>;
/**
* Gets an information object for the window.
* @return {Promise.<any>}
* @experimental
*/
getInfo(): Promise<any>;
/**
* Gets an external window's options.
* @return {Promise.<any>}
* @experimental
*/
getOptions(): Promise<any>;
/**
* Gets the current state ("minimized", "maximized", or "restored") of
* the external window.
* @return {Promise.<string>}
* @experimental
*/
getState(): Promise<string>;
/**
* Hides the external window.
* @return {Promise.<void>}
* @experimental
*/
hide(): Promise<void>;
/**
* Determines if the external window is currently showing.
* @return {Promise.<boolean>}
* @experimental
*/
isShowing(): Promise<boolean>;
/**
* Joins the same window group as the specified window.
* @param { _Window | ExternalWindow } target The window whose group is to be joined
* @return {Promise.<void>}
* @experimental
*/
joinGroup(target: OpenFinExternalWindow | OpenFinWindow): Promise<void>;
/**
* Leaves the current window group so that the window can be moved
* independently of those in the group.
* @return {Promise.<void>}
* @experimental
*/
leaveGroup(): Promise<void>;
/**
* Maximizes the external window.
* @return {Promise.<void>}
* @experimental
*/
maximize(): Promise<void>;
/**
* Merges the instance's window group with the same window group as the specified window
* @param { _Window | ExternalWindow } target The window whose group is to be merged with
* @return {Promise.<void>}
* @experimental
*/
mergeGroups(target: OpenFinExternalWindow | OpenFinWindow): Promise<void>;
/**
* Minimizes the external window.
* @return {Promise.<void>}
* @experimental
*/
minimize(): Promise<void>;
/**
* Moves the external window by a specified amount.
* @param { number } deltaLeft The change in the left position of the window
* @param { number } deltaTop The change in the top position of the window
* @return {Promise.<void>}
* @experimental
*/
moveBy(deltaLeft: number, deltaTop: number): Promise<void>;
/**
* Moves the external window to a specified location.
* @param { number } left The left position of the window
* @param { number } top The top position of the window
* @return {Promise.<void>}
* @experimental
*/
moveTo(left: number, top: number): Promise<void>;
/**
* Resizes the external window by a specified amount.
* @param { number } deltaWidth The change in the width of the window
* @param { number } deltaHeight The change in the height of the window
* @param { AnchorType } anchor Specifies a corner to remain fixed during the resize.
* Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right".
* If undefined, the default is "top-left".
* @return {Promise.<void>}
* @experimental
*/
resizeBy(deltaWidth: number, deltaHeight: number, anchor: AnchorType): Promise<void>;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinExternalWindowEventType,
listener: (event: ExternalWindowBaseEvent) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Resizes the external window to the specified dimensions.
* @param { number } width The change in the width of the window
* @param { number } height The change in the height of the window
* @param { AnchorType } anchor Specifies a corner to remain fixed during the resize.
* Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right".
* If undefined, the default is "top-left".
* @return {Promise.<void>}
* @experimental
*/
resizeTo(width: number, height: number, anchor: AnchorType): Promise<void>;
/**
* Restores the external window to its normal state (i.e. unminimized, unmaximized).
* @return {Promise.<void>}
* @experimental
*/
restore(): Promise<void>;
/**
* Will bring the external window to the front of the entire stack and
* give it focus.
* @return {Promise.<void>}
* @experimental
*/
setAsForeground(): Promise<void>;
/**
* Sets the external window's size and position.
* @property { Bounds } bounds
* @return {Promise.<void>}
* @experimental
*/
setBounds(bounds: Bounds): Promise<void>;
/**
* Shows the external window if it is hidden.
* @return {Promise.<void>}
* @experimental
*/
show(): Promise<void>;
/**
* Shows the external window, if it is hidden, at the specified location.
* If the toggle parameter is set to true, the external window will
* alternate between showing and hiding.
* @param { number } left The left position of the window
* @param { number } top The top position of the window
* @return {Promise.<void>}
* @experimental
*/
showAt(left: number, top: number): Promise<void>;
/**
* Stops the taskbar icon from flashing.
* @return {Promise.<void>}
* @experimental
*/
stopFlashing(): Promise<void>;
/**
* Updates the external window using the passed options
* @param {*} options Changes an external window's options
* @return {Promise.<void>}
* @experimental
*/
updateOptions(options: any): Promise<void>;
}
interface OpenFinFrameStatic {
wrap(uuid: string, name: string): OpenFinFrame;
getCurrent(): OpenFinFrame;
}
interface OpenFinFrame {
name: string;
uuid: string;
addEventListener(type: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string) => void): void;
getParentWindow(callback?: (entityInfo: EntityInfo) => void, errorCallback?: (reason: string) => void): void;
getInfo(callback?: (entityInfo: EntityInfo) => void, errorCallback?: (reason: string) => void): void;
removeEventListener(type: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string) => void): void;
}
interface ApplicationBaseEvent {
topic: string;
type: OpenFinApplicationEventType;
uuid: string;
}
interface TrayIconClickedEvent extends ApplicationBaseEvent {
button: number; // 0 for left, 1 for middle, 2 for right
monitorInfo: MonitorInfo;
x: number; // the cursor x coordinate
y: number; // the cursor y coordinate
}
interface WindowEvent extends ApplicationBaseEvent {
name: string;
}
interface WindowAlertRequestedEvent extends WindowEvent {
message: string;
url: string;
}
interface WindowAuthRequested extends WindowEvent {
authInfo: {
host: string;
isProxy: boolean;
port: number;
realm: string;
scheme: string;
};
}
interface WindowNavigationRejectedEvent extends WindowEvent {
sourceName: string;
url: string;
}
interface WindowEndLoadEvent extends WindowEvent {
documentName: string;
isMain: boolean;
}
interface MonitorInfoChangedEvent extends MonitorInfo {
topic: "system";
type: "monitor-info-changed";
}
interface SystemBaseEvent {
topic: string;
type: OpenFinSystemEventType;
uuid: string;
}
interface GlobalHotkeyEvent {
topic: string;
type: OpenFinGlobalHotkeyEventType;
/**
* The Identity that has just registered the hotkey
*/
identity: {
name: string;
uuid: string;
parentFrame: string;
entityType: string;
},
hotkey: string;
}
interface DesktopIconClickedEvent {
mouse: {
/**
* the left virtual screen coordinate of the mouse
*/
left: number,
/**
* the top virtual screen coordinate of the mouse
*/
top: number
};
/**
* the number of milliseconds that have elapsed since the system was started,
*/
tickCount: number;
topic: "system";
type: "desktop-icon-clicked";
}
interface IdleStateChangedEvent {
/**
* How long in milliseconds since the user has been idle.
*/
elapsedTime: number;
/**
* true when the user is idle,false when the user has returned;
*/
isIdle: boolean;
topic: "system";
type: "idle-state-changed";
}
interface WindowBaseEvent {
/**
* the name of the window
*/
name: string;
/**
* always window
*/
topic: "window";
/**
* window event type
*/
type: OpenFinWindowEventType;
/**
* the UUID of the application the window belongs to
*/
uuid: string;
}
interface ExternalWindowBaseEvent {
/**
* the name of the window
*/
name: string;
/**
* always window
*/
topic: "external-window";
/**
* window event type
*/
type: OpenFinExternalWindowEventType;
/**
* the UUID of the application the window belongs to
*/
uuid: string;
}
interface WindowAuthRequestedEvent extends WindowBaseEvent {
authInfo: {
host: string;
isProxy: boolean;
port: number;
realm: string;
scheme: string;
};
}
interface WindowBoundsEvent extends WindowBaseEvent {
/**
* describes what kind of change occurred.
* 0 means a change in position.
* 1 means a change in size.
* 2 means a change in position and size.
*/
changeType: number;
/**
* true when pending changes have been applied to the window.
*/
deferred: boolean;
/**
* the new height of the window.
*/
height: number;
/**
* the left-most coordinate of the window.
*/
left: number;
/**
* the top-most coordinate of the window.
*/
top: number;
type: "bounds-changed" | "bounds-changing" | "disabled-frame-bounds-changed" | "disabled-frame-bounds-changing";
/**
* the new width of the window.
*/
width: number;
}
interface WindowExternalProcessStartedEvent extends WindowBaseEvent {
/**
* the process handle uuid
*/
processUuid: string;
type: "external-process-started";
}
interface WindowExternalProcessExited extends WindowBaseEvent {
/**
* the process exit code
*/
exitCode: number;
/**
* the process handle uuid
*/
processUuid: string;
type: "external-process-exited";
}
interface WindowGroupChangedEvent extends WindowBaseEvent {
/**
* Which group array the window that the event listener was registered on is included in:
* 'source' The window is included in sourceGroup.
* 'target' The window is included in targetGroup.
* 'nothing' The window is not included in sourceGroup nor targetGroup.
*/
memberOf: "source" | "target" | "nothing";
/**
* The reason this event was triggered.
* 'leave' A window has left the group due to a leave or merge with group.
* 'join' A window has joined the group.
* 'merge' Two groups have been merged together.
* 'disband' There are no other windows in the group.
*/
reason: "leave" | "join" | "merge" | "disband";
/**
* All the windows in the group the sourceWindow originated from.
*/
sourceGroup: WindowOfGroupInfo[];
/**
* The UUID of the application the sourceWindow belongs to The source window is the window in which (merge/join/leave)group(s) was called.
*/
sourceWindowAppUuid: string;
/**
* the name of the sourcewindow.The source window is the window in which(merge / join / leave) group(s) was called.
*/
sourceWindowName: string;
/**
* All the windows in the group the targetWindow orginated from
*/
targetGroup: WindowOfGroupInfo[];
/**
* The UUID of the application the targetWindow belongs to. The target window is the window that was passed into (merge/join) group(s).
*/
targetWindowAppUuid: string;
/**
* The name of the targetWindow. The target window is the window that was passed into (merge/join) group(s).
*/
targetWindowName: string;
type: "group-changed";
}
interface WindowOfGroupInfo {
/**
* The UUID of the application this window entry belongs to.
*/
appUuid: string;
/**
* The name of this window entry.
*/
windowName: string;
}
interface WindowHiddenEvent extends WindowBaseEvent {
/**
* What action prompted the close.
* The reasons are: "hide", "hide-on-close"
*/
reason: "hide" | "hide-on-close";
type: "hidden";
}
interface Window_NavigationRejectedEvent {
name: string;
/**
* source of navigation window name
*/
sourceName: string;
topic: "navigation-rejected";
/**
* Url that was not reached "http://blocked-content.url"
*/
url: string;
/**
* the UUID of the application the window belongs to.
*/
uuid: string;
}
interface SessionChangedEvent {
/**
* the action that triggered this event:
*/
reason: "lock"
| "unlock"
| "remote-connect"
| "remote-disconnect"
| "unknown";
topic: "system";
type: "session-changed";
}
type OpenFinApplicationEventType = "closed"
| "connected"
| "crashed"
| "initialized"
| "manifest-changed"
| "not-responding"
| "out-of-memory"
| "responding"
| "run-requested"
| "started"
| "tray-icon-clicked"
| "window-alert-requested"
| "window-auth-requested"
| "window-closed"
| "window-created"
| "window-end-load"
| "window-navigation-rejected"
| "window-show-requested"
| "window-start-load";
type OpenFinExternalApplicationEventType = "connected"
| "disconnected";
type OpenFinGlobalHotkeyEventType = "registered"
| "unregistered";
type OpenFinSystemEventType = "application-closed"
| "application-crashed"
| "application-created"
| "application-started"
| "desktop-icon-clicked"
| "idle-state-changed"
| "monitor-info-changed"
| "session-changed";
type OpenFinWindowEventType = "auth-requested"
| "blurred"
| "bounds-changed"
| "bounds-changing"
| "close-requested"
| "closed"
| "disabled-frame-bounds-changed"
| "disabled-frame-bounds-changing"
| "embedded"
| "external-process-exited"
| "external-process-started"
| "focused"
| "frame-disabled"
| "frame-enabled"
| "group-changed"
| "hidden"
| "initialized"
| "maximized"
| "minimized"
| "navigation-rejected"
| "restored"
| "show-requested"
| "shown";
type OpenFinExternalWindowEventType = 'begin-user-bounds-changing' |
'blurred' |
'bounds-changed' |
'bounds-changing' |
'closed' |
'closing' |
'disabled-movement-bounds-changed' |
'disabled-movement-bounds-changing' |
'end-user-bounds-changing' |
'focused' |
'group-changed' |
'hidden' |
'maximized' |
'minimized' |
'restored' |
'shown' |
'user-movement-disabled' |
'user-movement-enabled';
} | the_stack |
import DataLoader from "dataloader";
import { CmsStorageEntry, CmsModel } from "@webiny/api-headless-cms/types";
import WebinyError from "@webiny/error";
import { Entity } from "dynamodb-toolbox";
import { queryAll, QueryAllParams } from "@webiny/db-dynamodb/utils/query";
import {
createLatestSortKey,
createPartitionKey,
createPublishedSortKey,
createRevisionSortKey
} from "./keys";
import { cleanupItems } from "@webiny/db-dynamodb/utils/cleanup";
import { parseIdentifier } from "@webiny/utils";
import { batchReadAll } from "@webiny/db-dynamodb/utils/batchRead";
const getAllEntryRevisions = (params: LoaderParams) => {
const { entity, model } = params;
const { tenant, locale } = model;
return new DataLoader<string, CmsStorageEntry[]>(async (ids: readonly string[]) => {
const results: Record<string, CmsStorageEntry[]> = {};
for (const id of ids) {
const queryAllParams: QueryAllParams = {
entity,
partitionKey: createPartitionKey({
tenant,
locale,
id
}),
options: {
beginsWith: "REV#"
}
};
const items = await queryAll<CmsStorageEntry>(queryAllParams);
results[id] = cleanupItems(entity, items);
}
return ids.map(id => {
return results[id] || [];
});
});
};
const getRevisionById = (params: LoaderParams) => {
const { entity, model } = params;
const { locale, tenant } = model;
return new DataLoader<string, CmsStorageEntry[]>(async (ids: readonly string[]) => {
const queries = ids.reduce((collection, id) => {
const partitionKey = createPartitionKey({
tenant,
locale,
id
});
const { version } = parseIdentifier(id);
if (version === null) {
return collection;
}
const sortKey = createRevisionSortKey({
version
});
const keys = `${partitionKey}__${sortKey}`;
if (collection[keys]) {
return collection;
}
collection[keys] = entity.getBatch({
PK: partitionKey,
SK: sortKey
});
return collection;
/**
* We cast as any because there is no return type defined.
*/
}, {} as Record<string, any>);
const records = await batchReadAll<CmsStorageEntry>({
table: entity.table,
items: Object.values(queries)
});
const items = cleanupItems(entity, records);
return ids.map(id => {
return items.filter(item => {
return id === item.id;
});
});
});
};
const getPublishedRevisionByEntryId = (params: LoaderParams) => {
const { entity, model } = params;
const { locale, tenant } = model;
const publishedKey = createPublishedSortKey();
return new DataLoader<string, CmsStorageEntry[]>(async (ids: readonly string[]) => {
const queries = ids.reduce((collection, id) => {
const partitionKey = createPartitionKey({
tenant,
locale,
id
});
if (collection[partitionKey]) {
return collection;
}
collection[partitionKey] = entity.getBatch({
PK: partitionKey,
SK: publishedKey
});
return collection;
/**
* We cast as any because there is no return type defined.
*/
}, {} as Record<string, any>);
const records = await batchReadAll<CmsStorageEntry>({
table: entity.table,
items: Object.values(queries)
});
const items = cleanupItems(entity, records);
return ids.map(id => {
const { id: entryId } = parseIdentifier(id);
return items.filter(item => {
return entryId === item.entryId;
});
});
});
};
const getLatestRevisionByEntryId = (params: LoaderParams) => {
const { entity, model } = params;
const { locale, tenant } = model;
const latestKey = createLatestSortKey();
return new DataLoader<string, CmsStorageEntry[]>(async (ids: readonly string[]) => {
const queries = ids.reduce((collection, id) => {
const partitionKey = createPartitionKey({
tenant,
locale,
id
});
if (collection[partitionKey]) {
return collection;
}
collection[partitionKey] = entity.getBatch({
PK: partitionKey,
SK: latestKey
});
return collection;
/**
* We cast as any because there is no return type defined.
*/
}, {} as Record<string, any>);
const records = await batchReadAll<CmsStorageEntry>({
table: entity.table,
items: Object.values(queries)
});
const items = cleanupItems(entity, records);
return ids.map(id => {
const { id: entryId } = parseIdentifier(id);
return items.filter(item => {
return entryId === item.entryId;
});
});
});
};
const dataLoaders: Record<Loaders, any> = {
getAllEntryRevisions,
getRevisionById,
getPublishedRevisionByEntryId,
getLatestRevisionByEntryId
};
export interface GetAllEntryRevisionsParams {
ids: readonly string[];
model: CmsModel;
}
export interface GetRevisionByIdParams {
ids: readonly string[];
model: CmsModel;
}
export interface GetPublishedRevisionByEntryIdParams {
ids: readonly string[];
model: CmsModel;
}
export interface GetLatestRevisionByEntryIdParams {
ids: readonly string[];
model: CmsModel;
}
interface LoaderParams {
entity: Entity<any>;
model: CmsModel;
}
interface GetLoaderParams {
model: CmsModel;
}
interface ClearLoaderParams {
model: CmsModel;
entry?: CmsStorageEntry;
}
type Loaders =
| "getAllEntryRevisions"
| "getRevisionById"
| "getPublishedRevisionByEntryId"
| "getLatestRevisionByEntryId";
const loaderNames = Object.keys(dataLoaders) as Loaders[];
interface DataLoadersHandlerParams {
entity: Entity<any>;
}
export class DataLoadersHandler {
private readonly loaders: Map<string, DataLoader<any, any>> = new Map();
private readonly entity: Entity<any>;
public constructor(params: DataLoadersHandlerParams) {
this.entity = params.entity;
}
public async getAllEntryRevisions(
params: GetAllEntryRevisionsParams
): Promise<CmsStorageEntry[]> {
return await this.loadMany("getAllEntryRevisions", params, params.ids);
}
public async getRevisionById(params: GetRevisionByIdParams): Promise<CmsStorageEntry[]> {
return await this.loadMany("getRevisionById", params, params.ids);
}
public async getPublishedRevisionByEntryId(
params: GetPublishedRevisionByEntryIdParams
): Promise<CmsStorageEntry[]> {
return await this.loadMany("getPublishedRevisionByEntryId", params, params.ids);
}
public async getLatestRevisionByEntryId(
params: GetLatestRevisionByEntryIdParams
): Promise<CmsStorageEntry[]> {
return await this.loadMany("getLatestRevisionByEntryId", params, params.ids);
}
/**
* TODO @ts-refactor
* Maybe pass on the generics to DataLoader definition?
*/
private getLoader(name: Loaders, params: GetLoaderParams): DataLoader<any, any> {
if (!dataLoaders[name]) {
throw new WebinyError("Unknown data loader.", "UNKNOWN_DATA_LOADER", {
name
});
}
const { model } = params;
const { tenant, locale } = model;
const loaderKey = `${name}-${tenant}-${locale}-${model.modelId}`;
if (!this.loaders.has(loaderKey)) {
this.loaders.set(
loaderKey,
dataLoaders[name]({
...params,
entity: this.entity
})
);
}
return this.loaders.get(loaderKey) as DataLoader<any, any>;
}
private async loadMany(
loader: Loaders,
params: GetLoaderParams,
ids: readonly string[]
): Promise<CmsStorageEntry[]> {
let results;
try {
results = await this.getLoader(loader, params).loadMany(ids);
if (Array.isArray(results) === true) {
return results.reduce((acc, res) => {
if (Array.isArray(res) === false) {
if (res && res.message) {
throw new WebinyError(res.message, res.code, {
...res,
data: JSON.stringify(res.data || {})
});
}
throw new WebinyError(
"Result from the data loader must be an array of arrays which contain requested items.",
"DATA_LOADER_RESULTS_ERROR",
{
...params,
loader
}
);
}
acc.push(...res);
return acc;
}, []);
}
} catch (ex) {
throw new WebinyError(
ex.message || "Data loader error.",
ex.code || "DATA_LOADER_ERROR",
{
error: ex,
...params,
loader,
ids
}
);
}
throw new WebinyError(
`Data loader did not return array of items or empty array.`,
"INVALID_DATA_LOADER_RESULT",
{
loader,
ids,
results
}
);
}
public clearAll(params: Omit<ClearLoaderParams, "entry">): void {
for (const name of loaderNames) {
const loader = this.getLoader(name, params);
loader.clearAll();
}
}
} | the_stack |
import * as Containers from '@docker/sdk/containers.d'; // Imports from the containers.d.ts file to prevent a tsc error (workaround for https://github.com/docker/node-sdk/issues/71)
import * as Contexts from '@docker/sdk/contexts.d'; // Imports from the containers.d.ts file to prevent a tsc error (workaround for https://github.com/docker/node-sdk/issues/71)
import * as Volumes from '@docker/sdk/volumes.d'; // Imports from the volumes.d.ts file to prevent a tsc error (workaround for https://github.com/docker/node-sdk/issues/71)
import { Containers as ContainersClient, Contexts as ContextsClient, Volumes as VolumesClient } from '@docker/sdk';
import { Client as GrpcClient, Metadata } from '@grpc/grpc-js';
import { IActionContext, parseError } from '@microsoft/vscode-azext-utils';
import { CancellationToken } from 'vscode';
import { localize } from '../../localize';
import { DockerInfo, DockerOSType, PruneResult } from '../Common';
import { DockerContainer, DockerContainerInspection } from '../Containers';
import { ContextChangeCancelClient } from '../ContextChangeCancelClient';
import { ContextType, DockerContext } from '../Contexts';
import { DockerApiClient, DockerExecCommandProvider, DockerExecOptions } from '../DockerApiClient';
import { DockerImage, DockerImageInspection } from '../Images';
import { DockerNetwork, DockerNetworkInspection, DriverType } from '../Networks';
import { NotSupportedError } from '../NotSupportedError';
import { DockerVersion } from '../Version';
import { DockerVolume, DockerVolumeInspection } from '../Volumes';
import { containerPortsToInspectionPorts, containerToDockerContainer } from './DockerServeUtils';
// 20 s timeout for all calls (enough time for any call, but short enough to be UX-reasonable)
const dockerServeCallTimeout = 20 * 1000;
export class DockerServeClient extends ContextChangeCancelClient implements DockerApiClient {
private readonly containersClient: ContainersClient;
private readonly volumesClient: VolumesClient;
private readonly contextsClient: ContextsClient;
private readonly callMetadata: Metadata;
private readonly fixedContextName: string | undefined;
public constructor(currentContext?: DockerContext) {
super();
this.containersClient = new ContainersClient();
this.volumesClient = new VolumesClient();
this.contextsClient = new ContextsClient();
this.callMetadata = new Metadata();
if (currentContext?.Name) {
this.callMetadata.add('context_key', (this.fixedContextName = currentContext.Name)); // Assignment is intentional
}
}
public dispose(): void {
super.dispose();
void this.containersClient?.close();
}
public async info(context: IActionContext, token?: CancellationToken): Promise<DockerInfo> {
throw new NotSupportedError(context);
}
public async version(context: IActionContext, token?: CancellationToken): Promise<DockerVersion> {
throw new NotSupportedError(context);
}
public async getContainers(context: IActionContext, token?: CancellationToken): Promise<DockerContainer[]> {
const request = new Containers.ListRequest()
.setAll(true);
const response: Containers.ListResponse = await this.promisify(context, this.containersClient, this.containersClient.list, request, token);
const result = response.getContainersList();
return result.map(c => containerToDockerContainer(c.toObject()));
}
public async inspectContainer(context: IActionContext, ref: string, token?: CancellationToken): Promise<DockerContainerInspection> {
const request = new Containers.InspectRequest()
.setId(ref);
const response: Containers.InspectResponse = await this.promisify(context, this.containersClient, this.containersClient.inspect, request, token);
const responseContainer = response.toObject().container;
const container = containerToDockerContainer(responseContainer);
if (!container) {
throw new Error(localize('vscode-docker.dockerServeClient.noContainer', 'No container with name \'{0}\' was found.', ref));
}
return {
...container,
NetworkSettings: {
Ports: containerPortsToInspectionPorts(container),
},
// NOTE: ACI contexts return "Linux" whereas default contexts return "linux".
Platform: responseContainer.platform.toLowerCase() as DockerOSType,
};
}
// #region Not supported by the Docker SDK yet
public async execInContainer(context: IActionContext, ref: string, command: string[] | DockerExecCommandProvider, options?: DockerExecOptions, token?: CancellationToken): Promise<{ stdout: string, stderr: string }> {
// Supported by SDK, but ACI implementation does not support non-interactive nor commands with arguments.
// (This means no listing of container directories to show files.)
throw new NotSupportedError(context);
}
public async getContainerFile(context: IActionContext, ref: string, path: string, token?: CancellationToken): Promise<Buffer> {
throw new NotSupportedError(context);
}
public async putContainerFile(context: IActionContext, ref: string, path: string, content: Buffer, token?: CancellationToken): Promise<void> {
throw new NotSupportedError(context);
}
public async getContainerLogs(context: IActionContext, ref: string, token?: CancellationToken): Promise<NodeJS.ReadableStream> {
// Supported by SDK, but used only for debugging which will not work in ACI, and complicated to implement
throw new NotSupportedError(context);
}
public async pruneContainers(context: IActionContext, token?: CancellationToken): Promise<PruneResult> {
throw new NotSupportedError(context);
}
// #endregion Not supported by the Docker SDK yet
public async startContainer(context: IActionContext, ref: string, token?: CancellationToken): Promise<void> {
const request = new Containers.StartRequest()
.setId(ref);
await this.promisify(context, this.containersClient, this.containersClient.start, request, token);
}
public async restartContainer(context: IActionContext, ref: string, token?: CancellationToken): Promise<void> {
await this.stopContainer(context, ref, token);
await this.startContainer(context, ref, token);
}
public async stopContainer(context: IActionContext, ref: string, token?: CancellationToken): Promise<void> {
const request = new Containers.StopRequest()
.setId(ref);
await this.promisify(context, this.containersClient, this.containersClient.stop, request, token);
}
public async removeContainer(context: IActionContext, ref: string, token?: CancellationToken): Promise<void> {
const request = new Containers.DeleteRequest()
.setId(ref)
.setForce(true);
await this.promisify(context, this.containersClient, this.containersClient.delete, request, token);
}
// #region Not supported by the Docker SDK yet
public async getImages(context: IActionContext, includeDangling?: boolean, token?: CancellationToken): Promise<DockerImage[]> {
throw new NotSupportedError(context);
}
public async inspectImage(context: IActionContext, ref: string, token?: CancellationToken): Promise<DockerImageInspection> {
throw new NotSupportedError(context);
}
public async pruneImages(context: IActionContext, token?: CancellationToken): Promise<PruneResult> {
throw new NotSupportedError(context);
}
public async tagImage(context: IActionContext, ref: string, tag: string, token?: CancellationToken): Promise<void> {
throw new NotSupportedError(context);
}
public async removeImage(context: IActionContext, ref: string, token?: CancellationToken): Promise<void> {
throw new NotSupportedError(context);
}
public async getNetworks(context: IActionContext, token?: CancellationToken): Promise<DockerNetwork[]> {
throw new NotSupportedError(context);
}
public async inspectNetwork(context: IActionContext, ref: string, token?: CancellationToken): Promise<DockerNetworkInspection> {
throw new NotSupportedError(context);
}
public async pruneNetworks(context: IActionContext, token?: CancellationToken): Promise<PruneResult> {
throw new NotSupportedError(context);
}
public async createNetwork(context: IActionContext, options: { Name: string; Driver: DriverType; }, token?: CancellationToken): Promise<void> {
throw new NotSupportedError(context);
}
public async removeNetwork(context: IActionContext, ref: string, token?: CancellationToken): Promise<void> {
throw new NotSupportedError(context);
}
// #endregion Not supported by the Docker SDK yet
public async getVolumes(context: IActionContext, token?: CancellationToken): Promise<DockerVolume[]> {
const response: Volumes.VolumesListResponse = await this.promisify(context, this.volumesClient, this.volumesClient.volumesList, new Volumes.VolumesListRequest(), token);
const result = response.getVolumesList();
return result.map(v => v.toObject()).map(v => {
return {
Name: v.id,
Description: v.description,
Id: undefined,
CreatedTime: undefined,
};
});
}
// #region Not supported by the Docker SDK yet
public async inspectVolume(context: IActionContext, ref: string, token?: CancellationToken): Promise<DockerVolumeInspection> {
throw new NotSupportedError(context);
}
public async pruneVolumes(context: IActionContext, token?: CancellationToken): Promise<PruneResult> {
throw new NotSupportedError(context);
}
// #endregion Not supported by the Docker SDK yet
public async removeVolume(context: IActionContext, ref: string, token?: CancellationToken): Promise<void> {
const request = new Volumes.VolumesDeleteRequest()
.setId(ref);
await this.promisify(context, this.volumesClient, this.volumesClient.volumesDelete, request, token);
}
public async getContexts(context: IActionContext, token?: CancellationToken): Promise<DockerContext[]> {
const response: Contexts.ListResponse = await this.promisify(context, this.contextsClient, this.contextsClient.list, new Contexts.ListRequest(), token);
const contextsList = response.getContextsList().map(ctx => ctx.toObject()).map(ctx => {
return {
Id: ctx.name,
Name: ctx.name,
ContextType: ctx.contexttype as ContextType,
Current: ctx.current,
DockerEndpoint: ctx.dockerEndpoint?.host,
Description: ctx.description,
CreatedTime: undefined,
};
});
// Workaround for https://github.com/docker/compose-cli/issues/1960: if no context is marked as Current=true, that means the environment has a fixed context or otherwise the default context is selected, so overwrite that property
if (contextsList.every(ctx => !ctx.Current)) {
contextsList.find(ctx => ctx.Name === (this.fixedContextName || 'default')).Current = true;
}
return contextsList;
}
private async promisify<TRequest, TResponse>(
context: IActionContext,
client: GrpcClient,
clientCallback: (req: TRequest, md: Metadata, callback: (err: unknown, response: TResponse) => void) => unknown,
request: TRequest,
token?: CancellationToken): Promise<TResponse> {
const callPromise: Promise<TResponse> = new Promise((resolve, reject) => {
try {
clientCallback.call(client, request, this.callMetadata, (err, response) => {
if (err) {
const error = parseError(err);
if (error.errorType === '12') {
// Rewrap NotImplemented (12) as NotSupportedError
reject(new NotSupportedError(context));
} else {
reject(err);
}
}
resolve(response);
});
} catch (err) {
reject(err);
}
});
return this.withTimeoutAndCancellations(context, async () => callPromise, dockerServeCallTimeout, token);
}
} | the_stack |
import {promisifyAll} from '@google-cloud/promisify';
import arrify = require('arrify');
import {CallOptions} from 'google-gax';
import {google} from '../protos/protos';
import {Datastore, TransactionOptions} from '.';
import {entity, Entity, Entities} from './entity';
import {Query} from './query';
import {
CommitCallback,
CommitResponse,
DatastoreRequest,
RequestOptions,
PrepareEntityObjectResponse,
} from './request';
/**
* A transaction is a set of Datastore operations on one or more entities. Each
* transaction is guaranteed to be atomic, which means that transactions are
* never partially applied. Either all of the operations in the transaction are
* applied, or none of them are applied.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/transactions| Transactions Reference}
*
* @class
* @extends {Request}
* @param {Datastore} datastore A Datastore instance.
* @mixes module:datastore/request
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*/
class Transaction extends DatastoreRequest {
namespace?: string;
readOnly: boolean;
request: Function;
modifiedEntities_: ModifiedEntities;
skipCommit?: boolean;
constructor(datastore: Datastore, options?: TransactionOptions) {
super();
/**
* @name Transaction#datastore
* @type {Datastore}
*/
this.datastore = datastore;
/**
* @name Transaction#namespace
* @type {string}
*/
this.namespace = datastore.namespace;
options = options || {};
this.id = options.id;
this.readOnly = options.readOnly === true;
this.request = datastore.request_.bind(datastore);
// A queue for entity modifications made during the transaction.
this.modifiedEntities_ = [];
// Queue the callbacks that process the API responses.
this.requestCallbacks_ = [];
// Queue the requests to make when we send the transactional commit.
this.requests_ = [];
}
/*! Developer Documentation
*
* Below, we override two methods that we inherit from DatastoreRequest:
* `delete` and `save`. This is done because:
*
* A) the documentation needs to be different for a transactional save, and
* B) we build up a "modifiedEntities_" array on this object, used to build
* the final commit request with.
*/
commit(gaxOptions?: CallOptions): Promise<CommitResponse>;
commit(callback: CommitCallback): void;
commit(gaxOptions: CallOptions, callback: CommitCallback): void;
/**
* Commit the remote transaction and finalize the current transaction
* instance.
*
* If the commit request fails, we will automatically rollback the
* transaction.
*
* @param {object} [gaxOptions] Request configuration options, outlined here:
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request.
* If the commit fails, we automatically try to rollback the transaction
* (see {module:datastore/transaction#rollback}).
* @param {object} callback.apiResponse The full API response.
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*
* transaction.commit((err, apiResponse) => {
* if (err) {
* // Transaction could not be committed.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* transaction.commit().then((data) => {
* const apiResponse = data[0];
* });
*/
commit(
gaxOptionsOrCallback?: CallOptions | CommitCallback,
cb?: CommitCallback
): void | Promise<CommitResponse> {
const callback =
typeof gaxOptionsOrCallback === 'function'
? gaxOptionsOrCallback
: typeof cb === 'function'
? cb
: () => {};
const gaxOptions =
typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
if (this.skipCommit) {
setImmediate(callback);
return;
}
const keys: Entities = {};
this.modifiedEntities_
// Reverse the order of the queue to respect the "last queued request
// wins" behavior.
.reverse()
// Limit the operations we're going to send through to only the most
// recently queued operations. E.g., if a user tries to save with the
// same key they just asked to be deleted, the delete request will be
// ignored, giving preference to the save operation.
.filter((modifiedEntity: Entity) => {
const key = modifiedEntity.entity.key;
if (!entity.isKeyComplete(key)) return true;
const stringifiedKey = JSON.stringify(modifiedEntity.entity.key);
if (!keys[stringifiedKey]) {
keys[stringifiedKey] = true;
return true;
}
return false;
})
// Group entities together by method: `save` mutations, then `delete`.
// Note: `save` mutations being first is required to maintain order when
// assigning IDs to incomplete keys.
.sort((a, b) => {
return a.method < b.method ? 1 : a.method > b.method ? -1 : 0;
})
// Group arguments together so that we only make one call to each
// method. This is important for `DatastoreRequest.save`, especially, as
// that method handles assigning auto-generated IDs to the original keys
// passed in. When we eventually execute the `save` method's API
// callback, having all the keys together is necessary to maintain
// order.
.reduce((acc: Entities, entityObject: Entity) => {
const lastEntityObject = acc[acc.length - 1];
const sameMethod =
lastEntityObject && entityObject.method === lastEntityObject.method;
if (!lastEntityObject || !sameMethod) {
acc.push(entityObject);
} else {
lastEntityObject.args = lastEntityObject.args.concat(
entityObject.args
);
}
return acc;
}, [])
// Call each of the mutational methods (DatastoreRequest[save,delete])
// to build up a `req` array on this instance. This will also build up a
// `callbacks` array, that is the same callback that would run if we
// were using `save` and `delete` outside of a transaction, to process
// the response from the API.
.forEach(
(modifiedEntity: {method: string; args: {reverse: () => void}}) => {
const method = modifiedEntity.method;
const args = modifiedEntity.args.reverse();
Datastore.prototype[method].call(this, args, () => {});
}
);
// Take the `req` array built previously, and merge them into one request to
// send as the final transactional commit.
const reqOpts = {
mutations: this.requests_
.map((x: {mutations: google.datastore.v1.Mutation}) => x.mutations)
.reduce(
(a: {concat: (arg0: Entity) => void}, b: Entity) => a.concat(b),
[]
),
};
this.request_(
{
client: 'DatastoreClient',
method: 'commit',
reqOpts,
gaxOpts: gaxOptions || {},
},
(err, resp) => {
if (err) {
// Rollback automatically for the user.
this.rollback(() => {
// Provide the error & API response from the failed commit to the
// user. Even a failed rollback should be transparent. RE:
// https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1369#discussion_r66833976
callback(err, resp);
});
return;
}
// The `callbacks` array was built previously. These are the callbacks
// that handle the API response normally when using the
// DatastoreRequest.save and .delete methods.
this.requestCallbacks_.forEach(
(cb: (arg0: null, arg1: Entity) => void) => {
cb(null, resp);
}
);
callback(null, resp);
}
);
}
createQuery(kind?: string): Query;
createQuery(kind?: string[]): Query;
createQuery(namespace: string, kind: string): Query;
createQuery(namespace: string, kind: string[]): Query;
/**
* Create a query for the specified kind. See {module:datastore/query} for all
* of the available methods.
*
* @see {@link https://cloud.google.com/datastore/docs/concepts/queries| Datastore Queries}
*
* @see {@link Query}
*
* @param {string} [namespace] Namespace.
* @param {string} kind The kind to query.
* @returns {Query}
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*
* // Run the query inside the transaction.
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
* const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);
*
* const query = transaction.createQuery('Company')
* .hasAncestor(ancestorKey);
*
* query.run((err, entities) => {
* if (err) {
* // Error handling omitted.
* }
*
* transaction.commit((err) => {
* if (!err) {
* // Transaction committed successfully.
* }
* });
* });
* });
*
* // Run the query inside the transaction.with namespace
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
* const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);
*
* const query = transaction.createQuery('CompanyNamespace', 'Company')
* .hasAncestor(ancestorKey);
*
* query.run((err, entities) => {
* if (err) {
* // Error handling omitted.
* }
*
* transaction.commit((err) => {
* if (!err) {
* // Transaction committed successfully.
* }
* });
* });
* });
*/
createQuery(
namespaceOrKind?: string | string[],
kind?: string | string[]
): Query {
return this.datastore.createQuery.call(
this,
namespaceOrKind as string,
kind as string[]
);
}
/**
* Delete all entities identified with the specified key(s) in the current
* transaction.
*
* @param {Key|Key[]} key Datastore key object(s).
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
*
* // Delete a single entity.
* transaction.delete(datastore.key(['Company', 123]));
*
* // Delete multiple entities at once.
* transaction.delete([
* datastore.key(['Company', 123]),
* datastore.key(['Product', 'Computer'])
* ]);
*
* transaction.commit((err) => {
* if (!err) {
* // Transaction committed successfully.
* }
* });
* });
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete(entities?: Entities): any {
arrify(entities).forEach((ent: Entity) => {
this.modifiedEntities_.push({
entity: {
key: ent,
},
method: 'delete',
args: [ent],
});
});
}
/**
* Maps to {@link Datastore#save}, forcing the method to be `insert`.
*
* @param {object|object[]} entities Datastore key object(s).
* @param {Key} entities.key Datastore key object.
* @param {string[]} [entities.excludeFromIndexes] Exclude properties from
* indexing using a simple JSON path notation. See the examples in
* {@link Datastore#save} to see how to target properties at different
* levels of nesting within your entity.
* @param {object} entities.data Data to save with the provided key.
*/
insert(entities: Entities): void {
entities = arrify(entities)
.map(DatastoreRequest.prepareEntityObject_)
.map((x: PrepareEntityObjectResponse) => {
x.method = 'insert';
return x;
});
this.save(entities);
}
rollback(callback: RollbackCallback): void;
rollback(gaxOptions?: CallOptions): Promise<RollbackResponse>;
rollback(gaxOptions: CallOptions, callback: RollbackCallback): void;
/**
* Reverse a transaction remotely and finalize the current transaction
* instance.
*
* @param {object} [gaxOptions] Request configuration options, outlined here:
* https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {function} callback The callback function.
* @param {?error} callback.err An error returned while making this request.
* @param {object} callback.apiResponse The full API response.
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
*
* transaction.rollback((err) => {
* if (!err) {
* // Transaction rolled back successfully.
* }
* });
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* transaction.rollback().then((data) => {
* const apiResponse = data[0];
* });
*/
rollback(
gaxOptionsOrCallback?: CallOptions | RollbackCallback,
cb?: RollbackCallback
): void | Promise<RollbackResponse> {
const gaxOptions =
typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
const callback =
typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!;
this.request_(
{
client: 'DatastoreClient',
method: 'rollback',
gaxOpts: gaxOptions || {},
},
(err, resp) => {
this.skipCommit = true;
callback(err || null, resp);
}
);
}
run(options?: RunOptions): Promise<RunResponse>;
run(callback: RunCallback): void;
run(options: RunOptions, callback: RunCallback): void;
/**
* Begin a remote transaction. In the callback provided, run your
* transactional commands.
*
* @param {object} [options] Configuration object.
* @param {object} [options.gaxOptions] Request configuration options, outlined
* here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
* @param {boolean} [options.readOnly=false] A read-only transaction cannot
* modify entities.
* @param {string} [options.transactionId] The ID of a previous transaction.
* @param {function} callback The function to execute within the context of
* a transaction.
* @param {?error} callback.err An error returned while making this request.
* @param {Transaction} callback.transaction This transaction
* instance.
* @param {object} callback.apiResponse The full API response.
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*
* transaction.run((err, transaction) => {
* // Perform Datastore transactional operations.
* const key = datastore.key(['Company', 123]);
*
* transaction.get(key, (err, entity) => {
* entity.name = 'Google';
*
* transaction.save({
* key: key,
* data: entity
* });
*
* transaction.commit((err) => {
* if (!err) {
* // Data saved successfully.
* }
* });
* });
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* transaction.run().then((data) => {
* const transaction = data[0];
* const apiResponse = data[1];
* });
*/
run(
optionsOrCallback?: RunOptions | RunCallback,
cb?: RunCallback
): void | Promise<RunResponse> {
const options =
typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
const callback =
typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!;
const reqOpts = {
transactionOptions: {},
} as RequestOptions;
if (options.readOnly || this.readOnly) {
reqOpts.transactionOptions!.readOnly = {};
}
if (options.transactionId || this.id) {
reqOpts.transactionOptions!.readWrite = {
previousTransaction: options.transactionId || this.id,
};
}
if (options.transactionOptions) {
reqOpts.transactionOptions = options.transactionOptions;
}
this.request_(
{
client: 'DatastoreClient',
method: 'beginTransaction',
reqOpts,
gaxOpts: options.gaxOptions,
},
(err, resp) => {
if (err) {
callback(err, null, resp);
return;
}
this.id = resp!.transaction;
callback(null, this, resp);
}
);
}
/**
* Insert or update the specified object(s) in the current transaction. If a
* key is incomplete, its associated object is inserted and the original Key
* object is updated to contain the generated ID.
*
* This method will determine the correct Datastore method to execute
* (`upsert`, `insert`, or `update`) by using the key(s) provided. For
* example, if you provide an incomplete key (one without an ID), the request
* will create a new entity and have its ID automatically assigned. If you
* provide a complete key, the entity will be updated with the data specified.
*
* By default, all properties are indexed. To prevent a property from being
* included in *all* indexes, you must supply an `excludeFromIndexes` array.
* See below for an example.
*
* @param {object|object[]} entities Datastore key object(s).
* @param {Key} entities.key Datastore key object.
* @param {string[]} [entities.excludeFromIndexes] Exclude properties from
* indexing using a simple JSON path notation. See the example below to
* see how to target properties at different levels of nesting within your
* entity.
* @param {object} entities.data Data to save with the provided key.
*
* @example
* <caption>Save a single entity.</caption>
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*
* // Notice that we are providing an incomplete key. After the transaction is
* // committed, the Key object held by the `key` variable will be populated
* // with a path containing its generated ID.
* //-
* const key = datastore.key('Company');
*
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
*
* transaction.save({
* key: key,
* data: {
* rating: '10'
* }
* });
*
* transaction.commit((err) => {
* if (!err) {
* // Data saved successfully.
* }
* });
* });
*
* @example
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
*
* // Use an array, `excludeFromIndexes`, to exclude properties from indexing.
* // This will allow storing string values larger than 1500 bytes.
*
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
*
* transaction.save({
* key: key,
* excludeFromIndexes: [
* 'description',
* 'embeddedEntity.description',
* 'arrayValue[].description'
* ],
* data: {
* description: 'Long string (...)',
* embeddedEntity: {
* description: 'Long string (...)'
* },
* arrayValue: [
* {
* description: 'Long string (...)'
* }
* ]
* }
* });
*
* transaction.commit((err) => {
* if (!err) {
* // Data saved successfully.
* }
* });
* });
*
* @example
* <caption>Save multiple entities at once.</caption>
* const {Datastore} = require('@google-cloud/datastore');
* const datastore = new Datastore();
* const transaction = datastore.transaction();
* const companyKey = datastore.key(['Company', 123]);
* const productKey = datastore.key(['Product', 'Computer']);
*
* transaction.run((err) => {
* if (err) {
* // Error handling omitted.
* }
*
* transaction.save([
* {
* key: companyKey,
* data: {
* HQ: 'Dallas, TX'
* }
* },
* {
* key: productKey,
* data: {
* vendor: 'Dell'
* }
* }
* ]);
*
* transaction.commit((err) => {
* if (!err) {
* // Data saved successfully.
* }
* });
* });
*/
save(entities: Entities): void {
arrify(entities).forEach((ent: Entity) => {
this.modifiedEntities_.push({
entity: {
key: ent.key,
},
method: 'save',
args: [ent],
});
});
}
/**
* Maps to {@link Datastore#save}, forcing the method to be `update`.
*
* @param {object|object[]} entities Datastore key object(s).
* @param {Key} entities.key Datastore key object.
* @param {string[]} [entities.excludeFromIndexes] Exclude properties from
* indexing using a simple JSON path notation. See the examples in
* {@link Datastore#save} to see how to target properties at different
* levels of nesting within your entity.
* @param {object} entities.data Data to save with the provided key.
*/
update(entities: Entities): void {
entities = arrify(entities)
.map(DatastoreRequest.prepareEntityObject_)
.map((x: PrepareEntityObjectResponse) => {
x.method = 'update';
return x;
});
this.save(entities);
}
/**
* Maps to {@link Datastore#save}, forcing the method to be `upsert`.
*
* @param {object|object[]} entities Datastore key object(s).
* @param {Key} entities.key Datastore key object.
* @param {string[]} [entities.excludeFromIndexes] Exclude properties from
* indexing using a simple JSON path notation. See the examples in
* {@link Datastore#save} to see how to target properties at different
* levels of nesting within your entity.
* @param {object} entities.data Data to save with the provided key.
*/
upsert(entities: Entities): void {
entities = arrify(entities)
.map(DatastoreRequest.prepareEntityObject_)
.map((x: PrepareEntityObjectResponse) => {
x.method = 'upsert';
return x;
});
this.save(entities);
}
}
export type ModifiedEntities = Array<{
entity: {key: Entity};
method: string;
args: Entity[];
}>;
export type RunResponse = [
Transaction,
google.datastore.v1.IBeginTransactionResponse
];
export interface RunCallback {
(
error: Error | null,
transaction: Transaction | null,
response?: google.datastore.v1.IBeginTransactionResponse
): void;
}
export interface RollbackCallback {
(error: Error | null, response?: google.datastore.v1.IRollbackResponse): void;
}
export type RollbackResponse = [google.datastore.v1.IRollbackResponse];
export interface RunOptions {
readOnly?: boolean;
transactionId?: string;
transactionOptions?: TransactionOptions;
gaxOptions?: CallOptions;
}
/*! Developer Documentation
*
* All async methods (except for streams) will return a Promise in the event
* that a callback is omitted.
*/
promisifyAll(Transaction, {
exclude: ['createQuery', 'delete', 'insert', 'save', 'update', 'upsert'],
});
/**
* Reference to the {@link Transaction} class.
* @name module:@google-cloud/datastore.Transaction
* @see Transaction
*/
export {Transaction}; | the_stack |
import * as tf from '../../index';
import {ALL_ENVS, describeWithFlags} from '../../jasmine_util';
import {expectArraysClose} from '../../test_util';
describeWithFlags('resizeBilinear', ALL_ENVS, () => {
it('simple alignCorners=false', async () => {
const input = tf.tensor3d([2, 2, 4, 4], [2, 2, 1]);
const output = input.resizeBilinear([3, 3], false);
expectArraysClose(
await output.data(), [2, 2, 2, 10 / 3, 10 / 3, 10 / 3, 4, 4, 4]);
});
it('5x5-bilinear, no change in shape', async () => {
const image: tf.Tensor4D = tf.ones([1, 5, 5, 3]);
const alignCorners = false;
const output = tf.image.resizeBilinear(image, [5, 5], alignCorners);
expect(output.shape).toEqual([1, 5, 5, 3]);
expect(output.dtype).toBe('float32');
expectArraysClose(await output.data(), await image.data());
});
it('simple alignCorners=true', async () => {
const input = tf.tensor3d([2, 2, 4, 4], [2, 2, 1]);
const output = input.resizeBilinear([3, 3], true);
expectArraysClose(await output.data(), [2, 2, 2, 3, 3, 3, 4, 4, 4]);
});
it('works when rows are copied', async () => {
const input = tf.tensor3d(
[
1.56324531, 2.13817752, 1.44398421, 1.07632684, 0.59306785,
-0.36970865, 1.62451879, 1.8367334, 1.13944798, 2.01993218,
2.01919952, 2.67524054
],
[2, 3, 2]);
const output = input.resizeBilinear([4, 3], false);
expectArraysClose(await output.data(), [
1.5632453, 2.13817763, 1.44398415, 1.07632685, 0.59306782, -0.36970866,
1.59388208, 1.98745549, 1.2917161, 1.54812956, 1.30613375, 1.15276587,
1.62451875, 1.83673334, 1.13944793, 2.01993227, 2.01919961, 2.67524052,
1.62451875, 1.83673334, 1.13944793, 2.01993227, 2.01919961, 2.67524052
]);
});
it('works for ints', async () => {
const input = tf.tensor3d([1, 2, 3, 4, 5], [1, 5, 1], 'int32');
const output = input.resizeBilinear([1, 10], false);
expect(output.shape).toEqual([1, 10, 1]);
expect(output.dtype).toBe('float32');
expectArraysClose(
await output.data(), [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5]);
});
it('matches tensorflow w/ random numbers alignCorners=false, ' +
'halfPixelCenters=true',
async () => {
const input = tf.tensor3d(
[
1.19074044, 0.91373104, 2.01611669, -0.52270832, 0.38725395,
1.30809779, 0.61835143, 3.49600659, 2.09230986, 0.56473997,
0.03823943, 1.19864896
],
[2, 3, 2]);
const output = input.resizeBilinear([4, 5], false, true);
expectArraysClose(await output.data(), [
1.1907405, 0.913731, 1.520891, 0.3391553, 2.0161166, -0.5227083,
1.0387988, 0.5757756, 0.3872539, 1.3080978, 1.0476432, 1.5592999,
1.442652, 0.8352414, 2.0351648, -0.2508462, 0.9940659, 0.6681031,
0.3000003, 1.2807356, 0.7614487, 2.8504376, 1.2861738, 1.8274136,
2.0732617, 0.2928779, 0.9046002, 0.8527579, 0.125493, 1.2260112,
0.6183515, 3.4960065, 1.2079349, 2.3234997, 2.09231, 0.5647399,
0.8598673, 0.9450854, 0.0382394, 1.1986489
]);
});
it('batch of 2, simple, alignCorners=false, ' +
'halfPixelCenters=true',
async () => {
const input = tf.tensor4d([2, 2, 4, 4, 3, 3, 5, 5], [2, 2, 2, 1]);
const output =
input.resizeBilinear([3, 3], false /* alignCorners */, true);
expectArraysClose(
await output.data(),
[2, 2, 2, 3, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 5, 5, 5]);
});
it('target width = 1, alignCorners=false, ' +
'halfPixelCenters=true',
async () => {
const input = tf.tensor3d([
[
[120.68856811523438, 134.51638793945312, 83.03671264648438],
[121.58008575439453, 113.28836059570312, 136.3172149658203],
[79.38370513916016, 101.87127685546875, 104.54979705810547],
[96.31678771972656, 111.77168273925781, 83.73509979248047]
],
[
[119.45088195800781, 88.98846435546875, 97.47553253173828],
[117.5562973022461, 108.26356506347656, 99.62212371826172],
[136.62701416015625, 94.10433197021484, 80.97366333007812],
[83.61205291748047, 90.60148620605469, 81.82512664794922]
],
[
[103.0362777709961, 123.1098403930664, 125.62944030761719],
[92.2915267944336, 103.15729522705078, 119.18060302734375],
[102.93293762207031, 117.821044921875, 99.40152740478516],
[96.32952117919922, 105.80963134765625, 104.8491439819336]
],
[
[104.87507629394531, 134.0189208984375, 111.02627563476562],
[85.4534683227539, 107.68426513671875, 103.03722381591797],
[89.70533752441406, 98.25298309326172, 78.42916870117188],
[113.6744613647461, 95.8189697265625, 122.75005340576172]
]
]);
const output = input.resizeBilinear([3, 1], false, true);
const expected = [
104.917, 106.514, 115.411, 112.352, 105.837, 99.7945, 89.2515, 104.222,
93.8262
];
expectArraysClose(await output.data(), expected);
expect(output.shape).toEqual([3, 1, 3]);
});
it('matches tensorflow w/ random numbers alignCorners=false', async () => {
const input = tf.tensor3d(
[
1.19074044, 0.91373104, 2.01611669, -0.52270832, 0.38725395,
1.30809779, 0.61835143, 3.49600659, 2.09230986, 0.56473997,
0.03823943, 1.19864896
],
[2, 3, 2]);
const output = input.resizeBilinear([4, 5], false);
expectArraysClose(await output.data(), [
1.19074047, 0.91373104, 1.68596613, 0.05186744, 1.69034398, -0.15654698,
0.7130264, 0.94193673, 0.38725394, 1.30809784, 0.9045459, 2.20486879,
1.59434628, 0.89455694, 1.68591988, 0.26748738, 0.58103991, 1.00690198,
0.21274668, 1.25337338, 0.6183514, 3.49600649, 1.50272655, 1.73724651,
1.68149579, 0.69152176, 0.44905344, 1.07186723, 0.03823943, 1.19864893,
0.6183514, 3.49600649, 1.50272655, 1.73724651, 1.68149579, 0.69152176,
0.44905344, 1.07186723, 0.03823943, 1.19864893
]);
});
it('matches tensorflow w/ random numbers alignCorners=true', async () => {
const input = tf.tensor3d(
[
1.56324531, 2.13817752, 1.44398421, 1.07632684, 0.59306785,
-0.36970865, 1.62451879, 1.8367334, 1.13944798, 2.01993218,
2.01919952, 2.67524054
],
[2, 3, 2]);
const output = input.resizeBilinear([4, 5], true);
expectArraysClose(await output.data(), [
1.5632453, 2.13817763, 1.50361478, 1.60725224, 1.44398427, 1.07632685,
1.01852608, 0.35330909, 0.59306782, -0.36970866, 1.58366978, 2.03769612,
1.46307099, 1.71427906, 1.3424722, 1.39086199, 1.20545864, 1.01806819,
1.06844509, 0.6452744, 1.60409427, 1.93721485, 1.42252707, 1.82130599,
1.24096, 1.70539713, 1.3923912, 1.68282723, 1.54382229, 1.66025746,
1.62451875, 1.83673346, 1.38198328, 1.92833281, 1.13944793, 2.01993227,
1.57932377, 2.34758639, 2.01919961, 2.67524052
]);
});
it('batch of 2, simple, alignCorners=true', async () => {
const input = tf.tensor4d([2, 2, 4, 4, 3, 3, 5, 5], [2, 2, 2, 1]);
const output = input.resizeBilinear([3, 3], true /* alignCorners */);
expectArraysClose(
await output.data(),
[2, 2, 2, 3, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 5, 5, 5]);
});
it('target width = 1, alignCorners=true', async () => {
const input = tf.tensor3d([
[
[120.68856811523438, 134.51638793945312, 83.03671264648438],
[121.58008575439453, 113.28836059570312, 136.3172149658203],
[79.38370513916016, 101.87127685546875, 104.54979705810547],
[96.31678771972656, 111.77168273925781, 83.73509979248047]
],
[
[119.45088195800781, 88.98846435546875, 97.47553253173828],
[117.5562973022461, 108.26356506347656, 99.62212371826172],
[136.62701416015625, 94.10433197021484, 80.97366333007812],
[83.61205291748047, 90.60148620605469, 81.82512664794922]
],
[
[103.0362777709961, 123.1098403930664, 125.62944030761719],
[92.2915267944336, 103.15729522705078, 119.18060302734375],
[102.93293762207031, 117.821044921875, 99.40152740478516],
[96.32952117919922, 105.80963134765625, 104.8491439819336]
],
[
[104.87507629394531, 134.0189208984375, 111.02627563476562],
[85.4534683227539, 107.68426513671875, 103.03722381591797],
[89.70533752441406, 98.25298309326172, 78.42916870117188],
[113.6744613647461, 95.8189697265625, 122.75005340576172]
]
]);
const output = input.resizeBilinear([3, 1], true);
const expected = [
120.68857, 134.51639, 83.03671, 111.243576, 106.04915, 111.55249,
104.87508, 134.01892, 111.026276
];
expectArraysClose(await output.data(), expected);
expect(output.shape).toEqual([3, 1, 3]);
});
it('target height = 1, alignCorners=true', async () => {
const input = tf.tensor3d([
[
[120.68856811523438, 134.51638793945312, 83.03671264648438],
[121.58008575439453, 113.28836059570312, 136.3172149658203],
[79.38370513916016, 101.87127685546875, 104.54979705810547],
[96.31678771972656, 111.77168273925781, 83.73509979248047]
],
[
[119.45088195800781, 88.98846435546875, 97.47553253173828],
[117.5562973022461, 108.26356506347656, 99.62212371826172],
[136.62701416015625, 94.10433197021484, 80.97366333007812],
[83.61205291748047, 90.60148620605469, 81.82512664794922]
],
[
[103.0362777709961, 123.1098403930664, 125.62944030761719],
[92.2915267944336, 103.15729522705078, 119.18060302734375],
[102.93293762207031, 117.821044921875, 99.40152740478516],
[96.32952117919922, 105.80963134765625, 104.8491439819336]
],
[
[104.87507629394531, 134.0189208984375, 111.02627563476562],
[85.4534683227539, 107.68426513671875, 103.03722381591797],
[89.70533752441406, 98.25298309326172, 78.42916870117188],
[113.6744613647461, 95.8189697265625, 122.75005340576172]
]
]);
const output = input.resizeBilinear([1, 3], true);
const expected = [
120.68857, 134.51639, 83.03671, 100.481895, 107.57982, 120.4335, 96.31679,
111.77168, 83.7351
];
expectArraysClose(await output.data(), expected);
expect(output.shape).toEqual([1, 3, 3]);
});
it('throws when passed a non-tensor', () => {
const e = /Argument 'images' passed to 'resizeBilinear' must be a Tensor/;
expect(() => tf.image.resizeBilinear({} as tf.Tensor3D, [
1, 1
])).toThrowError(e);
});
it('accepts a tensor-like object', async () => {
const input = [[[2], [2]], [[4], [4]]]; // 2x2x1
const output = tf.image.resizeBilinear(input, [3, 3], false);
expectArraysClose(
await output.data(), [2, 2, 2, 10 / 3, 10 / 3, 10 / 3, 4, 4, 4]);
});
});
describeWithFlags('resizeBilinear gradients', ALL_ENVS, () => {
it('greyscale: upscale, same aspect ratio', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([
[[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]],
[[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]]
]);
const size: [number, number] = [4, 4];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [6.0, 17.0, 38.0, 75.0];
expectArraysClose(await output.data(), expected);
});
it('with clones, greyscale: upscale, same aspect ratio', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([
[[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]],
[[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]]
]);
const size: [number, number] = [4, 4];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) =>
tf.image.resizeBilinear(i.clone(), size, alignCorners).clone());
const output = g(input, dy);
const expected = [6.0, 17.0, 38.0, 75.0];
expectArraysClose(await output.data(), expected);
});
it('greyscale: upscale, same aspect ratio, align corners', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([
[[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]],
[[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]]
]);
const size: [number, number] = [4, 4];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected =
[17.333330154418945, 23.999998092651367, 44.0, 50.66666793823242];
expectArraysClose(await output.data(), expected);
});
it('greyscale: upscale, taller than wider', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([
[[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]],
[[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]],
[[17.0], [18.0], [19.0], [20.0]], [[21.0], [22.0], [23.0], [24.0]],
[[25.0], [26.0], [27.0], [28.0]], [[29.0], [30.0], [31.0], [32.0]],
[[33.0], [34.0], [35.0], [36.0]]
]);
const size: [number, number] = [9, 4];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
25.55555534362793, 55.5555534362793, 208.44444274902344, 376.4444274902344
];
expectArraysClose(await output.data(), expected);
});
it('greyscale: upscale, taller than wider, align corners', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([
[[1.0], [2.0], [3.0], [4.0]], [[5.0], [6.0], [7.0], [8.0]],
[[9.0], [10.0], [11.0], [12.0]], [[13.0], [14.0], [15.0], [16.0]],
[[17.0], [18.0], [19.0], [20.0]], [[21.0], [22.0], [23.0], [24.0]],
[[25.0], [26.0], [27.0], [28.0]], [[29.0], [30.0], [31.0], [32.0]],
[[33.0], [34.0], [35.0], [36.0]]
]);
const size: [number, number] = [9, 4];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [99.0, 114.0, 219.00001525878906, 233.99998474121094];
expectArraysClose(await output.data(), expected);
});
it('greyscale: upscale, wider than taller', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([
[[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0]],
[[8.0], [9.0], [10.0], [11.0], [12.0], [13.0], [14.0]],
[[15.0], [16.0], [17.0], [18.0], [19.0], [20.0], [21.0]],
[[22.0], [23.0], [24.0], [25.0], [26.0], [27.0], [28.0]]
]);
const size: [number, number] = [4, 7];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
14.428570747375488, 52.07142639160156, 98.71427917480469,
240.78573608398438
];
expectArraysClose(await output.data(), expected);
});
it('greyscale: upscale, wider than taller, align corners', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([
[[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0]],
[[8.0], [9.0], [10.0], [11.0], [12.0], [13.0], [14.0]],
[[15.0], [16.0], [17.0], [18.0], [19.0], [20.0], [21.0]],
[[22.0], [23.0], [24.0], [25.0], [26.0], [27.0], [28.0]]
]);
const size: [number, number] = [4, 7];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [51.33332824707031, 70.0, 133.0, 151.66668701171875];
expectArraysClose(await output.data(), expected);
});
// Downscale
it('greyscale: downscale, same aspect ratio', async () => {
const input = tf.tensor3d([
[[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]],
[[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]]
]);
const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]);
const size: [number, number] = [2, 2];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0,
0.0
];
expectArraysClose(await output.data(), expected);
});
it('greyscale: downscale, same aspect ratio, align corners', async () => {
const input = tf.tensor3d([
[[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]],
[[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]]
]);
const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]);
const size: [number, number] = [2, 2];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0,
4.0
];
expectArraysClose(await output.data(), expected);
});
it('greyscale: downscale, taller than wider', async () => {
const input = tf.tensor3d([
[[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]],
[[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]]
]);
const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]], [[5.0], [6.0]]]);
const size: [number, number] = [3, 2];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 0.0, 2.0, 0.0, 1.9999998807907104, 0.0, 2.6666665077209473, 0.0,
2.6666665077209473, 0.0, 3.3333330154418945, 0.0, 3.333333730697632, 0.0,
4.000000476837158, 0.0
];
expectArraysClose(await output.data(), expected);
});
it('greyscale: downscale, taller than wider, align corners', async () => {
const input = tf.tensor3d([
[[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]],
[[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]]
]);
const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]], [[5.0], [6.0]]]);
const size: [number, number] = [3, 2];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 0.0, 0.0, 2.0, 1.5, 0.0, 0.0, 2.0, 1.5, 0.0, 0.0, 2.0, 5.0, 0.0, 0.0,
6.0
];
expectArraysClose(await output.data(), expected);
});
it('greyscale: downscale, wider than taller', async () => {
const input = tf.tensor3d([
[[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]],
[[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]]
]);
const dy = tf.tensor3d([[[1.0], [2.0], [3.0]], [[4.0], [5.0], [6.0]]]);
const size: [number, number] = [2, 3];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 1.3333332538604736, 1.6666665077209473, 2.000000238418579, 0.0, 0.0,
0.0, 0.0, 4.0, 3.3333330154418945, 3.6666665077209473, 4.000000476837158,
0.0, 0.0, 0.0, 0.0
];
expectArraysClose(await output.data(), expected);
});
it('greyscale: downscale, wider than taller, align corners', async () => {
const input = tf.tensor3d([
[[100.0], [50.0], [25.0], [10.0]], [[60.0], [20.0], [80.0], [20.0]],
[[40.0], [15.0], [200.0], [203.0]], [[40.0], [10.0], [230.0], [200.0]]
]);
const dy = tf.tensor3d([[[1.0], [2.0], [3.0]], [[4.0], [5.0], [6.0]]]);
const size: [number, number] = [2, 3];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 1.0, 1.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 2.5, 2.5,
6.0
];
expectArraysClose(await output.data(), expected);
});
// No Op
it('greyscale: same size', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]);
const size: [number, number] = [2, 2];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [1.0, 2.0, 3.0, 4.0];
expectArraysClose(await output.data(), expected);
});
it('greyscale: same size, align corners', async () => {
const input = tf.tensor3d([[[100.0], [50.0]], [[60.0], [20.0]]]);
const dy = tf.tensor3d([[[1.0], [2.0]], [[3.0], [4.0]]]);
const size: [number, number] = [2, 2];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [1.0, 2.0, 3.0, 4.0];
expectArraysClose(await output.data(), expected);
});
// 3 channel upscale
it('color: upscale, wider than taller', async () => {
const input = tf.tensor3d([
[
[115.11029815673828, 111.90936279296875, 66.87433624267578],
[72.03849029541016, 81.86637878417969, 119.53585815429688]
],
[
[68.555419921875, 97.49642181396484, 116.90741729736328],
[128.69467163085938, 86.78314208984375, 104.3116683959961]
]
]);
const dy = tf.tensor3d([
[
[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0],
[13.0, 14.0, 15.0]
],
[
[16.0, 17.0, 18.0], [19.0, 20.0, 21.0], [22.0, 23.0, 24.0],
[25.0, 26.0, 27.0], [28.0, 29.0, 30.0]
],
[
[31.0, 32.0, 33.0], [34.0, 35.0, 36.0], [37.0, 38.0, 39.0],
[40.0, 41.0, 42.0], [43.0, 44.0, 45.0]
]
]);
const size: [number, number] = [3, 5];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
15.399999618530273, 17.799999237060547, 20.19999885559082,
56.26666259765625, 60.533329010009766, 64.79999542236328,
80.00000762939453, 83.0, 86.0, 178.33334350585938, 183.66668701171875,
189.00001525878906
];
expectArraysClose(await output.data(), expected);
});
it('color: upscale, wider than taller, align corners', async () => {
const input = tf.tensor3d([
[
[115.11029815673828, 111.90936279296875, 66.87433624267578],
[72.03849029541016, 81.86637878417969, 119.53585815429688]
],
[
[68.555419921875, 97.49642181396484, 116.90741729736328],
[128.69467163085938, 86.78314208984375, 104.3116683959961]
]
]);
const dy = tf.tensor3d([
[
[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0],
[13.0, 14.0, 15.0]
],
[
[16.0, 17.0, 18.0], [19.0, 20.0, 21.0], [22.0, 23.0, 24.0],
[25.0, 26.0, 27.0], [28.0, 29.0, 30.0]
],
[
[31.0, 32.0, 33.0], [34.0, 35.0, 36.0], [37.0, 38.0, 39.0],
[40.0, 41.0, 42.0], [43.0, 44.0, 45.0]
]
]);
const size: [number, number] = [3, 5];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
33.75, 37.5, 41.25, 56.25, 60.0, 63.75, 108.75, 112.5, 116.25, 131.25,
135.0, 138.75
];
expectArraysClose(await output.data(), expected);
});
// 3 channel downscale
it('color: downscale, taller than wider', async () => {
const input = tf.tensor3d([
[
[120.68856811523438, 134.51638793945312, 83.03671264648438],
[121.58008575439453, 113.28836059570312, 136.3172149658203],
[79.38370513916016, 101.87127685546875, 104.54979705810547],
[96.31678771972656, 111.77168273925781, 83.73509979248047]
],
[
[119.45088195800781, 88.98846435546875, 97.47553253173828],
[117.5562973022461, 108.26356506347656, 99.62212371826172],
[136.62701416015625, 94.10433197021484, 80.97366333007812],
[83.61205291748047, 90.60148620605469, 81.82512664794922]
],
[
[103.0362777709961, 123.1098403930664, 125.62944030761719],
[92.2915267944336, 103.15729522705078, 119.18060302734375],
[102.93293762207031, 117.821044921875, 99.40152740478516],
[96.32952117919922, 105.80963134765625, 104.8491439819336]
],
[
[104.87507629394531, 134.0189208984375, 111.02627563476562],
[85.4534683227539, 107.68426513671875, 103.03722381591797],
[89.70533752441406, 98.25298309326172, 78.42916870117188],
[113.6744613647461, 95.8189697265625, 122.75005340576172]
]
]);
const dy =
tf.tensor3d([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0]]]);
const size: [number, number] = [3, 1];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0,
2.0,
3.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
2.6666665077209473,
3.3333330154418945,
3.999999761581421,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
3.666666269302368,
4.3333330154418945,
4.999999523162842,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
4.6666669845581055,
5.333333969116211,
6.000000953674316,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
];
expectArraysClose(await output.data(), expected);
});
it('color: downscale, width = 1, align corners', async () => {
const input = tf.tensor3d([
[
[120.68856811523438, 134.51638793945312, 83.03671264648438],
[121.58008575439453, 113.28836059570312, 136.3172149658203],
[79.38370513916016, 101.87127685546875, 104.54979705810547],
[96.31678771972656, 111.77168273925781, 83.73509979248047]
],
[
[119.45088195800781, 88.98846435546875, 97.47553253173828],
[117.5562973022461, 108.26356506347656, 99.62212371826172],
[136.62701416015625, 94.10433197021484, 80.97366333007812],
[83.61205291748047, 90.60148620605469, 81.82512664794922]
],
[
[103.0362777709961, 123.1098403930664, 125.62944030761719],
[92.2915267944336, 103.15729522705078, 119.18060302734375],
[102.93293762207031, 117.821044921875, 99.40152740478516],
[96.32952117919922, 105.80963134765625, 104.8491439819336]
],
[
[104.87507629394531, 134.0189208984375, 111.02627563476562],
[85.4534683227539, 107.68426513671875, 103.03722381591797],
[89.70533752441406, 98.25298309326172, 78.42916870117188],
[113.6744613647461, 95.8189697265625, 122.75005340576172]
]
]);
const dy =
tf.tensor3d([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0]]]);
const size: [number, number] = [3, 1];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
2.0, 2.5, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
2.0, 2.5, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
7.0, 8.0, 9.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
];
expectArraysClose(await output.data(), expected);
});
it('color: downscale, height = 1, align corners', async () => {
const input = tf.tensor3d([
[
[120.68856811523438, 134.51638793945312, 83.03671264648438],
[121.58008575439453, 113.28836059570312, 136.3172149658203],
[79.38370513916016, 101.87127685546875, 104.54979705810547],
[96.31678771972656, 111.77168273925781, 83.73509979248047]
],
[
[119.45088195800781, 88.98846435546875, 97.47553253173828],
[117.5562973022461, 108.26356506347656, 99.62212371826172],
[136.62701416015625, 94.10433197021484, 80.97366333007812],
[83.61205291748047, 90.60148620605469, 81.82512664794922]
],
[
[103.0362777709961, 123.1098403930664, 125.62944030761719],
[92.2915267944336, 103.15729522705078, 119.18060302734375],
[102.93293762207031, 117.821044921875, 99.40152740478516],
[96.32952117919922, 105.80963134765625, 104.8491439819336]
],
[
[104.87507629394531, 134.0189208984375, 111.02627563476562],
[85.4534683227539, 107.68426513671875, 103.03722381591797],
[89.70533752441406, 98.25298309326172, 78.42916870117188],
[113.6744613647461, 95.8189697265625, 122.75005340576172]
]
]);
const dy = tf.tensor3d([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]);
const size: [number, number] = [1, 3];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1., 2., 3., 2., 2.5, 3., 2., 2.5, 3., 7., 8., 9., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.
];
expectArraysClose(await output.data(), expected);
});
it('color: downscale, taller than wider, align corners', async () => {
const input = tf.tensor3d([
[
[120.68856811523438, 134.51638793945312, 83.03671264648438],
[121.58008575439453, 113.28836059570312, 136.3172149658203],
[79.38370513916016, 101.87127685546875, 104.54979705810547],
[96.31678771972656, 111.77168273925781, 83.73509979248047]
],
[
[119.45088195800781, 88.98846435546875, 97.47553253173828],
[117.5562973022461, 108.26356506347656, 99.62212371826172],
[136.62701416015625, 94.10433197021484, 80.97366333007812],
[83.61205291748047, 90.60148620605469, 81.82512664794922]
],
[
[103.0362777709961, 123.1098403930664, 125.62944030761719],
[92.2915267944336, 103.15729522705078, 119.18060302734375],
[102.93293762207031, 117.821044921875, 99.40152740478516],
[96.32952117919922, 105.80963134765625, 104.8491439819336]
],
[
[104.87507629394531, 134.0189208984375, 111.02627563476562],
[85.4534683227539, 107.68426513671875, 103.03722381591797],
[89.70533752441406, 98.25298309326172, 78.42916870117188],
[113.6744613647461, 95.8189697265625, 122.75005340576172]
]
]);
const dy = tf.tensor3d([
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]],
[[13.0, 14.0, 15.0], [16.0, 17.0, 18.0]]
]);
const size: [number, number] = [3, 2];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected = [
1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.0, 6.0,
3.5, 4.0, 4.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 5.5, 6.0,
3.5, 4.0, 4.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 5.5, 6.0,
13.0, 14.0, 15.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 16.0, 17.0, 18.0
];
expectArraysClose(await output.data(), expected);
});
// 3 channel no-op
it('color: same size', async () => {
const input = tf.tensor3d([
[
[115.11029815673828, 111.90936279296875, 66.87433624267578],
[72.03849029541016, 81.86637878417969, 119.53585815429688]
],
[
[68.555419921875, 97.49642181396484, 116.90741729736328],
[128.69467163085938, 86.78314208984375, 104.3116683959961]
]
]);
const dy = tf.tensor3d([
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]
]);
const size: [number, number] = [2, 2];
const alignCorners = false;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected =
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0];
expectArraysClose(await output.data(), expected);
});
it('color: same size, align corners', async () => {
const input = tf.tensor3d([
[
[115.11029815673828, 111.90936279296875, 66.87433624267578],
[72.03849029541016, 81.86637878417969, 119.53585815429688]
],
[
[68.555419921875, 97.49642181396484, 116.90741729736328],
[128.69467163085938, 86.78314208984375, 104.3116683959961]
]
]);
const dy = tf.tensor3d([
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]
]);
const size: [number, number] = [2, 2];
const alignCorners = true;
const g = tf.grad(
(i: tf.Tensor3D) => tf.image.resizeBilinear(i, size, alignCorners));
const output = g(input, dy);
const expected =
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0];
expectArraysClose(await output.data(), expected);
});
}); | the_stack |
//Import Web Part properties
import { IWebPartContext } from '@microsoft/sp-webpart-base';
//Import SPHttpClient
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { SPPermission } from '@microsoft/sp-page-context';
export namespace SharePointUtilityModule {
export class SharePointUtility {
constructor() { }
// Checks if the current user has permissions to manage lists.
public static checkCurrentUserIsAbleToManageList(context: IWebPartContext): boolean {
let currentPermission = context.pageContext.web.permissions;
var isAbleToProvision = currentPermission.hasPermission(SPPermission.manageLists) && currentPermission.hasPermission(SPPermission.managePermissions);
console.log("Current user permission: { High:" + currentPermission.value.High + ",Low:" + currentPermission.value.Low + "}");
console.log("Current user is" + (isAbleToProvision ? " " : "not ") + "able to manage lists and permissions.");
return isAbleToProvision;
}
// Determines if a SharePoint list exists
public static checkListExists(context: IWebPartContext, listTitle: string): Promise<boolean> {
return context.spHttpClient.get(context.pageContext.web.absoluteUrl
+ "/_api/web/lists/GetByTitle('"
+ listTitle
+ "')?$select=Title", SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
if (response.status === 404) {
return false;
}
else {
return true;
}
});
}
// Creates a SharePoint list
public static createList(context: IWebPartContext,
listTitle: string,
listDescription: string,
baseTemplate: number,
enableApproval: boolean = true,
enableVersioning: boolean = false): Promise<any> {
console.log(`create list ${listTitle}`);
const reqJSON: any = JSON.parse(
`{
"@odata.type": "#SP.List",
"AllowContentTypes": true,
"BaseTemplate": ${baseTemplate},
"ContentTypesEnabled": true,
"Description": "${listDescription}",
"Title": "${listTitle}"
}`);
if (enableApproval){
reqJSON.EnableModeration = true;
}
if (enableVersioning){
reqJSON.EnableVersioning = true;
}
return context.spHttpClient.post(context.pageContext.web.absoluteUrl + "/_api/web/lists",
SPHttpClient.configurations.v1,
{
body: JSON.stringify(reqJSON),
headers: {
"accept": "application/json",
"content-type": "application/json"
}
})
.then((response: SPHttpClientResponse): Promise<any> => {
console.log("result: " + response.status);
return response.json();
});
}
// Creates a field in a SharePoint list
public static createListField(context: IWebPartContext,
listGuid: string,
title: string,
staticName: string,
required: boolean,
fieldType: string,
fieldTypeKind: number,
more?: Object,
lookuplistGuid?: string,
lookupFieldName?: string)
: Promise<any> {
console.log(`create list field ${title}`);
let reqJSON: Object,
postUrl: string = context.pageContext.web.absoluteUrl
+ "/_api/web/lists('"
+ listGuid
+ "')/Fields";
const headers: any = {
"accept": "application/json",
"content-type": "application/json"
};
if (fieldTypeKind == 7) {
//add lookupfield
reqJSON = JSON.parse(`{
"parameters": {
"@odata.type": "#SP.FieldCreationInformation",
"Title": "${title}",
"FieldTypeKind": ${fieldTypeKind},
"LookupListId": "${lookuplistGuid}",
"LookupFieldName": "${lookupFieldName}"
}
}`);
if (more != null) {
for (let i: number = 0; i < Object.getOwnPropertyNames(more).length; i++)
reqJSON["parameters"][Object.getOwnPropertyNames(more)[i]] = more[Object.getOwnPropertyNames(more)[i]];
}
postUrl += "/addfield";
}
else {
//general field
reqJSON = JSON.parse(`{
"@odata.type": "#${fieldType}",
"Title": "${title}",
"FieldTypeKind": ${fieldTypeKind},
"Required": ${required},
"StaticName": "${staticName}"
}`);
//date field
if (fieldTypeKind === 4) {
reqJSON["DateTimeCalendarType"] = 0;
reqJSON["DisplayFormat"] = 1;
reqJSON["FriendlyDisplayFormat"] = 1;
}
if (more != null) {
for (let i: number = 0; i < Object.getOwnPropertyNames(more).length; i++)
reqJSON[Object.getOwnPropertyNames(more)[i]] = more[Object.getOwnPropertyNames(more)[i]];
}
}
return context.spHttpClient.post(
postUrl,
SPHttpClient.configurations.v1,
{
body: JSON.stringify(reqJSON),
headers: headers
})
.then((response: SPHttpClientResponse): Promise<any> => {
console.log("result: " + response.status);
return response.json();
})
.then((value: any): string => {
return value.Id;
});
}
// Modifies a field in a SharePoint list
public static updateListField(context: IWebPartContext, listGuid: string, fieldGuid: string, fieldType: string, change: Object)
: Promise<any> {
let restUrl: string = context.pageContext.web.absoluteUrl
+ `/_api/web/lists('${listGuid}')/fields('${fieldGuid}')`;
let reqJSON = JSON.parse(`{
"@odata.type": "#${fieldType}"
}`);
if (change != null) {
for (let i: number = 0; i < Object.getOwnPropertyNames(change).length; i++)
reqJSON[Object.getOwnPropertyNames(change)[i]] = change[Object.getOwnPropertyNames(change)[i]];
}
console.log(`Modify a field ${fieldGuid} in a SharePoint list ${listGuid}`);
return context.spHttpClient.post(restUrl,
SPHttpClient.configurations.v1,
{
body: JSON.stringify(reqJSON),
headers: {
"accept": "application/json",
"content-type": "application/json",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
})
.then((response: SPHttpClientResponse): void => {
console.log("result: " + response.status);
});
}
// Creates a SharePoint Group in a SharePoint site
public static createGroup(context: IWebPartContext, groupTitle: string): Promise<any> {
console.log(`create group ${groupTitle}`);
let reqJSON: Object,
postUrl: string = context.pageContext.web.absoluteUrl
+ "/_api/web/sitegroups";
const headers: any = {
"accept": "application/json",
"content-type": "application/json"
};
reqJSON = JSON.parse(`{
"@odata.type": "#SP.Group",
"Title": "${groupTitle}"
}`);
return context.spHttpClient.post(
postUrl,
SPHttpClient.configurations.v1,
{
body: JSON.stringify(reqJSON),
headers: headers
})
.then((response: SPHttpClientResponse): Promise<any> => {
console.log("result: " + response.status);
return response.json();
});
}
// Creates a Role definition in a SharePoint site
public static createRole(context: IWebPartContext, roleTitle: string, high: string, low: string): Promise<void> {
console.log(`create role ${roleTitle}`);
let reqJSON: any,
restUrl: string = context.pageContext.web.absoluteUrl
+ "/_api/web/roledefinitions";
const headers: any = {
"accept": "application/json",
"content-type": "application/json;IEEE754Compatible=true"
};
reqJSON = JSON.parse(
`{
"@odata.type": "#SP.RoleDefinition",
"Name": "${roleTitle}",
"BasePermissions":
{
"High": "${high}",
"Low": "${low}"
}
}`);
return context.spHttpClient.post(
restUrl,
SPHttpClient.configurations.v1,{
body: JSON.stringify(reqJSON),
headers: headers
})
.then((response: SPHttpClientResponse): Promise<any> => {
console.log("result: " + response.status);
return response.json();
});
}
// Assigns a role definition to a user or group in SharePoint site
public static addRoleAssignment(context: IWebPartContext, principalid: string, roleId: string): Promise<any> {
let restUrl: string = context.pageContext.web.absoluteUrl
+ `/_api/web/roleassignments/addroleassignment(principalid=${principalid}, roledefid=${roleId})`;
const headers: any = {
"accept": "application/json",
"content-type": "application/json;IEEE754Compatible=true"
};
console.log(`Assign role ${roleId} to group/user ${principalid}`);
return context.spHttpClient.post(
restUrl,
SPHttpClient.configurations.v1,{
headers: headers
}).then((response: SPHttpClientResponse) =>{
console.log("result: " + response.status);
return Promise.resolve(true);
});
}
// Gets the role id for a role in the current web
public static getRoleId(context: IWebPartContext, roleName: string): Promise<string>{
let restUrl: string = context.pageContext.web.absoluteUrl
+ `/_api/web/roledefinitions?$filter=Name eq '${roleName}'`;
const headers: any = {
"accept": "application/json",
"content-type": "application/json;IEEE754Compatible=true"
};
return context.spHttpClient.get(
restUrl,
SPHttpClient.configurations.v1,{
headers: headers
})
.then((response: SPHttpClientResponse) => {
return response.json();
})
.then((json: { value: any[] }) => {
if (json.value != null)
return Promise.resolve(json.value[0].Id);
else
return Promise.resolve("");
});
}
// Breaks role inheritance on a SharePoint list
public static breakRoleInheritanceOfList(context: IWebPartContext, listTitle: string): Promise<void> {
let restUrl: string = context.pageContext.web.absoluteUrl
+ `/_api/web/lists/getbytitle('${listTitle}')/breakroleinheritance(true)`;
const headers: any = {
"accept": "application/json",
"content-type": "application/json;IEEE754Compatible=true"
};
console.log(`break role inheritance on the ${listTitle} list`);
return context.spHttpClient.post(
restUrl,
SPHttpClient.configurations.v1,{
headers: headers
}).then((response: SPHttpClientResponse) =>{
console.log("result: " + response.status);
});
}
// Adds a new role assignment for the group on a SharePoint list
public static setNewPermissionsForGroup(context: IWebPartContext, listTitle: string, principalid: string, roleid: string): Promise<void> {
let restUrl: string = context.pageContext.web.absoluteUrl
+ `/_api/web/lists/getbytitle('${listTitle}')/roleassignments/addroleassignment(principalid=${principalid},roledefid=${roleid})`;
const headers: any = {
"accept": "application/json",
"content-type": "application/json;IEEE754Compatible=true"
};
console.log(`Add the new role ${roleid} assignment for the group ${principalid} on the ${listTitle} list`);
return context.spHttpClient.post(
restUrl,
SPHttpClient.configurations.v1,{
headers: headers
}).then((response: SPHttpClientResponse) =>{
console.log("result: " + response.status);
});
}
// Sets or updates ReadSecurity or WriteSecurity on a SharePoint list
public static setListSecurity(context: IWebPartContext, listTitle: string, readSecurity: string, writeSecurity: string): Promise<void>{
let restUrl: string = context.pageContext.web.absoluteUrl
+ `/_api/web/lists/getbytitle('${listTitle}')`;
let reqJSON: any = JSON.parse(
`{
"@odata.type": "#SP.List",
"ReadSecurity": ${readSecurity},
"WriteSecurity": ${writeSecurity}
}`);
console.log(`set ReadSecurity to ${readSecurity} and WriteSecurity to ${writeSecurity} for ${listTitle} list`);
return context.spHttpClient.post(restUrl,
SPHttpClient.configurations.v1,
{
body: JSON.stringify(reqJSON),
headers: {
"accept": "application/json",
"content-type": "application/json",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
})
.then((response: SPHttpClientResponse): void => {
console.log("result: " + response.status);
});
}
}
} | the_stack |
'use strict';
const assert = require('assert');
const ttm = require('azure-pipelines-task-lib/mock-test');
const path = require('path');
function setResponseFile(name) {
process.env['MOCK_RESPONSES'] = path.join(__dirname, name);
}
describe('Azure Resource Group Deployment', function () {
this.timeout(30000);
before((done) => {
done();
});
after(function () {
});
process.env['AGENT_HOMEDIRECTORY'] = process.env['AGENT_HOMEDIRECTORY'] || "C:\\temp\\agent\\home";
process.env['BUILD_SOURCESDIRECTORY'] = process.env['BUILD_SOURCESDIRECTORY'] || "C:\\temp\\agent\\home\\sources",
process.env['SYSTEM_DEFAULTWORKINGDIRECTORY'] = process.env['SYSTEM_DEFAULTWORKINGDIRECTORY'] || "C:\\temp\\agent\\home";
process.env["AGENT_TEMPDIRECTORY"] = process.env["AGENT_TEMPDIRECTORY"] || "C:\\temp\\agent\\home\\temp";
// uncomment to get test traces
// process.env['TASK_TEST_TRACE'] = "1";
it("Successfully added Azure Pipelines Agent Extension on VM when option specified - Create or update RG", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "dummy";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") > 0, "Deployment group agent should have been added on all VMs");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("DGAgentHandlerMajorVersion") > 0, "Since agent major version has been upgraded, modify the task version and also in the loc string; both are in task.json.");
assert(tr.stdout.indexOf("Copying VM tags") > 0, "Tags should be copied");
assert(tr.stdout.indexOf("loc_mock_AddExtension") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_VMDetailsFetchSucceeded") > 0, "VM details should have been fetched");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Task fails when incorrect PAT token endpoint is given - Create or update RG", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "IncorrectPat";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.failed, "Should have failed");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_AddExtension") > 0, "TeamServicesAgent should have been tried to be added on the VM");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") <= 0, "TeamServicesAgent should not have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_DeleteExtension") > 0, "TeamServicesAgent should have been tried to be deleted from the VM, since the installation failed");
assert(tr.stdout.indexOf("loc_mock_DeletionSucceeded") > 0, "TeamServicesAgent should have been deleted successfully");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Task fails when PAT service endpoint not of type Token is given - Create or update RG", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "dummy";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Basic\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.failed, "Should have failed");
assert(tr.stdout.indexOf("loc_mock_OnlyTokenAuthAllowed") > 0, "TeamServicesAgent should not have been added on the VM");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Successfully removed failed extensions - Create or update RG", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "dummy_ProvisioningOfDeploymentGroupExtensionFailed";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.failed, "Should have failed");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_AddExtension") > 0, "TeamServicesAgent should have been tried to be added on the VM");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") <= 0, "TeamServicesAgent should not have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_DeleteExtension") > 0, "TeamServicesAgent should have been tried to be deleted from the VM, since the installation failed");
assert(tr.stdout.indexOf("loc_mock_DeletionSucceeded") > 0, "TeamServicesAgent should have been deleted successfully");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Did not add extensions if no vms present", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "noVMs";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") <= 0, "Deployment group agent should not have been added since there are no VMs");
assert(tr.stdout.indexOf("Copying VM tags") <= 0, "Tags should not be copied since there are no VMs");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_AddExtension") <= 0, "TeamServicesAgent should not have been added since there are no VMs");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") <= 0, "TeamServicesAgent should not have been added since there are no VMs");
assert(tr.stdout.indexOf("loc_mock_VMDetailsFetchSucceeded") <= 0, "VM details should not have been fetched since there are no VMs");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Started stopped vm and installed extension", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "StoppedVM";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") > 0, "Deployment group agent should have been added on all vms");
assert(tr.stdout.indexOf("Copying VM tags") > 0, "Tags should be copied ");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_AddExtension") > 0, "TeamServicesAgent should have been added");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") > 0, "TeamServicesAgent should have been added");
assert(tr.stdout.indexOf("loc_mock_VMDetailsFetchSucceeded") > 0, "VM details should have been fetched");
assert(tr.stdout.indexOf("VMStartFailed") <= 0, "");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Task Failed when a vm was transitioning", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "TransitioningVM";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.failed, "Should have failed");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "virtualMachineExtensions.createOrUpdate function should not have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") <= 0, "Deployment group agent should not have been added on all vms");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_VMTransitioningSkipExtensionAddition") > 0, "VM is transitionin. Adding extension should be skipped and task aborted.");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") < 0, "TeamServicesAgent should not have been added on the VM. Task is supposed to abort before that.");
assert(tr.stdout.indexOf("loc_mock_VMDetailsFetchSucceeded") > 0, "VM details should have been fetched");
assert(tr.stdout.indexOf("VMStartFailed") <= 0, "");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Tags not copied when option not checked", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "dummy";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "false";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") > 0, "Deployment group agent should have been added on all VMs");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("Copying VM tags") <= 0, "Tags should not be copied because option is not checked");
assert(tr.stdout.indexOf("loc_mock_AddExtension") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_VMDetailsFetchSucceeded") > 0, "VM details should have been fetched");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Successfully added Azure Pipelines Agent Extension on VM - Select RG", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Select Resource Group";
process.env["resourceGroupName"] = "dummy";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "a";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") > 0, "Deployment group agent should have been added on all VMs");
assert(tr.stdout.indexOf("loc_mock_AddExtension") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_VMDetailsFetchSucceeded") > 0, "VM details should have been fetched");
assert(tr.stdout.indexOf("Copying VM tags") > 0, "Tags should be copied");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Successfully added Azure Pipelines Agent Linux Extension on Linux VM", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "NonWindowsVM";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMWithDGAgent";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "virtualMachineExtensions.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") > 0, "Deployment group agent should have been added on all VMs");
assert(tr.stdout.indexOf("Copying VM tags") > 0, "Tags should be copied");
assert(tr.stdout.indexOf("loc_mock_AddExtension") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") > 0, "TeamServicesAgent should have been added on the VM");
assert(tr.stdout.indexOf("loc_mock_VMDetailsFetchSucceeded") > 0, "VM details should have been fetched");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Did not add Azure Pipelines Agent Extension on VM when option not specified", (done) => {
let tp = path.join(__dirname, "addVSTSExtension.js");
process.env["action"] = "Create Or Update Resource Group";
process.env["resourceGroupName"] = "dummy";
process.env["enableDeploymentPrerequisites"] = "ConfigureVMwithWinRM";
process.env["copyAzureVMTags"] = "true";
process.env["outputVariable"] = "";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("loc_mock_DGAgentAddedOnAllVMs") <= 0, "Deployment group agent should not have been added on all VMs");
assert(tr.stdout.indexOf("Copying VM tags") <= 0, "Tags should not be copied");
assert(tr.stdout.indexOf("loc_mock_AddingExtensionSucceeded") <= 0, "TeamServicesAgent should not have been added on the VM, since option was not specified");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Successfully deleted Azure Pipelines Agent Extension on VM - Delete VMs", (done) => {
let tp = path.join(__dirname, "deleteVSTSExtension.js");
process.env["action"] = "Delete";
process.env["resourceGroupName"] = "NonWindowsVM";
process.env["outputVariable"] = "";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.deleteMethod is called") > 0, "virtualMachineExtensions.deleteMethod function should have been called from azure-sdk");
assert(tr.stdout.indexOf("virtualMachines.deleteMethod is called") > 0, "Should have deleted VM");
assert(tr.stdout.indexOf("loc_mock_DeleteExtension") > 0, "Deployment group agent should have been tried to be deleted from VM");
assert(tr.stdout.indexOf("loc_mock_DeletionSucceeded") > 0, "Deployment group agent should have been deleted from VM");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Successfully deleted Azure Pipelines Agent Extension on VM - Delete RG", (done) => {
let tp = path.join(__dirname, "deleteVSTSExtension.js");
process.env["action"] = "DeleteRG";
process.env["resourceGroupName"] = "NonWindowsVM";
process.env["outputVariable"] = "";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.deleteMethod is called") > 0, "virtualMachineExtensions.deleteMethod function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentDeletedFromAllVMs") > 0, "Deployment group agent should have been deleted from all VMs");
assert(tr.stdout.indexOf("resourceGroup.deleteMethod is called") > 0, "Task should have called resourceGroup.deleteMethod function from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DeleteExtension") > 0, "Deployment group agent should have started to be deleted from VM");
assert(tr.stdout.indexOf("loc_mock_DeletionSucceeded") > 0, "Deployment group agent should have been deleted from VM");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Did not delete extensions if no vms present - Delete VMs", (done) => {
let tp = path.join(__dirname, "deleteVSTSExtension.js");
process.env["action"] = "Delete";
process.env["resourceGroupName"] = "noVMs";
process.env["outputVariable"] = "";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.deleteMethod is called") <= 0, "virtualMachineExtensions.deleteMethod function should not have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentDeletedFromAllVMs") <= 0, "Deployment group agent should not have been deleted since there are no VMs");
assert(tr.stdout.indexOf("loc_mock_VM_Delete") <= 0, "Should not have deleted VM since no vms present");
assert(tr.stdout.indexOf("loc_mock_DeleteExtension") <= 0, "Should not have tried to deleted extension since no vms are present");
assert(tr.stdout.indexOf("virtualMachines.deleteMethod is called") <= 0, "Should not have called virtualMachines.deleteMethod function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Did not delete extensions on stopped vm but vm got deleted- Delete VMs", (done) => {
let tp = path.join(__dirname, "deleteVSTSExtension.js");
process.env["action"] = "Delete";
process.env["resourceGroupName"] = "StoppedVM";
process.env["outputVariable"] = "";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.deleteMethod is called") > 0, "virtualMachineExtensions.deleteMethod function should have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentDeletedFromAllVMs") <= 0, "Deployment group agent should not have been deleted from all VMs");
assert(tr.stdout.indexOf("loc_mock_VM_Delete") > 0, "Should have deleted VM");
assert(tr.stdout.indexOf("loc_mock_DeleteExtension") > 0, "Should have tried to deleted extension");
assert(tr.stdout.indexOf("loc_mock_DeleteAgentManually") > 0, "Deletion warning should have been prompted");
assert(tr.stdout.indexOf("virtualMachines.deleteMethod is called") > 0, "Should have called virtualMachines.deleteMethod function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it("Did not delete extensions if no vms present - Delete RG", (done) => {
let tp = path.join(__dirname, "deleteVSTSExtension.js");
process.env["action"] = "DeleteRG";
process.env["resourceGroupName"] = "noVMs";
process.env["outputVariable"] = "";
process.env["ENDPOINT_AUTH_PatEndpoint"] = "{\"parameters\":{\"apitoken\":\"PAT\"},\"scheme\":\"Token\"}";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.deleteMethod is called") <= 0, "virtualMachineExtensions.deleteMethod function should not have been called from azure-sdk");
assert(tr.stdout.indexOf("loc_mock_DGAgentDeletedFromAllVMs") <= 0, "Deployment group agent should not have been deleted since there are not vms");
assert(tr.stdout.indexOf("loc_mock_DeleteExtension") <= 0, "Should not have tried to deleted extension since no vms are present");
assert(tr.stdout.indexOf("resourceGroup.deleteMethod is called") > 0, "Delete Resource Group function should have been called");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Successfully triggered createOrUpdate deployment', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("set ") < 0, "deploymentsOutput should not have been updated");
assert(tr.stdout.indexOf("properly sanitized") > 0, "Parameters should have been sanitized");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Successfully triggered createOrUpdate deployment and updated deploymentOutputs', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
process.env["deploymentOutputs"] = "someVar";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("properly sanitized") > 0, "Parameters should have been sanitized");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
assert(tr.stdout.indexOf("##vso[task.setvariable variable=someVar;]") >= 0, "deploymentsOutput should have been updated");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Create or Update RG, failed on faulty CSM template file', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "faultyCSM.json";
process.env["csmParametersFile"] = "faultyCSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.failed, "Task should have failed");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") == -1, "Task should have failed before calling deployments.createOrUpdate function from azure-sdk");
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
done();
});
it('Create or Update RG, succeeded on CSM template file with comments', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "CSMwithComments.json";
process.env["csmParametersFile"] = "CSMwithComments.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Should have succeeded");
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") > 0, "deployments.createOrUpdate function should have been called from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Selected Resource Group successfully', (done) => {
let tp = path.join(__dirname, 'selectResourceGroup.js');
process.env["outputVariable"] = "output.variable.custom";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("set output.variable.custom") >= 0, "Should have written to the output variable.");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "Should have called networkInterfaces.list from azure-sdk");
assert(tr.stdout.indexOf("publicIPAddresses.list is called") > 0, "Should have called publicIPAddresses.list from azure-sdk");
assert(tr.stdout.indexOf("virtualMachines.list is called") > 0, "Should have called virtualMachines.list from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Selected Resource Group successfully in Azure Stack environment', (done) => {
let tp = path.join(__dirname, 'selectResourceGroup.js');
process.env["outputVariable"] = "output.variable.custom";
process.env["ENDPOINT_DATA_AzureRM_ENVIRONMENT"] = "AzureStack";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("set output.variable.custom") >= 0, "Should have written to the output variable.");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "Should have called networkInterfaces.list from azure-sdk");
assert(tr.stdout.indexOf("publicIPAddresses.list is called") > 0, "Should have called publicIPAddresses.list from azure-sdk");
assert(tr.stdout.indexOf("virtualMachines.list is called") > 0, "Should have called virtualMachines.list from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
} finally {
delete process.env.ENDPOINT_DATA_AzureRM_ENVIRONMENT
}
});
it('Select Resource Group failed on empty output Variable', (done) => {
let tp = path.join(__dirname, 'selectResourceGroup.js');
process.env["outputVariable"] = "";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.failed, "Task should have failed");
assert(tr.stdout.indexOf("loc_mock_OutputVariableShouldNotBeEmpty") > 0, "Should have logged the output variable requirement.");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
/* Disabled due to intermittently failing (timing out) during CI:
Azure Resource Group Deployment Deleted Resource Group:
Error: timeout of 30000ms exceeded. Ensure the done() callback is being called in this test.
it("Deleted Resource Group", (done) => {
let tp = path.join(__dirname, 'deleteResourceGroup.js');
process.env["outputVariable"] = null;
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loc_mock_DeletingResourceGroup") > 0, "Delete Resource Group function should have been called");
assert(tr.stdout.indexOf("resourceGroup.deleteMethod is called") > 0, "Task should have called resourceGroup.deleteMethod function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
*/
it('Started VMs', (done) => {
let tp = path.join(__dirname, 'VMOperations.js');
process.env["operation"] = "Start";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loc_mock_VM_Start") > 0, "Should have started VM");
assert(tr.stdout.indexOf("virtualMachines.start is called") > 0, "Should have called virtualMachines.start function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Stopped VMs', (done) => {
let tp = path.join(__dirname, 'VMOperations.js');
process.env["operation"] = "Stop";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loc_mock_VM_Stop") > 0, "Should have stopped VM");
assert(tr.stdout.indexOf("virtualMachines.powerOff is called") > 0, "Should have called virtualMachines.powerOff function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Stopped VMs with deallocating', (done) => {
let tp = path.join(__dirname, 'VMOperations.js');
process.env["operation"] = "StopWithDeallocate";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loc_mock_VM_Deallocate") > 0, "Should have deallocated VM");
assert(tr.stdout.indexOf("virtualMachines.deallocate is called") > 0, "Should have called virtualMachines.deallocate function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Restarted VMs', (done) => {
let tp = path.join(__dirname, 'VMOperations.js');
process.env["operation"] = "Restart";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loc_mock_VM_Restart") > 0, "Should have started VM");
assert(tr.stdout.indexOf("virtualMachines.restart is called") > 0, "Should have called virtualMachines.restart function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Deleted VMs', (done) => {
let tp = path.join(__dirname, 'VMOperations.js');
process.env["operation"] = "Delete";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loc_mock_VM_Delete") > 0, "Should have started VM");
assert(tr.stdout.indexOf("virtualMachines.deleteMethod is called") > 0, "Should have called virtualMachines.deleteMethod function from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Vms doesnot have windows VM', (done) => {
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "NonWindowsVM";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("Enabling winrm for virtual machine") <= 0, "Should not enable winrm if the Operating System is not windows");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('No LB present, Vm Doesnot contain Custom Script Extension, Vm has no NSG', (done) => {
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionNotPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("Updating the load balancers with the appropriate Inbound Nat rules") <= 0, "Shouldn't add Inbound Nat Rule for the LB");
assert(tr.stdout.indexOf("Enabling winrm for virtual machine") > 0, "Should add Custom Script Extension to the virual machine");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "Should try getting the extension on the virtual machine");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should call createOrUpdate of virtual Machine extensions");
assert(tr.stdout.indexOf("Addition of extension completed for vm: customVM") > 0, "Should be able to add the extension");
assert(tr.stdout.indexOf("Provisioning of CustomScriptExtension on vm customVM is in Succeeded State") > 0, "Provisioning of the Custom Script Extension should be in succeeded state");
assert(tr.stdout.indexOf("Trying to add a network security group rule") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('1 LB 1 VM present, No Inbound Nat Rule Present', (done) => {
// VM has WinRMHttps Listener enabled, but no NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBOneVM";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") > 0, "LoadBalancers.createOrUpdate should have been called");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "The network Interfaces of the vms should be listed");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") > 0, "The network Interfaces of the vms should be updated with appropriate Inbound Nat Rules of LB");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should not try adding custom Script Extension as winrmHttps Listener is already enabled");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
//Assertion check
it('1 LB 2 Vms present, No Inbound Nat Rules Present', (done) => {
// VM has WinRMHttps Listener enabled, but no NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBTwoVMs";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") > 0, "LoadBalancers.createOrUpdate should have been called");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "The network Interfaces of the vms should be listed");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") > 0, "The network Interfaces of the vms should be updated with appropriate Inbound Nat Rules of LB");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should not enable winrm as it is already present");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('1 LB 1 VM present, Inbound Nat Rule Present but has no VM attached', (done) => {
// VM has WinRMHttps Listener enabled, but no NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBOneVMInboundNatRulesPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") > 0, "LoadBalancers.createOrUpdate should have been called");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "The network Interfaces of the vms should be listed");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") > 0, "The network Interfaces of the vms should be updated with appropriate Inbound Nat Rules of LB");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should not enable winrm as it is already present");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('1 LB 2 VMs present, Inbound Nat Rule Present but has no VM attached', (done) => {
// VM has WinRMHttps Listener enabled, but no NSG
// VM has WinRMHttps Listener enabled, but no NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBTwoVMsInboundNatRulesPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") > 0, "LoadBalancers.createOrUpdate should have been called");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "The network Interfaces of the vms should be listed");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") > 0, "The network Interfaces of the vms should be updated with appropriate Inbound Nat Rules of LB");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should not enable winrm as it is already present");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('1 LB 1 VM present, Inbound Nat Rule Present and has VM attached', (done) => {
// VM has WinRMHttps Listener enabled, but no NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBOneVMInboundNatRulesPresentVMAttached";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should not enable winrm as it is already present");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('1 LB 2 Vms Present, Inbound Nat Rule Present and has VM attached', (done) => {
// VM has WinRMHttps Listener enabled, but no NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBTwoVMsInboundNatRulesPresentVMsAttached";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should not enable winrm as it is already present");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('VM doesnot have WinRMHttps Listener enabled, but has no Nsg', (done) => {
// No LB present, No NSg
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionNotPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "Should get the status for Custom Script Extension");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should enable winrm Https Listener");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('WinRM Custom Script Extension is present on the VM, status is succeeded, substatus is succeeded', (done) => {
//No LB
//1 VM
//No NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("Updating the load balancers with the appropriate Inbound Nat rules") <= 0, "Shouldn't add Inbound Nat Rules to the LB");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("Updating the NIC of the concerned vms") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "Should get the list of all the Custom Script Extensions");
assert(tr.stdout.indexOf("Custom Script extension is for enabling Https Listener on VM") > 0, "The present custom script extension should enable winrm Https Listener");
assert(tr.stdout.indexOf("Validating the winrm configuration custom script extension status") > 0, "Should validate the substatus of the extension");
assert(tr.stdout.indexOf("virtualMachines.get is called with options: { expand: 'instanceView' }") > 0, "Should try to get the substatus of the extension");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should not add Custom Script Extension");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('WinRM Custom Script Extension is present on the VM , status is succeeded, substatus is failed', (done) => {
//No LB
//1 VM
//No NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionPresentInvalidSubstatus";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("Updating the load balancers with the appropriate Inbound Nat rules") <= 0, "Shouldn't add Inbound Nat Rules to the LB");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("Updating the NIC of the concerned vms") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("Custom Script extension is for enabling Https Listener on VM") > 0, "The present custom script extension should enable winrm Https Listener");
assert(tr.stdout.indexOf("Validating the winrm configuration custom script extension status") > 0, "Should validate the substatus of the extension present");
assert(tr.stdout.indexOf("virtualMachines.get is called with options: { expand: 'instanceView' }") > 0, "Should try to get the substatus of the extension");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should add the extension");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('WinRM Custom Script Extension is present on the VM, status is failed', (done) => {
//No LB
//1 VM
//No NSG
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionPresentProvisioningStateIsNotSucceeded";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("Updating the load balancers with the appropriate Inbound Nat rules") <= 0, "Shouldn't add Inbound Nat Rules to the LB");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("Updating the NIC of the concerned vms") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "The extensions on the vm should be listed to get the extension of concern");
assert(tr.stdout.indexOf("Custom Script extension is for enabling Https Listener on VM") > 0, "The present custom script extension should enable winrm Https Listener");
assert(tr.stdout.indexOf("virtualMachineExtensions.deleteMethod is called") > 0, "Should remove the extension");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should add the extension");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try adding NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('Vms have NSG', (done) => {
//No LB
//1 VM
//WinRMHttps Listener enabled
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionPresentNSGPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("Updating the load balancers with the appropriate Inbound Nat rules") <= 0, "Shouldn't add Inbound Nat Rules to the LB");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("Updating the NIC of the concerned vms") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("Custom Script extension is for enabling Https Listener on VM") > 0, "The present custom script extension should enable winrm Https Listener");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") <= 0, "Should add the extension");
assert(tr.stdout.indexOf("Validating the winrm configuration custom script extension status") > 0, "Should Validate the Custom Script Extension");
assert(tr.stdout.indexOf("networkSecurityGroups.list is called") > 0, "Should list the Network Security Groups");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") > 0, "Shouldn't try to add NSG rule");
assert(tr.stdout.indexOf("securityRules.get is called") > 0, "Should try to get the security rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('WinRM Custom Script Extension present is not for enabling WinRMHttpsListener', (done) => {
// No LB
// 1 VM, No Nsg
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionPresentWinRMHttpsListenerNotEnabled";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("Updating the load balancers with the appropriate Inbound Nat rules") <= 0, "Shouldn't add Inbound Nat Rules to the LB");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("Updating the NIC of the concerned vms") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "The extensions on the vm should be listed to get the extension of concern");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should update the extension to enable WinrmHttps Listener");
assert(tr.stdout.indexOf("networkSecurityGroups.list is called") > 0, "Should list the Network Security Groups");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") <= 0, "Shouldn't try to add NSG rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('WinRM Custom Script is not present, VM has NSG associated', (done) => {
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "ExtensionNotPresentNSGPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("Updating the load balancers with the appropriate Inbound Nat rules") <= 0, "Shouldn't add Inbound Nat Rules to the LB");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") <= 0, "LoadBalancers.createOrUpdate should not have been called");
assert(tr.stdout.indexOf("Updating the NIC of the concerned vms") <= 0, "The NIC of the VMs should not be updated");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should add the extension");
assert(tr.stdout.indexOf("networkSecurityGroups.list is called") > 0, "Should list the Network Security Groups");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") > 0, "Shouldn't try to add NSG rule");
assert(tr.stdout.indexOf("securityRules.get is called") > 0, "Should try to get the security rule");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('1 LB 1 VM, WinRM Custom Script extension is not present, VM has NSG associated', (done) => {
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBOneVMExtensionNotPresentNSGPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") > 0, "LoadBalancers.createOrUpdate should have been called");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "The network Interfaces of the vms should be listed");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") > 0, "The network Interfaces of the vms should be updated with appropriate Inbound Nat Rules of LB");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "Should try to list all the Custom Script Extensions");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should enable winrm Https Listener");
assert(tr.stdout.indexOf("networkSecurityGroups.list is called") > 0, "Should list the Network Security Groups");
assert(tr.stdout.indexOf("securityRules.get is called") > 0, "Should try to get the security rule");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") > 0, "Should add NSG Rules");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('1 LB 2 Vms, WinRM Custom Script Extension is not present, VMs have NSG associated', (done) => {
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "OneLBTwoVMsExtensionNotPresentNSGPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("loadBalancers.list is called") > 0, "loadBalancers.list should have been called");
assert(tr.stdout.indexOf("loadBalancers.createOrUpdate is called") > 0, "LoadBalancers.createOrUpdate should have been called");
assert(tr.stdout.indexOf("networkInterfaces.list is called") > 0, "The network Interfaces of the vms should be listed");
assert(tr.stdout.indexOf("networkInterfaces.createOrUpdate is called") > 0, "The network Interfaces of the vms should be updated with appropriate Inbound Nat Rules of LB");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "Should try to get the Custom Script Extension");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should enable winrm Https Listener");
assert(tr.stdout.indexOf("networkSecurityGroups.list is called") > 0, "Should list the Network Security Groups");
assert(tr.stdout.indexOf("securityRules.get is called") > 0, "Should try to get the security rule");
assert(tr.stdout.indexOf("securityRules.createOrUpdate is called: Added rule Name VSO-Custom-WinRM-Https-Port to the security Group") > 0, "Should add NSG Rules");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('WinRM Custom Script Extension is not present, but some other CustomScriptExtension is present', (done) => {
let tp = path.join(__dirname, 'EnablePrereq.js');
process.env["resourceGroupName"] = "SomeOtherCustomScriptExtensionPresent";
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(tr.succeeded, "Task should have succeeded");
assert(tr.stdout.indexOf("virtualMachineExtensions.list is called") > 0, "Should try to get the Custom Script Extension");
assert(tr.stdout.indexOf("virtualMachineExtensions.deleteMethod is called") > 0, "Should try to delete the already existing Custom Script extension");
assert(tr.stdout.indexOf("virtualMachineExtensions.createOrUpdate is called") > 0, "Should enable winrm Https Listener");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('createOrUpdate deployment should fail when no template file is found', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "CSMNotThere.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(!tr.succeeded, "Should have failed");
assert(tr.stdout.indexOf("TemplateFilePatternMatchingNoFile") > 0, "should have printed TemplateFilePatternMatchingNoFile")
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") < 0, "deployments.createOrUpdate function should not have been called from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('createOrUpdate deployment should fail when multiple template files are found', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "CSMmultiple.json";
process.env["csmParametersFile"] = "CSM.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(!tr.succeeded, "Should have failed");
assert(tr.stdout.indexOf("TemplateFilePatternMatchingMoreThanOneFile") > 0, "should have printed TemplateFilePatternMatchingMoreThanOneFile")
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") < 0, "deployments.createOrUpdate function should not have been called from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('createOrUpdate deployment should fail when no parameter file is found', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSMNotThere.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(!tr.succeeded, "Should have failed");
assert(tr.stdout.indexOf("TemplateParameterFilePatternMatchingNoFile") > 0, "should have printed TemplateParameterFilePatternMatchingNoFile")
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") < 0, "deployments.createOrUpdate function should not have been called from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
it('createOrUpdate deployment should fail when multiple template files are found', (done) => {
let tp = path.join(__dirname, 'createOrUpdate.js');
process.env["csmFile"] = "CSM.json";
process.env["csmParametersFile"] = "CSMmultiple.json";
let tr = new ttm.MockTestRunner(tp);
tr.run();
try {
assert(!tr.succeeded, "Should have failed");
assert(tr.stdout.indexOf("TemplateParameterFilePatternMatchingMoreThanOneFile") > 0, "should have printed TemplateFilePatternMatchingMoreThanOneFile")
assert(tr.stdout.indexOf("deployments.createOrUpdate is called") < 0, "deployments.createOrUpdate function should not have been called from azure-sdk");
done();
}
catch (error) {
console.log("STDERR", tr.stderr);
console.log("STDOUT", tr.stdout);
done(error);
}
});
}); | the_stack |
interface JQuery {
visibility: SemanticUI.Visibility;
}
declare namespace SemanticUI {
interface Visibility {
settings: VisibilitySettings;
/**
* Disable callbacks temporarily. This is useful if you need to adjust scroll position and do not want to trigger callbacks during the position change.
*/
(behavior: 'disable callbacks'): JQuery;
/**
* Re-enable callbacks
*/
(behavior: 'enable callbacks'): JQuery;
/**
* Returns whether element is on screen
*/
(behavior: 'is on screen'): boolean;
/**
* Returns whether element is off screen
*/
(behavior: 'is off screen'): boolean;
/**
* Returns number of pixels passed in current element from top of element
*/
(behavior: 'get pixels passed'): number;
/**
* Returns element calculations as object
*/
(behavior: 'get element calculations'): Visibility.ElementCalculations;
/**
* Returns screen calculations as object
*/
(behavior: 'get screen calculations'): Visibility.ScreenCalculations;
/**
* Returns screen size as object
*/
(behavior: 'get screen size'): Visibility.ScreenSize;
(behavior: 'destroy'): JQuery;
<K extends keyof VisibilitySettings>(behavior: 'setting', name: K, value?: undefined): VisibilitySettings._Impl[K];
<K extends keyof VisibilitySettings>(behavior: 'setting', name: K, value: VisibilitySettings._Impl[K]): JQuery;
(behavior: 'setting', value: VisibilitySettings): JQuery;
(settings?: VisibilitySettings): JQuery;
}
/**
* @see {@link http://semantic-ui.com/behaviors/visibility.html#/settings}
*/
type VisibilitySettings = VisibilitySettings.Param;
namespace VisibilitySettings {
type Param = (Pick<_Impl, 'once'> |
Pick<_Impl, 'continuous'> |
Pick<_Impl, 'type'> |
Pick<_Impl, 'initialCheck'> |
Pick<_Impl, 'context'> |
Pick<_Impl, 'refreshOnLoad'> |
Pick<_Impl, 'refreshOnResize'> |
Pick<_Impl, 'checkOnRefresh'> |
Pick<_Impl, 'zIndex'> |
Pick<_Impl, 'offset'> |
Pick<_Impl, 'includeMargin'> |
Pick<_Impl, 'throttle'> |
Pick<_Impl, 'observeChanges'> |
Pick<_Impl, 'transition'> |
Pick<_Impl, 'duration'> |
Pick<_Impl, 'onTopVisible'> |
Pick<_Impl, 'onTopPassed'> |
Pick<_Impl, 'onBottomVisible'> |
Pick<_Impl, 'onPassing'> |
Pick<_Impl, 'onBottomPassed'> |
Pick<_Impl, 'onTopVisibleReverse'> |
Pick<_Impl, 'onTopPassedReverse'> |
Pick<_Impl, 'onBottomVisibleReverse'> |
Pick<_Impl, 'onPassingReverse'> |
Pick<_Impl, 'onBottomPassedReverse'> |
Pick<_Impl, 'onOnScreen'> |
Pick<_Impl, 'onOffScreen'> |
Pick<_Impl, 'onLoad'> |
Pick<_Impl, 'onAllLoaded'> |
Pick<_Impl, 'onFixed'> |
Pick<_Impl, 'onUnfixed'> |
Pick<_Impl, 'onUpdate'> |
Pick<_Impl, 'onRefresh'> |
Pick<_Impl, 'className'> |
Pick<_Impl, 'error'> |
Pick<_Impl, 'namespace'> |
Pick<_Impl, 'name'> |
Pick<_Impl, 'silent'> |
Pick<_Impl, 'debug'> |
Pick<_Impl, 'performance'> |
Pick<_Impl, 'verbose'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
// region Functionality
/**
* When set to false a callback will occur each time an element passes the threshold for a condition.
*
* @default true
*/
once: boolean;
/**
* When set to true a callback will occur anytime an element passes a condition not just immediately after the threshold is met.
*
* @default false
*/
continuous: boolean;
/**
* Set to image to load images when on screen. Set to fixed to add class name fixed when passed.
*
* @default false
*/
type: false | 'image' | 'fixed';
/**
* Whether visibility conditions should be checked immediately on init
*
* @default true
*/
initialCheck: boolean;
/**
* The scroll context visibility should use.
*
* @default 'window'
*/
context: string | JQuery;
/**
* Whether visibility conditions should be checked on window load. This ensures that after images load content positions will be updated correctly.
*
* @default true
*/
refreshOnLoad: boolean;
/**
* Whether visibility conditions should be checked on window resize. Useful when content resizes causes continuous changes in position
*
* @default true
*/
refreshOnResize: boolean;
/**
* Whether visibility conditions should be checked on calls to refresh.
* These calls can be triggered from either resize, load or manually calling $('.foo').visibility('refresh')
*
* @default true
*/
checkOnRefresh: boolean;
/**
* Specify a z-index when using type: 'fixed'.
*
* @default 1
* @since 2.2
*/
zIndex: number;
/**
* Value that context scrollTop should be adjusted in pixels. Useful for making content appear below content fixed to the page.
*
* @default 0
*/
offset: number;
/**
* Whether element calculations should include its margin
*
* @default false
*/
includeMargin: boolean;
/**
* When set to an integer, scroll position will be debounced using this ms value. false will debounce with requestAnimationFrame.
*
* @default false
*/
throttle: false | number;
/**
* Whether to automatically refresh content when changes are made to the element's DOM subtree
*
* @default true
*/
observeChanges: boolean;
/**
* When using type: image allows you to specify transition when showing a loaded image
*
* @default false
*/
transition: false | string;
/**
* When using type: image allows you to specify transition duration
*
* @default 1000
*/
duration: number;
// endregion
// region Visibility Callbacks
/**
* Element's top edge has passed bottom of screen
*/
onTopVisible(this: JQuery): void;
/**
* Element's top edge has passed top of the screen
*/
onTopPassed(this: JQuery): void;
/**
* Element's bottom edge has passed bottom of screen
*/
onBottomVisible(this: JQuery): void;
/**
* Any part of an element is visible on screen
*/
onPassing(this: JQuery): void;
/**
* Element's bottom edge has passed top of screen
*/
onBottomPassed(this: JQuery): void;
/**
* Element's top edge has not passed bottom of screen
*/
onTopVisibleReverse(this: JQuery): void;
/**
* Element's top edge has not passed top of the screen
*/
onTopPassedReverse(this: JQuery): void;
/**
* Element's bottom edge has not passed bottom of screen
*/
onBottomVisibleReverse(this: JQuery): void;
/**
* Element's top has not passed top of screen but bottom has
*/
onPassingReverse(this: JQuery): void;
/**
* Element's bottom edge has not passed top of screen
*/
onBottomPassedReverse(this: JQuery): void;
onOnScreen(this: JQuery): void;
onOffScreen(this: JQuery): void;
// endregion
// region Image Callbacks
/**
* Occurs after an image has completed loading
*
* @since 2.2
*/
onLoad(this: JQuery): void;
/**
* Occurs after all img initialized at the same time have loaded.
*
* @since 2.2
*/
onAllLoaded(this: JQuery): void;
// endregion
// region Fixed Callbacks
/**
* Occurs after element has been assigned position fixed
*
* @since 2.2
*/
onFixed(this: JQuery): void;
/**
* Occurs after element has been removed from fixed position
*
* @since 2.2
*/
onUnfixed(this: JQuery): void;
// endregion
// region Utility Callbacks
/**
* Occurs each time an elements calculations are updated
*/
onUpdate(this: JQuery, calculations: Visibility.ElementCalculations): void;
/**
* Occurs whenever element's visibility is refreshed
*/
onRefresh(this: JQuery): void;
// endregion
// region DOM Settings
/**
* Class names used to attach style to state
*/
className: Visibility.ClassNameSettings;
// endregion
// region Debug Settings
error: Visibility.ErrorSettings;
// endregion
// region Component Settings
// region DOM Settings
/**
* Event namespace. Makes sure module teardown does not effect other events attached to an element.
*/
namespace: string;
// endregion
// region Debug Settings
/**
* Name used in log statements
*/
name: string;
/**
* Silences all console output including error messages, regardless of other debug settings.
*/
silent: boolean;
/**
* Debug output to console
*/
debug: boolean;
/**
* Show console.table output with performance metrics
*/
performance: boolean;
/**
* Debug output includes all internal behaviors
*/
verbose: boolean;
// endregion
// endregion
}
}
namespace Visibility {
interface ElementPosition {
fits: boolean;
offset: JQueryCoordinates;
width: number;
height: number;
}
interface ElementCalculations extends ElementPosition {
margin?: {
top: number;
bottom: number;
};
top: number;
bottom: number;
topVisible: boolean;
topPassed: boolean;
bottomVisible: boolean;
bottomPassed: boolean;
pixelsPassed: number;
percentagePassed: number;
onScreen: boolean;
passing: boolean;
offScreen: boolean;
}
interface ScreenCalculations {
top: number;
bottom: number;
}
interface ScreenSize {
height: number;
}
type ClassNameSettings = ClassNameSettings.Param;
namespace ClassNameSettings {
type Param = (Pick<_Impl, 'fixed'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'fixed'
*/
fixed: string;
}
}
type ErrorSettings = ErrorSettings.Param;
namespace ErrorSettings {
type Param = (Pick<_Impl, 'method'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'The method you called is not defined.'
*/
method: string;
}
}
}
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* SKU parameters supplied to the create RedisEnterprise operation.
*/
export interface Sku {
/**
* The type of RedisEnterprise cluster to deploy. Possible values: (Enterprise_E10,
* EnterpriseFlash_F300 etc.). Possible values include: 'Enterprise_E10', 'Enterprise_E20',
* 'Enterprise_E50', 'Enterprise_E100', 'EnterpriseFlash_F300', 'EnterpriseFlash_F700',
* 'EnterpriseFlash_F1500'
*/
name: SkuName;
/**
* The size of the RedisEnterprise cluster. Defaults to 2 or 3 depending on SKU. Valid values are
* (2, 4, 6, ...) for Enterprise SKUs and (3, 9, 15, ...) for Flash SKUs.
*/
capacity?: number;
}
/**
* The Private Endpoint resource.
*/
export interface PrivateEndpoint {
/**
* The ARM identifier for Private Endpoint
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
}
/**
* A collection of information about the state of the connection between service consumer and
* provider.
*/
export interface PrivateLinkServiceConnectionState {
/**
* Indicates whether the connection has been Approved/Rejected/Removed by the owner of the
* service. Possible values include: 'Pending', 'Approved', 'Rejected'
*/
status?: PrivateEndpointServiceConnectionStatus;
/**
* The reason for approval/rejection of the connection.
*/
description?: string;
/**
* A message indicating if changes on the service provider require any updates on the consumer.
*/
actionsRequired?: string;
}
/**
* Common fields that are returned in the response for all Azure Resource Manager resources
* @summary Resource
*/
export interface Resource extends BaseResource {
/**
* Fully qualified resource ID for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
* "Microsoft.Storage/storageAccounts"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* The Private Endpoint Connection resource.
*/
export interface PrivateEndpointConnection extends Resource {
/**
* The resource of private end point.
*/
privateEndpoint?: PrivateEndpoint;
/**
* A collection of information about the state of the connection between service consumer and
* provider.
*/
privateLinkServiceConnectionState: PrivateLinkServiceConnectionState;
/**
* The provisioning state of the private endpoint connection resource. Possible values include:
* 'Succeeded', 'Creating', 'Deleting', 'Failed'
*/
provisioningState?: PrivateEndpointConnectionProvisioningState;
}
/**
* The resource model definition for an Azure Resource Manager tracked top level resource which has
* 'tags' and a 'location'
* @summary Tracked Resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* Describes the RedisEnterprise cluster
*/
export interface Cluster extends TrackedResource {
/**
* The SKU to create, which affects price, performance, and features.
*/
sku: Sku;
/**
* The Availability Zones where this cluster will be deployed.
*/
zones?: string[];
/**
* The minimum TLS version for the cluster to support, e.g. '1.2'. Possible values include:
* '1.0', '1.1', '1.2'
*/
minimumTlsVersion?: TlsVersion;
/**
* DNS name of the cluster endpoint
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hostName?: string;
/**
* Current provisioning status of the cluster. Possible values include: 'Succeeded', 'Failed',
* 'Canceled', 'Creating', 'Updating', 'Deleting'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: ProvisioningState;
/**
* Current resource status of the cluster. Possible values include: 'Running', 'Creating',
* 'CreateFailed', 'Updating', 'UpdateFailed', 'Deleting', 'DeleteFailed', 'Enabling',
* 'EnableFailed', 'Disabling', 'DisableFailed', 'Disabled'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceState?: ResourceState;
/**
* Version of redis the cluster supports, e.g. '6'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly redisVersion?: string;
/**
* List of private endpoint connections associated with the specified RedisEnterprise cluster
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
}
/**
* A partial update to the RedisEnterprise cluster
*/
export interface ClusterUpdate {
/**
* The SKU to create, which affects price, performance, and features.
*/
sku?: Sku;
/**
* The minimum TLS version for the cluster to support, e.g. '1.2'. Possible values include:
* '1.0', '1.1', '1.2'
*/
minimumTlsVersion?: TlsVersion;
/**
* DNS name of the cluster endpoint
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hostName?: string;
/**
* Current provisioning status of the cluster. Possible values include: 'Succeeded', 'Failed',
* 'Canceled', 'Creating', 'Updating', 'Deleting'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: ProvisioningState;
/**
* Current resource status of the cluster. Possible values include: 'Running', 'Creating',
* 'CreateFailed', 'Updating', 'UpdateFailed', 'Deleting', 'DeleteFailed', 'Enabling',
* 'EnableFailed', 'Disabling', 'DisableFailed', 'Disabled'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceState?: ResourceState;
/**
* Version of redis the cluster supports, e.g. '6'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly redisVersion?: string;
/**
* List of private endpoint connections associated with the specified RedisEnterprise cluster
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Persistence-related configuration for the RedisEnterprise database
* @summary Persistence settings
*/
export interface Persistence {
/**
* Sets whether AOF is enabled.
*/
aofEnabled?: boolean;
/**
* Sets whether RDB is enabled.
*/
rdbEnabled?: boolean;
/**
* Sets the frequency at which data is written to disk. Possible values include: '1s', 'always'
*/
aofFrequency?: AofFrequency;
/**
* Sets the frequency at which a snapshot of the database is created. Possible values include:
* '1h', '6h', '12h'
*/
rdbFrequency?: RdbFrequency;
}
/**
* Specifies configuration of a redis module
* @summary Module settings
*/
export interface Module {
/**
* The name of the module, e.g. 'RedisBloom', 'RediSearch', 'RedisTimeSeries'
*/
name: string;
/**
* Configuration options for the module, e.g. 'ERROR_RATE 0.00 INITIAL_SIZE 400'.
*/
args?: string;
/**
* The version of the module, e.g. '1.0'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly version?: string;
}
/**
* The resource model definition for a Azure Resource Manager proxy resource. It will not have tags
* and a location
* @summary Proxy Resource
*/
export interface ProxyResource extends Resource {
}
/**
* Describes a database on the RedisEnterprise cluster
*/
export interface Database extends ProxyResource {
/**
* Specifies whether redis clients can connect using TLS-encrypted or plaintext redis protocols.
* Default is TLS-encrypted. Possible values include: 'Encrypted', 'Plaintext'
*/
clientProtocol?: Protocol;
/**
* TCP port of the database endpoint. Specified at create time. Defaults to an available port.
*/
port?: number;
/**
* Current provisioning status of the database. Possible values include: 'Succeeded', 'Failed',
* 'Canceled', 'Creating', 'Updating', 'Deleting'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: ProvisioningState;
/**
* Current resource status of the database. Possible values include: 'Running', 'Creating',
* 'CreateFailed', 'Updating', 'UpdateFailed', 'Deleting', 'DeleteFailed', 'Enabling',
* 'EnableFailed', 'Disabling', 'DisableFailed', 'Disabled'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceState?: ResourceState;
/**
* Clustering policy - default is OSSCluster. Specified at create time. Possible values include:
* 'EnterpriseCluster', 'OSSCluster'
*/
clusteringPolicy?: ClusteringPolicy;
/**
* Redis eviction policy - default is VolatileLRU. Possible values include: 'AllKeysLFU',
* 'AllKeysLRU', 'AllKeysRandom', 'VolatileLRU', 'VolatileLFU', 'VolatileTTL', 'VolatileRandom',
* 'NoEviction'
*/
evictionPolicy?: EvictionPolicy;
/**
* Persistence settings
*/
persistence?: Persistence;
/**
* Optional set of redis modules to enable in this database - modules can only be added at
* creation time.
*/
modules?: Module[];
}
/**
* A partial update to the RedisEnterprise database
*/
export interface DatabaseUpdate {
/**
* Specifies whether redis clients can connect using TLS-encrypted or plaintext redis protocols.
* Default is TLS-encrypted. Possible values include: 'Encrypted', 'Plaintext'
*/
clientProtocol?: Protocol;
/**
* TCP port of the database endpoint. Specified at create time. Defaults to an available port.
*/
port?: number;
/**
* Current provisioning status of the database. Possible values include: 'Succeeded', 'Failed',
* 'Canceled', 'Creating', 'Updating', 'Deleting'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: ProvisioningState;
/**
* Current resource status of the database. Possible values include: 'Running', 'Creating',
* 'CreateFailed', 'Updating', 'UpdateFailed', 'Deleting', 'DeleteFailed', 'Enabling',
* 'EnableFailed', 'Disabling', 'DisableFailed', 'Disabled'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceState?: ResourceState;
/**
* Clustering policy - default is OSSCluster. Specified at create time. Possible values include:
* 'EnterpriseCluster', 'OSSCluster'
*/
clusteringPolicy?: ClusteringPolicy;
/**
* Redis eviction policy - default is VolatileLRU. Possible values include: 'AllKeysLFU',
* 'AllKeysLRU', 'AllKeysRandom', 'VolatileLRU', 'VolatileLFU', 'VolatileTTL', 'VolatileRandom',
* 'NoEviction'
*/
evictionPolicy?: EvictionPolicy;
/**
* Persistence settings
*/
persistence?: Persistence;
/**
* Optional set of redis modules to enable in this database - modules can only be added at
* creation time.
*/
modules?: Module[];
}
/**
* The secret access keys used for authenticating connections to redis
* @summary Access keys
*/
export interface AccessKeys {
/**
* The current primary key that clients can use to authenticate
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryKey?: string;
/**
* The current secondary key that clients can use to authenticate
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryKey?: string;
}
/**
* Specifies which access keys to reset to a new random value.
* @summary Regenerate access keys request
*/
export interface RegenerateKeyParameters {
/**
* Which access key to regenerate. Possible values include: 'Primary', 'Secondary'
*/
keyType: AccessKeyType;
}
/**
* Parameters for a Redis Enterprise import operation.
* @summary Import an RDB file into a target database
*/
export interface ImportClusterParameters {
/**
* SAS URI for the target blob to import from
*/
sasUri: string;
}
/**
* Parameters for a Redis Enterprise export operation.
* @summary Export an RDB file into a target database
*/
export interface ExportClusterParameters {
/**
* SAS URI for the target directory to export to
*/
sasUri: string;
}
/**
* The resource management error additional info.
*/
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* The additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly info?: any;
}
/**
* The error detail.
*/
export interface ErrorDetail {
/**
* The error code.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* The error message.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* The error target.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly target?: string;
/**
* The error details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly details?: ErrorDetail[];
/**
* The error additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/**
* Common error response for all Azure Resource Manager APIs to return error details for failed
* operations. (This also follows the OData error response format.).
* @summary Error response
*/
export interface ErrorResponse {
/**
* The error object.
*/
error?: ErrorDetail;
}
/**
* The status of a long-running operation.
*/
export interface OperationStatus {
/**
* The operation's unique id.
*/
id?: string;
/**
* The operation's name.
*/
name?: string;
/**
* The start time of the operation.
*/
startTime?: string;
/**
* The end time of the operation.
*/
endTime?: string;
/**
* The current status of the operation.
*/
status?: string;
/**
* Error response describing why the operation failed.
*/
error?: ErrorResponse;
}
/**
* The resource model definition for an Azure Resource Manager resource with an etag.
* @summary Entity Resource
*/
export interface AzureEntityResource extends Resource {
/**
* Resource Etag.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* A private link resource
*/
export interface PrivateLinkResource extends Resource {
/**
* The private link resource group id.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly groupId?: string;
/**
* The private link resource required member names.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly requiredMembers?: string[];
/**
* The private link resource Private link DNS zone name.
*/
requiredZoneNames?: string[];
}
/**
* Localized display information for this particular operation.
*/
export interface OperationDisplay {
/**
* The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring
* Insights" or "Microsoft Compute".
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: string;
/**
* The localized friendly name of the resource type related to this operation. E.g. "Virtual
* Machines" or "Job Schedule Collections".
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resource?: string;
/**
* The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create
* or Update Virtual Machine", "Restart Virtual Machine".
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly operation?: string;
/**
* The short, localized friendly description of the operation; suitable for tool tips and
* detailed views.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly description?: string;
}
/**
* Details of a REST API operation, returned from the Resource Provider Operations API
* @summary REST API Operation
*/
export interface Operation {
/**
* The name of the operation, as per Resource-Based Access Control (RBAC). Examples:
* "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Whether the operation applies to data-plane. This is "true" for data-plane operations and
* "false" for ARM/control-plane operations.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isDataAction?: boolean;
/**
* Localized display information for this particular operation.
*/
display?: OperationDisplay;
/**
* The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit
* logs UX. Default value is "user,system". Possible values include: 'user', 'system',
* 'user,system'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly origin?: Origin;
/**
* Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.
* Possible values include: 'Internal'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly actionType?: ActionType;
}
/**
* An interface representing RedisEnterpriseManagementClientOptions.
*/
export interface RedisEnterpriseManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* A list of REST API operations supported by an Azure Resource Provider. It contains an URL link
* to get the next set of results.
* @extends Array<Operation>
*/
export interface OperationListResult extends Array<Operation> {
/**
* URL to get the next set of operation list results (if there are any).
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* The response of a list-all operation.
* @extends Array<Cluster>
*/
export interface ClusterList extends Array<Cluster> {
/**
* The URI to fetch the next page of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* The response of a list-all operation.
* @extends Array<Database>
*/
export interface DatabaseList extends Array<Database> {
/**
* The URI to fetch the next page of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* List of private endpoint connection associated with the specified storage account
* @extends Array<PrivateEndpointConnection>
*/
export interface PrivateEndpointConnectionListResult extends Array<PrivateEndpointConnection> {
}
/**
* @interface
* A list of private link resources
* @extends Array<PrivateLinkResource>
*/
export interface PrivateLinkResourceListResult extends Array<PrivateLinkResource> {
}
/**
* Defines values for SkuName.
* Possible values include: 'Enterprise_E10', 'Enterprise_E20', 'Enterprise_E50',
* 'Enterprise_E100', 'EnterpriseFlash_F300', 'EnterpriseFlash_F700', 'EnterpriseFlash_F1500'
* @readonly
* @enum {string}
*/
export type SkuName = 'Enterprise_E10' | 'Enterprise_E20' | 'Enterprise_E50' | 'Enterprise_E100' | 'EnterpriseFlash_F300' | 'EnterpriseFlash_F700' | 'EnterpriseFlash_F1500';
/**
* Defines values for ProvisioningState.
* Possible values include: 'Succeeded', 'Failed', 'Canceled', 'Creating', 'Updating', 'Deleting'
* @readonly
* @enum {string}
*/
export type ProvisioningState = 'Succeeded' | 'Failed' | 'Canceled' | 'Creating' | 'Updating' | 'Deleting';
/**
* Defines values for ResourceState.
* Possible values include: 'Running', 'Creating', 'CreateFailed', 'Updating', 'UpdateFailed',
* 'Deleting', 'DeleteFailed', 'Enabling', 'EnableFailed', 'Disabling', 'DisableFailed', 'Disabled'
* @readonly
* @enum {string}
*/
export type ResourceState = 'Running' | 'Creating' | 'CreateFailed' | 'Updating' | 'UpdateFailed' | 'Deleting' | 'DeleteFailed' | 'Enabling' | 'EnableFailed' | 'Disabling' | 'DisableFailed' | 'Disabled';
/**
* Defines values for TlsVersion.
* Possible values include: '1.0', '1.1', '1.2'
* @readonly
* @enum {string}
*/
export type TlsVersion = '1.0' | '1.1' | '1.2';
/**
* Defines values for PrivateEndpointServiceConnectionStatus.
* Possible values include: 'Pending', 'Approved', 'Rejected'
* @readonly
* @enum {string}
*/
export type PrivateEndpointServiceConnectionStatus = 'Pending' | 'Approved' | 'Rejected';
/**
* Defines values for PrivateEndpointConnectionProvisioningState.
* Possible values include: 'Succeeded', 'Creating', 'Deleting', 'Failed'
* @readonly
* @enum {string}
*/
export type PrivateEndpointConnectionProvisioningState = 'Succeeded' | 'Creating' | 'Deleting' | 'Failed';
/**
* Defines values for Protocol.
* Possible values include: 'Encrypted', 'Plaintext'
* @readonly
* @enum {string}
*/
export type Protocol = 'Encrypted' | 'Plaintext';
/**
* Defines values for ClusteringPolicy.
* Possible values include: 'EnterpriseCluster', 'OSSCluster'
* @readonly
* @enum {string}
*/
export type ClusteringPolicy = 'EnterpriseCluster' | 'OSSCluster';
/**
* Defines values for EvictionPolicy.
* Possible values include: 'AllKeysLFU', 'AllKeysLRU', 'AllKeysRandom', 'VolatileLRU',
* 'VolatileLFU', 'VolatileTTL', 'VolatileRandom', 'NoEviction'
* @readonly
* @enum {string}
*/
export type EvictionPolicy = 'AllKeysLFU' | 'AllKeysLRU' | 'AllKeysRandom' | 'VolatileLRU' | 'VolatileLFU' | 'VolatileTTL' | 'VolatileRandom' | 'NoEviction';
/**
* Defines values for AofFrequency.
* Possible values include: '1s', 'always'
* @readonly
* @enum {string}
*/
export type AofFrequency = '1s' | 'always';
/**
* Defines values for RdbFrequency.
* Possible values include: '1h', '6h', '12h'
* @readonly
* @enum {string}
*/
export type RdbFrequency = '1h' | '6h' | '12h';
/**
* Defines values for AccessKeyType.
* Possible values include: 'Primary', 'Secondary'
* @readonly
* @enum {string}
*/
export type AccessKeyType = 'Primary' | 'Secondary';
/**
* Defines values for Origin.
* Possible values include: 'user', 'system', 'user,system'
* @readonly
* @enum {string}
*/
export type Origin = 'user' | 'system' | 'user,system';
/**
* Defines values for ActionType.
* Possible values include: 'Internal'
* @readonly
* @enum {string}
*/
export type ActionType = 'Internal';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type OperationsStatusGetResponse = OperationStatus & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationStatus;
};
};
/**
* Contains response data for the create operation.
*/
export type RedisEnterpriseCreateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the update operation.
*/
export type RedisEnterpriseUpdateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the get operation.
*/
export type RedisEnterpriseGetResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type RedisEnterpriseListByResourceGroupResponse = ClusterList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ClusterList;
};
};
/**
* Contains response data for the list operation.
*/
export type RedisEnterpriseListResponse = ClusterList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ClusterList;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type RedisEnterpriseBeginCreateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type RedisEnterpriseBeginUpdateResponse = Cluster & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Cluster;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type RedisEnterpriseListByResourceGroupNextResponse = ClusterList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ClusterList;
};
};
/**
* Contains response data for the listNext operation.
*/
export type RedisEnterpriseListNextResponse = ClusterList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ClusterList;
};
};
/**
* Contains response data for the listByCluster operation.
*/
export type DatabasesListByClusterResponse = DatabaseList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DatabaseList;
};
};
/**
* Contains response data for the create operation.
*/
export type DatabasesCreateResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the update operation.
*/
export type DatabasesUpdateResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the get operation.
*/
export type DatabasesGetResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the listKeys operation.
*/
export type DatabasesListKeysResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the regenerateKey operation.
*/
export type DatabasesRegenerateKeyResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type DatabasesBeginCreateResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type DatabasesBeginUpdateResponse = Database & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Database;
};
};
/**
* Contains response data for the beginRegenerateKey operation.
*/
export type DatabasesBeginRegenerateKeyResponse = AccessKeys & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessKeys;
};
};
/**
* Contains response data for the listByClusterNext operation.
*/
export type DatabasesListByClusterNextResponse = DatabaseList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: DatabaseList;
};
};
/**
* Contains response data for the list operation.
*/
export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnectionListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnection;
};
};
/**
* Contains response data for the put operation.
*/
export type PrivateEndpointConnectionsPutResponse = PrivateEndpointConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnection;
};
};
/**
* Contains response data for the beginPut operation.
*/
export type PrivateEndpointConnectionsBeginPutResponse = PrivateEndpointConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateEndpointConnection;
};
};
/**
* Contains response data for the listByCluster operation.
*/
export type PrivateLinkResourcesListByClusterResponse = PrivateLinkResourceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PrivateLinkResourceListResult;
};
}; | the_stack |
export type RequestParams = ApiKeyParams | PremiumPlanParams;
export interface ApiKeyParams {
/**
* You must include an API key with every API request. We strongly recommend that you restrict your API key.
* Restrictions provide added security and help ensure only authorized requests are made with your API key.
*
* There are two restrictions. You should set both:
*
* Application restriction: Limits usage of the API key to either websites (HTTP referrers),
* web servers (IP addresses), or mobile apps (Android apps or iOS apps). You can select only one
* restriction from this category, based on the platform of the API or SDK (see GMP APIs by Platform).
*
* API restriction: Limits usage of the API key to one or more APIs or SDKs. Requests to an API or SDK
* associated with the API key will be processed. Requests to an API or SDK not associated with the API
* key will fail.
*/
key: string;
}
/**
* The Google Maps Platform Premium Plan is no longer available for sign up or new customers. This option is
* only provided for maintaining existing legacy applications that use client IDs. For new applications,
* please use API keys.
* @deprecated
*/
export interface PremiumPlanParams {
/** project client ID */
client_id: string;
/** project URL signing secret. Used to create the request signature */
client_secret: string;
}
export interface ResponseData {
/** contains metadata on the request. See Status Codes below. */
status: Status;
/**
* When the top-level status code is other than `OK`, this field contains more detailed information
* about the reasons behind the given status code.
*/
error_message: string;
/** may contain a set of attributions about this listing which must be displayed to the user (some listings may not have attribution). */
html_attributions?: string[];
/**
* contains a token that can be used to return up to 20 additional results.
* A `next_page_token` will not be returned if there are no additional results to display.
* The maximum number of results that can be returned is 60.
* There is a short delay between when a `next_page_token` is issued, and when it will become valid.
*/
next_page_token?: string;
}
export enum Status {
/** indicates the response contains a valid result. */
OK = "OK",
/** indicates that the provided request was invalid. */
INVALID_REQUEST = "INVALID_REQUEST",
/**
* indicates that too many `waypoints` were provided in the request. For applications using the Directions API as a web service,
* or the [directions service in the Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/directions),
* the maximum allowed number of `waypoints` is 23, plus the origin and destination.
*/
MAX_WAYPOINTS_EXCEEDED = "MAX_WAYPOINTS_EXCEEDED",
/**
* indicates the requested route is too long and cannot be processed.
* This error occurs when more complex directions are returned.
* Try reducing the number of waypoints, turns, or instructions.
*/
MAX_ROUTE_LENGTH_EXCEEDED = "MAX_ROUTE_LENGTH_EXCEEDED",
/**
* indicates any of the following:
* - The API key is missing or invalid.
* - Billing has not been enabled on your account.
* - A self-imposed usage cap has been exceeded.
* - The provided method of payment is no longer valid (for example, a credit card has expired).
* See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this.
*/
OVER_DAILY_LIMIT = "OVER_DAILY_LIMIT",
/** indicates the service has received too many requests from your application within the allowed time period. */
OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT",
/** indicates that the service denied use of the Distance Matrix service by your application. */
REQUEST_DENIED = "REQUEST_DENIED",
/** indicates a Distance Matrix request could not be processed due to a server error. The request may succeed if you try again. */
UNKNOWN_ERROR = "UNKNOWN_ERROR",
/** indicates that the request was successful but returned no results. */
ZERO_RESULTS = "ZERO_RESULTS",
/** indicates that the referenced location (place_id) was not found in the Places database. */
NOT_FOUND = "NOT_FOUND",
}
export interface PlacePhoto {
/** a string used to identify the photo when you perform a Photo request. */
photo_reference: string;
/** the maximum height of the image. */
height: number;
/** the maximum width of the image. */
width: number;
/** contains any required attributions. This field will always be present, but may be empty. */
html_attributions: string[];
}
export enum PlaceIdScope {
/**
* The place ID is recognised by your application only.
* This is because your application added the place, and the place has not yet passed the moderation process.
*/
APP = "APP",
/** The place ID is available to other applications and on Google Maps. */
GOOGLE = "GOOGLE",
}
export interface AlternativePlaceId {
/**
* The most likely reason for a place to have an alternative place ID is if your application adds a place and receives
* an application-scoped place ID, then later receives a Google-scoped place ID after passing the moderation process.
*/
place_id: string;
/**
* The scope of an alternative place ID will always be `APP`,
* indicating that the alternative place ID is recognised by your application only.
*/
scope: "APP";
}
export enum PlaceInputType {
textQuery = "textquery",
phoneNumber = "phonenumber",
}
/**
* Table 1: Types supported in place search and addition
*
* You can use the following values in the types filter for place searches and when adding a place.
*
* @see https://developers.google.com/places/web-service/supported_types#table1
*/
export enum PlaceType1 {
accounting = "accounting",
/** indicates an airport. */
airport = "airport",
amusement_park = "amusement_park",
aquarium = "aquarium",
art_gallery = "art_gallery",
atm = "atm",
bakery = "bakery",
bank = "bank",
bar = "bar",
beauty_salon = "beauty_salon",
bicycle_store = "bicycle_store",
book_store = "book_store",
bowling_alley = "bowling_alley",
bus_station = "bus_station",
cafe = "cafe",
campground = "campground",
car_dealer = "car_dealer",
car_rental = "car_rental",
car_repair = "car_repair",
car_wash = "car_wash",
casino = "casino",
cemetery = "cemetery",
church = "church",
city_hall = "city_hall",
clothing_store = "clothing_store",
convenience_store = "convenience_store",
courthouse = "courthouse",
dentist = "dentist",
department_store = "department_store",
doctor = "doctor",
electrician = "electrician",
electronics_store = "electronics_store",
embassy = "embassy",
fire_station = "fire_station",
florist = "florist",
funeral_home = "funeral_home",
furniture_store = "furniture_store",
gas_station = "gas_station",
gym = "gym",
hair_care = "hair_care",
hardware_store = "hardware_store",
hindu_temple = "hindu_temple",
home_goods_store = "home_goods_store",
hospital = "hospital",
insurance_agency = "insurance_agency",
jewelry_store = "jewelry_store",
laundry = "laundry",
lawyer = "lawyer",
library = "library",
liquor_store = "liquor_store",
local_government_office = "local_government_office",
locksmith = "locksmith",
lodging = "lodging",
meal_delivery = "meal_delivery",
meal_takeaway = "meal_takeaway",
mosque = "mosque",
movie_rental = "movie_rental",
movie_theater = "movie_theater",
moving_company = "moving_company",
museum = "museum",
night_club = "night_club",
painter = "painter",
/** indicates a named park. */
park = "park",
parking = "parking",
pet_store = "pet_store",
pharmacy = "pharmacy",
physiotherapist = "physiotherapist",
plumber = "plumber",
police = "police",
post_office = "post_office",
real_estate_agency = "real_estate_agency",
restaurant = "restaurant",
roofing_contractor = "roofing_contractor",
rv_park = "rv_park",
school = "school",
secondary_school = "secondary_school",
shoe_store = "shoe_store",
shopping_mall = "shopping_mall",
spa = "spa",
stadium = "stadium",
storage = "storage",
store = "store",
subway_station = "subway_station",
supermarket = "supermarket",
synagogue = "synagogue",
taxi_stand = "taxi_stand",
tourist_attraction = "tourist_attraction",
train_station = "train_station",
transit_station = "transit_station",
travel_agency = "travel_agency",
veterinary_care = "veterinary_care",
zoo = "zoo",
}
/**
* Table 2: Additional types returned by the Places service
*
* The following types may be returned in the results of a place search, in addition to the types in table 1 above.
* For more details on these types, refer to [Address Types](https://developers.google.com/maps/documentation/geocoding/intro#Types)
* in Geocoding Responses.
*
* @see https://developers.google.com/places/web-service/supported_types#table2
*/
export enum PlaceType2 {
/**
* indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states.
* Not all nations exhibit these administrative levels. In most cases, `administrative_area_level_1` short names will closely match
* ISO 3166-2 subdivisions and other widely circulated lists; however this is not guaranteed as our geocoding results are based
* on a variety of signals and location data.
*/
administrative_area_level_1 = "administrative_area_level_1",
/**
* indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties.
* Not all nations exhibit these administrative levels.
*/
administrative_area_level_2 = "administrative_area_level_2",
/**
* indicates a third-order civil entity below the country level. This type indicates a minor civil division.
* Not all nations exhibit these administrative levels.
*/
administrative_area_level_3 = "administrative_area_level_3",
/**
* indicates a fourth-order civil entity below the country level. This type indicates a minor civil division.
* Not all nations exhibit these administrative levels.
*/
administrative_area_level_4 = "administrative_area_level_4",
/**
* indicates a fifth-order civil entity below the country level. This type indicates a minor civil division.
* Not all nations exhibit these administrative levels.
*/
administrative_area_level_5 = "administrative_area_level_5",
archipelago = "archipelago",
/** indicates a commonly-used alternative name for the entity. */
colloquial_area = "colloquial_area",
continent = "continent",
/** indicates the national political entity, and is typically the highest order type returned by the Geocoder. */
country = "country",
establishment = "establishment",
finance = "finance",
floor = "floor",
food = "food",
general_contractor = "general_contractor",
geocode = "geocode",
health = "health",
/** indicates a major intersection, usually of two major roads. */
intersection = "intersection",
landmark = "landmark",
/** indicates an incorporated city or town political entity. */
locality = "locality",
/** indicates a prominent natural feature. */
natural_feature = "natural_feature",
/** indicates a named neighborhood */
neighborhood = "neighborhood",
place_of_worship = "place_of_worship",
plus_code = "plus_code",
point_of_interest = "point_of_interest",
/** indicates a political entity. Usually, this type indicates a polygon of some civil administration. */
political = "political",
post_box = "post_box",
/** indicates a postal code as used to address postal mail within the country. */
postal_code = "postal_code",
postal_code_prefix = "postal_code_prefix",
postal_code_suffix = "postal_code_suffix",
postal_town = "postal_town",
/** indicates a named location, usually a building or collection of buildings with a common name */
premise = "premise",
room = "room",
/** indicates a named route (such as "US 101"). */
route = "route",
street_address = "street_address",
street_number = "street_number",
/**
* indicates a first-order civil entity below a locality. For some locations may receive one of the additional types:
* `sublocality_level_1` to `sublocality_level_5`. Each sublocality level is a civil entity. Larger numbers indicate a smaller
* geographic area.
*/
sublocality = "sublocality",
sublocality_level_1 = "sublocality_level_1",
sublocality_level_2 = "sublocality_level_2",
sublocality_level_3 = "sublocality_level_3",
sublocality_level_4 = "sublocality_level_4",
sublocality_level_5 = "sublocality_level_5",
/**
* indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a
* common name.
*/
subpremise = "subpremise",
town_square = "town_square",
}
export interface PlaceReview {
/**
* contains a collection of `AspectRating` objects, each of which provides a rating of a single attribute of the establishment.
* The first object in the collection is considered the primary aspect.
*/
aspects: AspectRating[];
/** the name of the user who submitted the review. Anonymous reviews are attributed to "A Google user". */
author_name: string;
/** the URL to the user's Google Maps Local Guides profile, if available. */
author_url?: string;
/**
* an IETF language code indicating the language used in the user's review.
* This field contains the main language tag only, and not the secondary tag indicating country or region.
* For example, all the English reviews are tagged as 'en', and not 'en-AU' or 'en-UK' and so on.
*/
language: string;
/** the URL to the user's profile photo, if available. */
profile_photo_url: string;
/** the user's overall rating for this place. This is a whole number, ranging from 1 to 5. */
rating: number;
/* The time since review in relative terms, for example '7 months ago' */
relative_time_description: string;
/**
* the user's review. When reviewing a location with Google Places, text reviews are considered optional.
* Therefore, this field may by empty. Note that this field may include simple HTML markup.
* For example, the entity reference `&` may represent an ampersand character.
*/
text: string;
/** the time that the review was submitted, measured in the number of seconds since since midnight, January 1, 1970 UTC. */
time: string;
}
export interface AspectRating {
/** the name of the aspect that is being rated. */
type: AspectRatingType;
/** the user's rating for this particular aspect, from 0 to 3. */
rating: number;
}
export enum AspectRatingType {
appeal = "appeal",
atmosphere = "atmosphere",
decor = "decor",
facilities = "facilities",
food = "food",
overall = "overall",
quality = "quality",
service = "service",
}
export type Place = Partial<PlaceData>;
export interface PlaceData {
/**
* is an array containing the separate components applicable to this address.
*
* Note the following facts about the `address_components[]` array:
* - The array of address components may contain more components than the `formatted_address`.
* - The array does not necessarily include all the political entities that contain an address,
* apart from those included in the `formatted_address`. To retrieve all the political entities
* that contain a specific address, you should use reverse geocoding, passing the latitude/longitude
* of the address as a parameter to the request.
* - The format of the response is not guaranteed to remain the same between requests.
* In particular, the number of `address_components` varies based on the address requested
* and can change over time for the same address. A component can change position in the array.
* The type of the component can change. A particular component may be missing in a later response.
*/
address_components: AddressComponent[];
/**
* is a string containing the human-readable address of this place.
*
* Often this address is equivalent to the postal address. Note that some countries, such as the United Kingdom,
* do not allow distribution of true postal addresses due to licensing restrictions.
*
* The formatted address is logically composed of one or more address components.
* For example, the address "111 8th Avenue, New York, NY" consists of the following components: "111"
* (the street number), "8th Avenue" (the route), "New York" (the city) and "NY" (the US state).
*
* Do not parse the formatted address programmatically. Instead you should use the individual address components,
* which the API response includes in addition to the formatted address field.
*/
formatted_address: string;
/**
* contains the place's phone number in its local format.
* For example, the `formatted_phone_number` for Google's Sydney, Australia office is `(02) 9374 4000`.
*/
formatted_phone_number: string;
/** is a representation of the place's address in the [adr microformat](http://microformats.org/wiki/adr). */
adr_address: string;
/**
* contains the following information:
* - `location`: contains the geocoded latitude,longitude value for this place.
* - `viewport`: contains the preferred viewport when displaying this place on a map as a `LatLngBounds` if it is known.
*/
geometry: AddressGeometry;
/**
* is an encoded location reference, derived from latitude and longitude coordinates, that represents an area:
* 1/8000th of a degree by 1/8000th of a degree (about 14m x 14m at the equator) or smaller.
* Plus codes can be used as a replacement for street addresses in places where they do not exist
* (where buildings are not numbered or streets are not named).
*
* The plus code is formatted as a global code and a compound code:
* - `global_code` is a 4 character area code and 6 character or longer local code (849VCWC8+R9).
* - `compound_code` is a 6 character or longer local code with an explicit location (CWC8+R9, Mountain View, CA, USA).
*
* Typically, both the global code and compound code are returned.
* However, if the result is in a remote location (for example, an ocean or desert) only the global code may be returned.
*
* @see [Open Location Code](https://en.wikipedia.org/wiki/Open_Location_Code)
* @see [plus codes](https://plus.codes/)
*/
plus_code: PlusCode;
/** contains the URL of a suggested icon which may be displayed to the user when indicating this result on a map. */
icon: string;
/**
* The default HEX color code for the place's category.
* @see https://developers.google.com/maps/documentation/places/web-service/icons
*/
icon_background_color: string;
/**
* The base URL for a non-colored icon, minus the file type extension (append `.svg` or `.png`).
* @see https://developers.google.com/maps/documentation/places/web-service/icons
*/
icon_mask_base_uri: string;
/**
* contains the place's phone number in international format.
* International format includes the country code, and is prefixed with the plus (+) sign.
* For example, the `international_phone_number` for Google's Sydney, Australia office is `+61 2 9374 4000`.
*/
international_phone_number: string;
/**
* contains the human-readable name for the returned result.
* For establishment results, this is usually the canonicalized business name.
*/
name: string;
/** place opening hours. */
opening_hours: OpeningHours;
/**
* is a boolean flag indicating whether the place has permanently shut down (value `true`).
* If the place is not permanently closed, the flag is absent from the response. This field is deprecated in favor of `business_status`.
*/
permanently_closed: boolean;
/**
* is a string indicating the operational status of the place, if it is a business.
*/
business_status: string;
/**
* an array of photo objects, each containing a reference to an image.
* A Place Details request may return up to ten photos.
* More information about place photos and how you can use the images in your application can be found in the Place Photos documentation.
*/
photos: PlacePhoto[];
/**
* A textual identifier that uniquely identifies a place.
* To retrieve information about the place, pass this identifier in the `placeId` field of a Places API request.
*/
place_id: string;
/**
* The price level of the place, on a scale of 0 to 4.
* The exact amount indicated by a specific value will vary from region to region.
*
* Price levels are interpreted as follows:
* - `0`: Free
* - `1`: Inexpensive
* - `2`: Moderate
* - `3`: Expensive
* - `4`: Very Expensive
*/
price_level: number;
/** contains the place's rating, from 1.0 to 5.0, based on aggregated user reviews. */
rating: number;
/** The total number of ratings from users */
user_ratings_total: number;
/**
* a JSON array of up to five reviews. If a `language` parameter was specified in the Place Details request,
* the Places Service will bias the results to prefer reviews written in that language.
*/
reviews: PlaceReview[];
/**
* contains an array of feature types describing the given result.
* XML responses include multiple `<type>` elements if more than one type is assigned to the result.
*/
types: AddressType[];
/**
* contains the URL of the official Google page for this place.
* This will be the Google-owned page that contains the best available information about the place.
* Applications must link to or embed this page on any screen that shows detailed results about the place to the user.
*/
url: string;
/**
* contains the number of minutes this place’s current timezone is offset from UTC.
* For example, for places in Sydney, Australia during daylight saving time this would be 660 (+11 hours from UTC),
* and for places in California outside of daylight saving time this would be -480 (-8 hours from UTC).
*/
utc_offset: number;
/**
* lists a simplified address for the place, including the street name, street number, and locality,
* but not the province/state, postal code, or country. For example, Google's Sydney, Australia office
* has a `vicinity` value of `48 Pirrama Road, Pyrmont`.
*/
vicinity: string;
/** lists the authoritative website for this place, such as a business' homepage. */
website: string;
}
export type LatLngArray = [number, number];
export type LatLngString = string;
export interface LatLngLiteral {
lat: number;
lng: number;
}
export interface LatLngLiteralVerbose {
latitude: number;
longitude: number;
}
/**
* A latitude, longitude pair. The API methods accept either:
* - a two-item array of [latitude, longitude];
* - a comma-separated string;
* - an object with 'lat', 'lng' properties; or
* - an object with 'latitude', 'longitude' properties.
*/
export type LatLng =
| LatLngArray
| LatLngString
| LatLngLiteral
| LatLngLiteralVerbose;
/** The bounds parameter defines the latitude/longitude coordinates of the southwest and northeast corners of this bounding box. */
export interface LatLngBounds {
northeast: LatLngLiteral;
southwest: LatLngLiteral;
}
/**
* By default the API will attempt to load the most appropriate language based on the users location or browser settings.
* Some APIs allow you to explicitly set a language when you make a request
*
* @see https://developers.google.com/maps/faq#languagesupport
*/
export enum Language {
/** Arabic */
ar = "ar",
/** Belarusian */
be = "be",
/** Bulgarian */
bg = "bg",
/** Bengali */
bn = "bn",
/** Catalan */
ca = "ca",
/** Czech */
cs = "cs",
/** Danish */
da = "da",
/** German */
de = "de",
/** Greek */
el = "el",
/** English */
en = "en",
/** English (Australian) */
en_Au = "en-Au",
/** English (Great Britain) */
en_GB = "en-GB",
/** Spanish */
es = "es",
/** Basque */
eu = "eu",
/** Farsi */
fa = "fa",
/** Finnish */
fi = "fi",
/** Filipino */
fil = "fil",
/** French */
fr = "fr",
/** Galician */
gl = "gl",
/** Gujarati */
gu = "gu",
/** Hindi */
hi = "hi",
/** Croatian */
hr = "hr",
/** Hungarian */
hu = "hu",
/** Indonesian */
id = "id",
/** Italian */
it = "it",
/** Hebrew */
iw = "iw",
/** Japanese */
ja = "ja",
/** Kazakh */
kk = "kk",
/** Kannada */
kn = "kn",
/** Korean */
ko = "ko",
/** Kyrgyz */
ky = "ky",
/** Lithuanian */
lt = "lt",
/** Latvian */
lv = "lv",
/** Macedonian */
mk = "mk",
/** Malayalam */
ml = "ml",
/** Marathi */
mr = "mr",
/** Burmese */
my = "my",
/** Dutch */
nl = "nl",
/** Norwegian */
no = "no",
/** Punjabi */
pa = "pa",
/** Polish */
pl = "pl",
/** Portuguese */
pt = "pt",
/** Portuguese (Brazil) */
pt_BR = "pt-BR",
/** Portuguese (Portugal) */
pt_PT = "pt-PT",
/** Romanian */
ro = "ro",
/** Russian */
ru = "ru",
/** Slovak */
sk = "sk",
/** Slovenian */
sl = "sl",
/** Albanian */
sq = "sq",
/** Serbian */
sr = "sr",
/** Swedish */
sv = "sv",
/** Tamil */
ta = "ta",
/** Telugu */
te = "te",
/** Thai */
th = "th",
/** Tagalog */
tl = "tl",
/** Turkish */
tr = "tr",
/** Ukrainian */
uk = "uk",
/** Uzbek */
uz = "uz",
/** Vietnamese */
vi = "vi",
/** Chinese (Simlified) */
zh_CN = "zh-CN",
/** Chinese (Traditional) */
zh_TW = "zh-TW",
}
/**
* When you calculate directions, you may specify the transportation mode to use.
* By default, directions are calculated as `driving` directions.
*
* **Note:** Both walking and bicycling directions may sometimes not include clear pedestrian or bicycling paths,
* so these directions will return warnings in the returned result which you must display to the user.
*/
export enum TravelMode {
/** (default) indicates standard driving directions using the road network. */
driving = "driving",
/** requests walking directions via pedestrian paths & sidewalks (where available). */
walking = "walking",
/** requests bicycling directions via bicycle paths & preferred streets (where available). */
bicycling = "bicycling",
/**
* requests directions via public transit routes (where available).
* If you set the mode to transit, you can optionally specify either a departure_time or an arrival_time.
* If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time).
* You can also optionally include a transit_mode and/or a transit_routing_preference.
*/
transit = "transit",
}
export enum TravelRestriction {
/** indicates that the calculated route should avoid toll roads/bridges. */
tolls = "tolls",
/** indicates that the calculated route should avoid highways. */
highways = "highways",
/** indicates that the calculated route should avoid ferries. */
ferries = "ferries",
/**
* indicates that the calculated route should avoid indoor steps for walking and transit directions.
* Only requests that include an API key or a Google Maps APIs Premium Plan client ID will receive indoor steps by default.
*/
indoor = "indoor",
}
/**
* Directions results contain text within distance fields that may be displayed to the user to indicate the distance of
* a particular "step" of the route. By default, this text uses the unit system of the origin's country or region.
*/
export enum UnitSystem {
/** specifies usage of the metric system. Textual distances are returned using kilometers and meters. */
metric = "metric",
/** specifies usage of the Imperial (English) system. Textual distances are returned using miles and feet. */
imperial = "imperial",
}
export enum TrafficModel {
/**
* indicates that the returned `duration_in_traffic` should be the best estimate of travel time given what is known about
* both historical traffic conditions and live traffic. Live traffic becomes more important the closer the `departure_time` is to now.
*/
best_guess = "best_guess",
/**
* indicates that the returned `duration_in_traffic` should be longer than the actual travel time on most days,
* though occasional days with particularly bad traffic conditions may exceed this value.
*/
pessimistic = "pessimistic",
/**
* indicates that the returned `duration_in_traffic` should be shorter than the actual travel time on most days,
* though occasional days with particularly good traffic conditions may be faster than this value.
*/
optimistic = "optimistic",
}
export enum TransitMode {
/** indicates that the calculated route should prefer travel by bus. */
bus = "bus",
/** indicates that the calculated route should prefer travel by subway. */
subway = "subway",
/** indicates that the calculated route should prefer travel by train. */
train = "train",
/** indicates that the calculated route should prefer travel by tram and light rail. */
tram = "tram",
/**
* indicates that the calculated route should prefer travel by train, tram, light rail, and subway.
* This is equivalent to `transit_mode=train|tram|subway`
*/
rail = "rail",
}
export enum TransitRoutingPreference {
/** indicates that the calculated route should prefer limited amounts of walking. */
less_walking = "less_walking",
/** indicates that the calculated route should prefer a limited number of transfers. */
fewer_transfers = "fewer_transfers",
}
/**
* The `status` field within the Directions response object contains the status of the request, and may contain debugging information
* to help you track down why the Directions service failed.
*/
export enum DirectionsResponseStatus {
/** indicates the response contains a valid `result`. */
OK = "OK",
/** indicates at least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded. */
NOT_FOUND = "NOT_FOUND",
/** indicates no route could be found between the origin and destination. */
ZERO_RESULTS = "ZERO_RESULTS",
/**
* indicates that too many `waypoints` were provided in the request. For applications using the Directions API as a web service,
* or the [directions service in the Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/directions),
* the maximum allowed number of `waypoints` is 23, plus the origin and destination.
*/
MAX_WAYPOINTS_EXCEEDED = "MAX_WAYPOINTS_EXCEEDED",
/**
* indicates the requested route is too long and cannot be processed.
* This error occurs when more complex directions are returned.
* Try reducing the number of waypoints, turns, or instructions.
*/
MAX_ROUTE_LENGTH_EXCEEDED = "MAX_ROUTE_LENGTH_EXCEEDED",
/** indicates that the provided request was invalid. Common causes of this status include an invalid parameter or parameter value. */
INVALID_REQUEST = "INVALID_REQUEST",
/**
* indicates any of the following:
* - The API key is missing or invalid.
* - Billing has not been enabled on your account.
* - A self-imposed usage cap has been exceeded.
* - The provided method of payment is no longer valid (for example, a credit card has expired).
* See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this.
*/
OVER_DAILY_LIMIT = "OVER_DAILY_LIMIT",
/** indicates the service has received too many requests from your application within the allowed time period. */
OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT",
/** indicates that the service denied use of the directions service by your application. */
REQUEST_DENIED = "REQUEST_DENIED",
/** indicates a directions request could not be processed due to a server error. The request may succeed if you try again. */
UNKNOWN_ERROR = "UNKNOWN_ERROR",
}
/**
* The `status` field within the Directions response object contains the status of the request, and may contain debugging information
* to help you track down why the Directions service failed.
* @deprecated
*/
export enum DirectionsReponseStatus {
/** indicates the response contains a valid `result`. */
OK = "OK",
/** indicates at least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded. */
NOT_FOUND = "NOT_FOUND",
/** indicates no route could be found between the origin and destination. */
ZERO_RESULTS = "ZERO_RESULTS",
/**
* indicates that too many `waypoints` were provided in the request. For applications using the Directions API as a web service,
* or the [directions service in the Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/directions),
* the maximum allowed number of `waypoints` is 23, plus the origin and destination.
*/
MAX_WAYPOINTS_EXCEEDED = "MAX_WAYPOINTS_EXCEEDED",
/**
* indicates the requested route is too long and cannot be processed.
* This error occurs when more complex directions are returned.
* Try reducing the number of waypoints, turns, or instructions.
*/
MAX_ROUTE_LENGTH_EXCEEDED = "MAX_ROUTE_LENGTH_EXCEEDED",
/** indicates that the provided request was invalid. Common causes of this status include an invalid parameter or parameter value. */
INVALID_REQUEST = "INVALID_REQUEST",
/**
* indicates any of the following:
* - The API key is missing or invalid.
* - Billing has not been enabled on your account.
* - A self-imposed usage cap has been exceeded.
* - The provided method of payment is no longer valid (for example, a credit card has expired).
* See the [Maps FAQ](https://developers.google.com/maps/faq#over-limit-key-error) to learn how to fix this.
*/
OVER_DAILY_LIMIT = "OVER_DAILY_LIMIT",
/** indicates the service has received too many requests from your application within the allowed time period. */
OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT",
/** indicates that the service denied use of the directions service by your application. */
REQUEST_DENIED = "REQUEST_DENIED",
/** indicates a directions request could not be processed due to a server error. The request may succeed if you try again. */
UNKNOWN_ERROR = "UNKNOWN_ERROR",
}
/**
* Elements in the `geocoded_waypoints` array correspond, by their zero-based position, to the origin,
* the waypoints in the order they are specified, and the destination.
*/
export interface GeocodedWaypoint {
/** indicates the status code resulting from the geocoding operation. */
geocoder_status: GeocodedWaypointStatus;
/**
* indicates that the geocoder did not return an exact match for the original request, though it was able to match part of the
* requested address. You may wish to examine the original request for misspellings and/or an incomplete address.
*
* Partial matches most often occur for street addresses that do not exist within the locality you pass in the request.
* Partial matches may also be returned when a request matches two or more locations in the same locality.
* For example, "21 Henr St, Bristol, UK" will return a partial match for both Henry Street and Henrietta Street.
* Note that if a request includes a misspelled address component, the geocoding service may suggest an alternative address.
* Suggestions triggered in this way will also be marked as a partial match.
*/
partial_match: boolean;
/** unique identifier that can be used with other Google APIs. */
place_id: string;
/**
* indicates the *address type* of the geocoding result used for calculating directions.
*
* An empty list of types indicates there are no known types for the particular address component, for example, Lieu-dit in France.
*/
types: AddressType[];
}
export enum GeocodedWaypointStatus {
/** indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned. */
OK = "OK",
/**
* indicates that the geocode was successful but returned no results.
* This may occur if the geocoder was passed a non-existent `address`.
*/
ZERO_RESULTS = "ZERO_RESULTS",
}
export const AddressType = Object.assign({}, PlaceType1, PlaceType2);
export type AddressType = PlaceType1 | PlaceType2;
/**
* This route may consist of one or more `legs` depending on whether any waypoints were specified. As well, the route also contains
* copyright and warning information which must be displayed to the user in addition to the routing information.
*/
export interface DirectionsRoute {
/** contains a short textual description for the route, suitable for naming and disambiguating the route from alternatives. */
summary: string;
/**
* contains an array which contains information about a leg of the route, between two locations within the given route.
* A separate leg will be present for each waypoint or destination specified.
* (A route with no waypoints will contain exactly one leg within the `legs` array.)
* Each leg consists of a series of `steps`.
*/
legs: RouteLeg[];
/**
* contains an array indicating the order of any waypoints in the calculated route.
* This waypoints may be reordered if the request was passed `optimize:true` within its `waypoints` parameter.
*/
waypoint_order: number[];
/**
* contains a single `points` object that holds an encoded polyline representation of the route.
* This polyline is an approximate (smoothed) path of the resulting directions.
*/
overview_polyline: {
points: string;
};
/** contains the viewport bounding box of the `overview_polyline`. */
bounds: LatLngBounds;
/** contains the copyrights text to be displayed for this route. You must handle and display this information yourself. */
copyrights: string;
/** contains an array of warnings to be displayed when showing these directions. You must handle and display these warnings yourself. */
warnings: string[];
/**
* If present, contains the total fare (that is, the total ticket costs) on this route.
* This property is only returned for transit requests and only for routes where fare information is available for all transit legs.
*
* **Note:** The Directions API only returns fare information for requests that contain either an API key or a client ID
* and digital signature.
*/
fare: TransitFare;
/**
* An array of LatLngs representing the entire course of this route. The path is simplified in order to make
* it suitable in contexts where a small number of vertices is required (such as Static Maps API URLs).
*/
overview_path: LatLngLiteral[];
}
export interface TransitFare {
/** An [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217) indicating the currency that the amount is expressed in. */
currency: string;
/** The total fare amount, in the currency specified above. */
value: number;
/** The total fare amount, formatted in the requested language. */
text: string;
}
/**
* A single leg of the journey from the origin to the destination in the calculated route.
* For routes that contain no waypoints, the route will consist of a single "leg," but for routes that define one or more waypoints,
* the route will consist of one or more legs, corresponding to the specific legs of the journey.
*/
export interface RouteLeg {
/** contains an array of steps denoting information about each separate step of the leg of the journey. */
steps: DirectionsStep[];
/**
* indicates the total distance covered by this leg, as a field with the following elements.
*
* This field may be absent if the distance is unknown.
*/
distance: Distance;
/**
* indicates the total duration of this leg.
*
* This field may be absent if the duration is unknown.
*/
duration: Duration;
/**
* indicates the total duration of this leg.
* This value is an estimate of the time in traffic based on current and historical traffic conditions.
* See the `traffic_model` request parameter for the options you can use to request that the returned value is optimistic, pessimistic,
* or a best-guess estimate. The duration in traffic is returned only if all of the following are true:
*
* - The request includes a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature.
* - The request does not include stopover waypoints. If the request includes waypoints, they must be prefixed with `via:`
* to avoid stopovers.
* - The request is specifically for driving directions—the `mode` parameter is set to `driving`.
* - The request includes a `departure_time` parameter.
* - Traffic conditions are available for the requested route.
*/
duration_in_traffic?: Duration;
/** contains the estimated time of arrival for this leg. This property is only returned for transit directions. */
arrival_time: Time;
/**
* contains the estimated time of departure for this leg, specified as a `Time` object.
* The `departure_time` is only available for transit directions.
*/
departure_time: Time;
/**
* contains the latitude/longitude coordinates of the origin of this leg.
* Because the Directions API calculates directions between locations by using the nearest transportation option (usually a road)
* at the start and end points, `start_location` may be different than the provided origin of this leg if, for example,
* a road is not near the origin.
*/
start_location: LatLngLiteral;
/**
* contains the latitude/longitude coordinates of the given destination of this leg.
* Because the Directions API calculates directions between locations by using the nearest transportation option (usually a road)
* at the start and end points, `end_location` may be different than the provided destination of this leg if, for example,
* a road is not near the destination.
*/
end_location: LatLngLiteral;
/** contains the human-readable address (typically a street address) resulting from reverse geocoding the `start_location` of this leg. */
start_address: string;
/** contains the human-readable address (typically a street address) from reverse geocoding the `end_location` of this leg. */
end_address: string;
}
/**
* A step is the most atomic unit of a direction's route, containing a single step describing a specific, single instruction on the journey.
* E.g. "Turn left at W. 4th St." The step not only describes the instruction but also contains distance and duration information relating to
* how this step relates to the following step. For example, a step denoted as "Merge onto I-80 West" may contain a duration of
* "37 miles" and "40 minutes," indicating that the next step is 37 miles/40 minutes from this step.
*
* When using the Directions API to search for transit directions, the steps array will include additional transit details in the form of
* a `transit_details` array. If the directions include multiple modes of transportation, detailed directions will be provided for walking or
* driving steps in an inner `steps` array. For example, a walking step will include directions from the start and end locations:
* "Walk to Innes Ave & Fitch St". That step will include detailed walking directions for that route in the inner `steps` array, such as:
* "Head north-west", "Turn left onto Arelious Walker", and "Turn left onto Innes Ave".
*/
export interface DirectionsStep {
/** contains formatted instructions for this step, presented as an HTML text string. */
html_instructions: string;
/**
* contains the distance covered by this step until the next step. (See the discussion of this field in Directions Legs)
*
* This field may be undefined if the distance is unknown.
*/
distance: Distance;
/**
* contains the typical time required to perform the step, until the next step. (See the description in Directions Legs)
*
* This field may be undefined if the duration is unknown
*/
duration: Duration;
/** contains the location of the starting point of this step, as a single set of `lat` and `lng` fields. */
start_location: LatLngLiteral;
/** contains the location of the last point of this step, as a single set of `lat` and `lng` fields. */
end_location: LatLngLiteral;
/**
* contains the action to take for the current step (turn left, merge, straight, etc.).
* This field is used to determine which icon to display.
*/
maneuver: Maneuver;
/**
* contains a single points object that holds an encoded polyline representation of the step.
* This polyline is an approximate (smoothed) path of the step.
*/
polyline: {
points: string;
};
/**
* contains detailed directions for walking or driving steps in transit directions.
* Substeps are only available when `travel_mode` is set to "transit".
* The inner `steps` array is of the same type as `steps`.
*/
steps: DirectionsStep;
/** contains transit specific information. This field is only returned with travel_mode is set to "transit". */
transit_details: TransitDetails;
/** contains the type of travel mode used. */
travel_mode: TravelMode;
}
export interface Distance {
/** indicates the distance in meters. */
value: number;
/**
* contains a human-readable representation of the distance, displayed in units as used at the origin
* (or as overridden within the `units` parameter in the request).
* (For example, miles and feet will be used for any origin within the United States.)
*/
text: string;
}
export interface Duration {
/** indicates the duration in seconds. */
value: number;
/** contains a human-readable representation of the duration. */
text: string;
}
export interface Time {
/** the time specified as a JavaScript `Date` object. */
value: Date;
/** the time specified as a string. The time is displayed in the time zone of the transit stop. */
text: string;
/**
* contains the time zone of this station. The value is the name of the time zone as defined in the
* [IANA Time Zone Database](http://www.iana.org/time-zones), e.g. "America/New_York".
*/
time_zone: string;
}
export enum Maneuver {
turn_slight_left = "turn-slight-left",
turn_sharp_left = "turn-sharp-left",
uturn_left = "uturn-left",
turn_left = "turn-left",
turn_slight_right = "turn-slight-right",
turn_sharp_right = "turn-sharp-right",
uturn_right = "uturn-right",
turn_right = "turn-right",
straight = "straight",
ramp_left = "ramp-left",
ramp_right = "ramp-right",
merge = "merge",
fork_left = "fork-left",
fork_right = "fork-right",
ferry = "ferry",
ferry_train = "ferry-train",
roundabout_left = "roundabout-left",
roundabout_right = "roundabout-right",
}
/**
* Transit directions return additional information that is not relevant for other modes of transportation.
* These additional properties are exposed through the `transit_details` object, returned as a field of an element in the `steps[]` array.
* From the `TransitDetails` object you can access additional information about the transit stop, transit line and transit agency
*/
export interface TransitDetails {
/** contains information about the stop for this part of the trip. */
arrival_stop: TransitStop;
/** contains information about the station for this part of the trip. */
departure_stop: TransitStop;
/** contain the arrival time for this leg of the journey. */
arrival_time: Time;
/** contain the departure time for this leg of the journey. */
departure_time: Time;
/**
* specifies the direction in which to travel on this line, as it is marked on the vehicle or at the departure stop.
* This will often be the terminus station.
*/
headsign: string;
/**
* specifies the expected number of seconds between departures from the same stop at this time.
* For example, with a `headway` value of 600, you would expect a ten minute wait if you should miss your bus.
*/
headway: number;
/**
* contains the number of stops in this step, counting the arrival stop, but not the departure stop.
* For example, if your directions involve leaving from Stop A, passing through stops B and C, and arriving at stop D,
* `num_stops` will return 3.
*/
num_stops: number;
/** contains information about the transit line used in this step. */
line: TransitLine;
}
export interface TransitStop {
/** the name of the transit station/stop. eg. "Union Square". */
name: string;
/** the location of the transit station/stop, represented as a `lat` and `lng` field. */
location: LatLngLiteral;
}
export interface TransitLine {
/** contains the full name of this transit line. eg. "7 Avenue Express". */
name: string;
/** contains the short name of this transit line. This will normally be a line number, such as "M7" or "355". */
short_name: string;
/** contains the color commonly used in signage for this transit line. The color will be specified as a hex string such as: #FF0033. */
color: string;
/**
* is an array containing a single `TransitAgency` object.
* The `TransitAgency` object provides information about the operator of the line
*/
agencies: TransitAgency[];
/** contains the URL for this transit line as provided by the transit agency. */
url: string;
/** contains the URL for the icon associated with this line. */
icon: string;
/** contains the color of text commonly used for signage of this line. The color will be specified as a hex string. */
text_color: string;
/** contains the type of vehicle used on this line. */
vehicle: TransitVehicle;
}
/** You must display the names and URLs of the transit agencies servicing the trip results. */
export interface TransitAgency {
/** contains the name of the transit agency. */
name: string;
/** contains the phone number of the transit agency. */
phone: string;
/** contains the URL for the transit agency. */
url: string;
}
export interface TransitVehicle {
/** contains the name of the vehicle on this line. eg. "Subway.". */
name: string;
/** contains the type of vehicle that runs on this line. */
type: VehicleType;
/** contains the URL for an icon associated with this vehicle type. */
icon: string;
/** contains the URL for the icon associated with this vehicle type, based on the local transport signage. */
local_icon: string;
}
/** @see https://developers.google.com/maps/documentation/directions/intro#VehicleType. */
export enum VehicleType {
/** Rail. */
RAIL = "RAIL",
/** Light rail transit. */
METRO_RAIL = "METRO_RAIL",
/** Underground light rail. */
SUBWAY = "SUBWAY",
/** Above ground light rail. */
TRAM = "TRAM",
/** Monorail. */
MONORAIL = "MONORAIL",
/** Heavy rail. */
HEAVY_RAIL = "HEAVY_RAIL",
/** Commuter rail. */
COMMUTER_TRAIN = "COMMUTER_TRAIN",
/** High speed train. */
HIGH_SPEED_TRAIN = "HIGH_SPEED_TRAIN",
/** Bus. */
BUS = "BUS",
/** Intercity bus. */
INTERCITY_BUS = "INTERCITY_BUS",
/** Trolleybus. */
TROLLEYBUS = "TROLLEYBUS",
/** Share taxi is a kind of bus with the ability to drop off and pick up passengers anywhere on its route. */
SHARE_TAXI = "SHARE_TAXI",
/** Ferry. */
FERRY = "FERRY",
/** A vehicle that operates on a cable, usually on the ground. Aerial cable cars may be of the type `GONDOLA_LIFT`. */
CABLE_CAR = "CABLE_CAR",
/** An aerial cable car. */
GONDOLA_LIFT = "GONDOLA_LIFT",
/**
* A vehicle that is pulled up a steep incline by a cable.
* A Funicular typically consists of two cars, with each car acting as a counterweight for the other.
*/
FUNICULAR = "FUNICULAR",
/** All other vehicles will return this type. */
OTHER = "OTHER",
}
/**
* When the Distance Matrix API returns results, it places them within a JSON `rows` array.
* Even if no results are returned (such as when the origins and/or destinations don't exist), it still returns an empty array.
* XML responses consist of zero or more `<row>` elements.
*
* Rows are ordered according to the values in the `origin` parameter of the request.
* Each row corresponds to an origin, and each `element` within that row corresponds to a pairing of the origin with a `destination` value.
*
* Each `row` array contains one or more `element` entries, which in turn contain the information about a single origin-destination pairing.
*/
export interface DistanceMatrixRow {
elements: DistanceMatrixRowElement[];
}
/** The information about each origin-destination pairing is returned in an `element` entry. */
export interface DistanceMatrixRowElement {
/** possible status codes */
status: Status;
/**
* The length of time it takes to travel this route, expressed in seconds (the `value` field) and as `text`.
* The textual representation is localized according to the query's `language` parameter.
*/
duration: Duration;
/**
* The length of time it takes to travel this route, based on current and historical traffic conditions.
* See the `traffic_model` request parameter for the options you can use to request that the returned value is
* `optimistic`, `pessimistic`, or a `best-guess` estimate. The duration is expressed in seconds (the `value` field) and as `text`.
* The textual representation is localized according to the query's `language` parameter.
* The duration in traffic is returned only if all of the following are true:
* - The request includes a `departure_time` parameter.
* - The request includes a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature.
* - Traffic conditions are available for the requested route.
* - The `mode` parameter is set to `driving`.
*/
duration_in_traffic: Duration;
/**
* The total distance of this route, expressed in meters (`value`) and as `text`.
* The textual value uses the `unit` system specified with the unit parameter of the original request, or the origin's region.
*/
distance: Distance;
/**
* If present, contains the total fare (that is, the total ticket costs) on this route.
* This property is only returned for transit requests and only for transit providers where fare information is available.
*/
fare: TransitFare;
}
export interface OpeningHours {
/** is a boolean value indicating if the place is open at the current time. */
open_now: boolean;
/** is an array of opening periods covering seven days, starting from Sunday, in chronological order. */
periods: OpeningPeriod[];
/**
* is an array of seven strings representing the formatted opening hours for each day of the week.
* If a `language` parameter was specified in the Place Details request, the Places Service will format
* and localize the opening hours appropriately for that language. The ordering of the elements in this array
* depends on the `language` parameter. Some languages start the week on Monday while others start on Sunday.
*/
weekday_text: string[];
}
export interface OpeningPeriod {
/** contains a pair of day and time objects describing when the place opens. */
open: OpeningHoursTime;
/**
* may contain a pair of day and time objects describing when the place closes.
* **Note:** If a place is **always open**, the `close` section will be missing from the response.
* Clients can rely on always-open being represented as an `open` period containing `day` with value 0
* and `time` with value 0000, and no `close`.
*/
close?: OpeningHoursTime;
}
export interface OpeningHoursTime {
/** a number from 0–6, corresponding to the days of the week, starting on Sunday. For example, 2 means Tuesday. */
day: number;
/**
* may contain a time of day in 24-hour hhmm format. Values are in the range 0000–2359. The `time`
* will be reported in the place's time zone.
*/
time?: string;
}
export interface GeocodeResult {
/**
* array indicates the type of the returned result.
* This array contains a set of zero or more tags identifying the type of feature returned in the result.
* For example, a geocode of "Chicago" returns "locality" which indicates that "Chicago" is a city,
* and also returns "political" which indicates it is a political entity.
*/
types: AddressType[];
/**
* is a string containing the human-readable address of this location.
*
* Often this address is equivalent to the postal address. Note that some countries, such as the United Kingdom,
* do not allow distribution of true postal addresses due to licensing restrictions.
*
* The formatted address is logically composed of one or more address components.
* For example, the address "111 8th Avenue, New York, NY" consists of the following components: "111" (the street number),
* "8th Avenue" (the route), "New York" (the city) and "NY" (the US state).
*
* Do not parse the formatted address programmatically. Instead you should use the individual address components,
* which the API response includes in addition to the formatted address field.
*/
formatted_address: string;
/**
* is an array containing the separate components applicable to this address.
*
* Note the following facts about the `address_components[]` array:
* - The array of address components may contain more components than the `formatted_address`.
* - The array does not necessarily include all the political entities that contain an address,
* apart from those included in the `formatted_address`. To retrieve all the political entities that contain a specific address,
* you should use reverse geocoding, passing the latitude/longitude of the address as a parameter to the request.
* - The format of the response is not guaranteed to remain the same between requests.
* In particular, the number of `address_components` varies based on the address requested and can change
* over time for the same address. A component can change position in the array.
* The type of the component can change. A particular component may be missing in a later response.
*/
address_components: AddressComponent[];
/**
* is an array denoting all the localities contained in a postal code.
* This is only present when the result is a postal code that contains multiple localities.
*/
postcode_localities: string[];
/** address geometry. */
geometry: AddressGeometry;
/**
* is an encoded location reference, derived from latitude and longitude coordinates,
* that represents an area: 1/8000th of a degree by 1/8000th of a degree (about 14m x 14m at the equator) or smaller.
* Plus codes can be used as a replacement for street addresses in places where they do not exist
* (where buildings are not numbered or streets are not named).
*
* The plus code is formatted as a global code and a compound code:
* - `global_code` is a 4 character area code and 6 character or longer local code (849VCWC8+R9).
* - `compound_code` is a 6 character or longer local code with an explicit location (CWC8+R9, Mountain View, CA, USA).
* Typically, both the global code and compound code are returned. However, if the result is in a remote location
* (for example, an ocean or desert) only the global code may be returned.
*
* @see [Open Location Code](https://en.wikipedia.org/wiki/Open_Location_Code)
* @see [plus codes](https://plus.codes/)
*/
plus_code: PlusCode;
/**
* indicates that the geocoder did not return an exact match for the original request,
* though it was able to match part of the requested address.
* You may wish to examine the original request for misspellings and/or an incomplete address.
*
* Partial matches most often occur for street addresses that do not exist within the locality you pass in the request.
* Partial matches may also be returned when a request matches two or more locations in the same locality.
* For example, "21 Henr St, Bristol, UK" will return a partial match for both Henry Street and Henrietta Street.
* Note that if a request includes a misspelled address component, the geocoding service may suggest an alternative address.
* Suggestions triggered in this way will also be marked as a partial match.
*/
partial_match: boolean;
/** is a unique identifier that can be used with other Google APIs. */
place_id: string;
}
export enum GeocodingAddressComponentType {
/** indicates the floor of a building address. */
floor = "floor",
/** typically indicates a place that has not yet been categorized. */
establishment = "establishment",
/** indicates a named point of interest. */
point_of_interest = "point_of_interest",
/** indicates a parking lot or parking structure. */
parking = "parking",
/** indicates a specific postal box. */
post_box = "post_box",
/** indicates a grouping of geographic areas, such as locality and sublocality, used for mailing addresses in some countries. */
postal_town = "postal_town",
/** indicates the room of a building address. */
room = "room",
/** indicates the precise street number. */
street_number = "street_number",
/** indicate the location of a bus. */
bus_station = "bus_station",
/** indicate the location of a train. */
train_station = "train_station",
/** indicate the location of a public transit stop. */
transit_station = "transit_station",
}
export interface AddressComponent {
/** is an array indicating the *type* of the address component. */
types: Array<AddressType | GeocodingAddressComponentType>;
/** is the full text description or name of the address component as returned by the Geocoder. */
long_name: string;
/**
* is an abbreviated textual name for the address component, if available.
* For example, an address component for the state of Alaska may have a `long_name` of "Alaska" and a `short_name` of "AK"
* using the 2-letter postal abbreviation.
*/
short_name: string;
}
export interface AddressGeometry {
/** contains the geocoded latitude, longitude value. For normal address lookups, this field is typically the most important. */
location: LatLngLiteral;
/** stores additional data about the specified location. */
location_type: LocationType;
/**
* contains the recommended viewport for displaying the returned result, specified as two latitude, longitude values
* defining the `southwest` and `northeast` corner of the viewport bounding box.
* Generally the viewport is used to frame a result when displaying it to a user.
*/
viewport: LatLngBounds;
/**
* (optionally returned) stores the bounding box which can fully contain the returned result.
* Note that these bounds may not match the recommended viewport.
* (For example, San Francisco includes the [Farallon islands](https://en.wikipedia.org/wiki/Farallon_Islands),
* which are technically part of the city, but probably should not be returned in the viewport.)
*/
bounds: LatLngBounds;
}
export enum LocationType {
/**
* indicates that the returned result is a precise geocode for which we have location information
* accurate down to street address precision
*/
ROOFTOP = "ROOFTOP",
/**
* indicates that the returned result reflects an approximation (usually on a road) interpolated between two precise points
* (such as intersections). Interpolated results are generally returned when rooftop geocodes are unavailable for a street address.
*/
RANGE_INTERPOLATED = "RANGE_INTERPOLATED",
/**
* indicates that the returned result is the geometric center of a result such as a polyline
* (for example, a street) or polygon (region).
*/
GEOMETRIC_CENTER = "GEOMETRIC_CENTER",
/** indicates that the returned result is approximate. */
APPROXIMATE = "APPROXIMATE",
}
export interface PlusCode {
/** is a 4 character area code and 6 character or longer local code (849VCWC8+R9). */
global_code: string;
/** is a 6 character or longer local code with an explicit location (CWC8+R9, Mountain View, CA, USA). */
compound_code: string;
}
export enum RadioType {
lte = "lte",
gsm = "gsm",
cdma = "cdma",
wcdma = "wcdma",
}
export interface CellTower {
/**
* Unique identifier of the cell.
* On GSM, this is the Cell ID (CID);
* CDMA networks use the Base Station ID (BID).
* WCDMA networks use the UTRAN/GERAN Cell Identity (UC-Id), which is a 32-bit value concatenating the Radio Network Controller (RNC)
* and Cell ID. Specifying only the 16-bit Cell ID value in WCDMA networks may return inaccurate results.
*/
cellId: number;
/** The Location Area Code (LAC) for GSM and WCDMA networks. The Network ID (NID) for CDMA networks. */
locationAreaCode: number;
/** The cell tower's Mobile Country Code (MCC). */
mobileCountryCode: number;
/** The cell tower's Mobile Network Code. This is the MNC for GSM and WCDMA; CDMA uses the System ID (SID). */
mobileNetworkCode: number;
/** The number of milliseconds since this cell was primary. If age is 0, the `cellId` represents a current measurement. */
age?: number;
/** Radio signal strength measured in dBm. */
signalStrength?: number;
/** The [timing advance](https://en.wikipedia.org/wiki/Timing_advance) value. */
timingAdvance?: number;
}
export interface WifiAccessPoint {
/** The MAC address of the WiFi node. It's typically called a BSS, BSSID or MAC address. Separators must be `:` (colon). */
macAddress: string;
/** The current signal strength measured in dBm. */
signalStrength?: number;
/** The number of milliseconds since this access point was detected. */
age?: number;
/** The channel over which the client is communicating with the acces. */
channel?: number;
/** The current signal to noise ratio measured in dB. */
signalToNoiseRatio?: number;
}
export interface PredictionTerm {
/** containing the text of the term. */
value: string;
/** start position of this term in the description, measured in Unicode characters. */
offset: number;
}
export interface PredictionSubstring {
/** location of the entered term. */
offset: number;
/** length of the entered term. */
length: number;
}
export interface StructuredFormatting {
/** contains the main text of a prediction, usually the name of the place. */
main_text: string;
/**
* contains an array with `offset` value and `length`. These describe the location of
* the entered term in the prediction result text, so that the term can be highlighted if desired.
*/
main_text_matched_substrings: PredictionSubstring[];
/** contains the secondary text of a prediction, usually the location of the place. */
secondary_text: string;
/**
* contains an array with `offset` value and `length`. These describe the location of
* the entered term in the prediction result secondary text, so that the term can be highlighted if desired.
*/
secondary_text_matched_substrings: PredictionSubstring[];
}
export interface SnappedPoint {
/** Contains a `latitude` and `longitude` value. */
location: LatLngLiteralVerbose;
/**
* An integer that indicates the corresponding value in the original request.
* Each point in the request maps to at most two segmentsin the response:
* - If there are no nearby roads, no segment is returned.
* - If the nearest road is one-way, one segment is returned.
* - If the nearest road is bidirectional, two segments are returned.
*/
originalIndex: number;
/**
* A unique identifier for a place. All place IDs returned by the Roads API correspond to road segments.
* Place IDs can be used with other Google APIs, including the Places SDK and the Maps JavaScript API.
* For example, if you need to get road names for the snapped points returned by the Roads API,
* you can pass the `placeId` to the Places SDK or the Geocoding API. Within the Roads API,
* you can pass the `placeId` in a speed limits request to determine the speed limit along that road segment.
*/
placeId: string;
} | the_stack |
import { Action, action, Thunk, thunk, Computed, computed } from "easy-peasy";
import { IStoreModel } from "./index";
import { IStoreInjections } from "./store";
import { lnrpc } from "../../proto/lightning";
import { getItemObject, StorageItem, setItemObject, getItem } from "../storage/app";
import { toast, timeout, stringToUint8Array } from "../utils";
import { Chain } from "../utils/build";
import logger from "./../utils/log";
const log = logger("Lightning");
export type LndChainBackend = "neutrino" | "bitcoindWithZmq";
interface ILightningPeer {
peer: lnrpc.Peer;
node?: lnrpc.LightningNode;
}
interface ISetLightningPeersPayload {
peer: lnrpc.IPeer;
node?: lnrpc.ILightningNode;
}
export interface ILightningModel {
initialize: Thunk<ILightningModel, { start: Date }, IStoreInjections, IStoreModel>;
setupStores: Thunk<ILightningModel, void, IStoreInjections, IStoreModel>;
getInfo: Thunk<ILightningModel, void, IStoreInjections>;
waitForChainSync: Thunk<ILightningModel, void, IStoreInjections>;
waitForGraphSync: Thunk<ILightningModel, void, IStoreInjections>;
checkRecoverInfo: Thunk<ILightningModel, void, IStoreInjections, IStoreModel, Promise<void>>;
setupAutopilot: Thunk<ILightningModel, boolean, IStoreInjections>;
getLightningPeers: Thunk<ILightningModel, void, IStoreInjections>;
connectPeer: Thunk<ILightningModel, string, IStoreInjections>;
disconnectPeer: Thunk<ILightningModel, string, IStoreInjections>;
signMessage: Thunk<ILightningModel, string, IStoreInjections, {}, Promise<lnrpc.SignMessageResponse>>;
setNodeInfo: Action<ILightningModel, lnrpc.IGetInfoResponse>;
setRPCServerReady: Action<ILightningModel, boolean>;
setReady: Action<ILightningModel, boolean>;
setInitializeDone: Action<ILightningModel, boolean>;
setSyncedToChain: Action<ILightningModel, boolean>;
setSyncedToGraph: Action<ILightningModel, boolean>;
setRecoverInfo: Action<ILightningModel, lnrpc.GetRecoveryInfoResponse>;
setFirstSync: Action<ILightningModel, boolean>;
setAutopilotSet: Action<ILightningModel, boolean>;
setLightningPeers: Action<ILightningModel, ISetLightningPeersPayload[]>
setBestBlockheight: Action<ILightningModel, number>;
nodeInfo?: lnrpc.IGetInfoResponse;
rpcReady: boolean;
syncedToChain: Computed<ILightningModel, boolean>;
syncedToGraph: Computed<ILightningModel, boolean>;
recoverInfo: lnrpc.GetRecoveryInfoResponse;
isRecoverMode: Computed<ILightningModel, boolean>;
ready: boolean;
initializeDone: boolean;
firstSync: boolean;
autopilotSet?: boolean;
lightningPeers: ILightningPeer[];
bestBlockheight?: number;
initialKnownBlockheight?: number;
}
export const lightning: ILightningModel = {
initialize: thunk(async (actions, { start }, { getState, getStoreState }) => {
log.d("getState().ready: " + getState().ready);
if (getState().ready) {
log.d("Lightning store already started");
return;
}
log.i("Starting");
const lastSync = await getItemObject<number>(StorageItem.timeSinceLastSync);
const firstSync = await getItemObject<boolean>(StorageItem.firstSync);
actions.setFirstSync(firstSync);
const debugShowStartupInfo = getStoreState().settings.debugShowStartupInfo;
const fastInit = true; // differenceInDays(start, lastSync) <3 || firstSync;
if (fastInit) {
actions.setReady(true);
}
actions.setRPCServerReady(true);
(async () => {
try {
actions.setupStores();
actions.checkRecoverInfo()
.then(() => debugShowStartupInfo && toast("checkRecoverInfo time: " + (new Date().getTime() - start.getTime()) / 1000 + "s"))
.catch((error) => toast("checkRecoverInfo error: " + error.message, undefined, "danger"));
await actions.waitForChainSync();
debugShowStartupInfo && toast("syncedToChain time: " + (new Date().getTime() - start.getTime()) / 1000 + "s");
await actions.setupAutopilot(getStoreState().settings.autopilotEnabled);
await actions.waitForGraphSync();
debugShowStartupInfo && toast("syncedToGraph time: " + (new Date().getTime() - start.getTime()) / 1000 + "s");
actions.setInitializeDone(true);
} catch (e) {
debugShowStartupInfo && toast("Error in initialization task: " + e.message, 10000, "danger");
return;
}
})();
(async () => {
try {
// tslint:disable-next-line: no-floating-promises
const result = await fetch(Chain === "mainnet"
? "https://mempool.space/api/blocks/tip/height"
: "https://mempool.space/testnet/api/blocks/tip/height"
);
if (result.ok) {
const bestBlockHeight = await result.text();
actions.setBestBlockheight(Number.parseInt(bestBlockHeight, 10));
} else {
log.e("Unable to get best block height from mempool.space");
}
} catch (e) {
debugShowStartupInfo && toast(e.message, 10000, "danger");
return;
}
})();
return true;
}),
setupStores: thunk(async (_, _2, { dispatch }) => {
try {
await Promise.all([
dispatch.channel.initialize(),
dispatch.receive.initialize(),
dispatch.onChain.initialize(),
dispatch.transaction.checkOpenTransactions(),
dispatch.scheduledSync.initialize(),
]);
await dispatch.notificationManager.initialize();
await dispatch.clipboardManager.initialize();
await dispatch.deeplinkManager.initialize();
await dispatch.blixtLsp.initialize();
} catch (e) {
toast(e.message, 0, "danger", "OK");
return;
}
}),
setupAutopilot: thunk(async (actions, enabled, { injections }) => {
log.i("Setting up Autopilot");
const modifyStatus = injections.lndMobile.autopilot.modifyStatus;
const status = injections.lndMobile.autopilot.status;
if (enabled) {
try {
await timeout(5000);
const scores = await getNodeScores();
// console.log(scores);
const setScores = injections.lndMobile.autopilot.setScores;
await setScores(scores);
} catch (e) {
log.e("Autopilot fail", [e]);
}
}
do {
try {
await modifyStatus(enabled);
actions.setAutopilotSet(enabled);
log.i("Autopilot status:", [await status()]);
break;
} catch (e) {
log.e("Error modifying Autopilot: " + e.message);
await timeout(2000);
}
} while (true);
}),
getLightningPeers: thunk(async (actions, _, { injections }) => {
const listPeers = injections.lndMobile.index.listPeers;
const getNodeInfo = injections.lndMobile.index.getNodeInfo;
const response = await listPeers();
const lightningPeers = await Promise.all(response.peers.map(async (ipeer) => {
let nodeInfo = undefined;
try {
nodeInfo = await getNodeInfo(ipeer.pubKey ?? "");
} catch(e) { console.log(e) }
return {
peer: ipeer,
node: nodeInfo?.node ?? undefined,
}
}));
const sortedPeers = lightningPeers.sort((lightningNode, lightningNode2) => {
if (lightningNode.peer.pubKey! < lightningNode2.peer.pubKey!) {
return -1;
} else if (lightningNode.peer.pubKey! > lightningNode2.peer.pubKey!){
return 1;
}
return 0;
});
actions.setLightningPeers(sortedPeers);
}),
connectPeer: thunk(async (_, peer, { injections }) => {
const connectPeer = injections.lndMobile.index.connectPeer;
const [pubkey, host] = peer.split("@");
return await connectPeer(pubkey, host);
}),
disconnectPeer: thunk(async (_, pubkey, { injections }) => {
const disconnectPeer = injections.lndMobile.index.disconnectPeer;
return await disconnectPeer(pubkey);
}),
signMessage: thunk(async (_, message, { injections }) => {
const signMessageNodePubkey = injections.lndMobile.wallet.signMessageNodePubkey;
return await signMessageNodePubkey(stringToUint8Array(message));
}),
getInfo: thunk(async (actions, _, { injections }) => {
const { getInfo } = injections.lndMobile.index;
const info = await getInfo();
actions.setNodeInfo(info);
}),
checkRecoverInfo: thunk((async (actions, _, { getState, injections }) => {
while (true) {
try {
const info = await injections.lndMobile.index.getRecoveryInfo();
log.i("Recovery info", [info, info.recoveryMode, info.recoveryFinished, info.progress]);
actions.setRecoverInfo(info);
if (!info.recoveryMode || info.recoveryFinished) {
log.i("Recovery either finished or not activated");
break;
}
} catch (e) {
log.e("checkRecoverInfo: " + e.message);
}
await timeout(10000);
}
})),
waitForChainSync: thunk(async (actions, _, { getState, injections }) => {
const getInfo = injections.lndMobile.index.getInfo;
const firstSync = getState().firstSync;
let info;
do {
info = await getInfo();
log.d(`blockHeight: ${info.blockHeight}, syncedToChain: ${info.syncedToChain}`);
actions.setNodeInfo(info);
if (info.syncedToChain !== true) {
await timeout(firstSync ? 6000 : 1000);
}
else {
log.d(JSON.stringify(info));
}
} while (!info.syncedToChain);
if (firstSync) {
await setItemObject(StorageItem.firstSync, false);
actions.setFirstSync(false);
// Connect to a lightning node
// to get the network graph ASAP
// in case DNS bootstrap fails
setTimeout(async () => {
try {
const nodes = [
["030c3f19d742ca294a55c00376b3b355c3c90d61c6b6b39554dbc7ac19b141c14f", "52.50.244.44:9735"], // Bitrefill
["03c2abfa93eacec04721c019644584424aab2ba4dff3ac9bdab4e9c97007491dda", "157.245.68.47:9735"], // tippin.me
["03abf6f44c355dec0d5aa155bdbdd6e0c8fefe318eff402de65c6eb2e1be55dc3e", "18.221.23.28:9735"], // OpenNode
["02004c625d622245606a1ea2c1c69cfb4516b703b47945a3647713c05fe4aaeb1c", "172.81.178.151:9735"], // WalletOfSatoshi.com [2]
["02e7c42ae2952d7a71398e23535b53ffc60deb269acbc7c10307e6b797b91b1e79", "87.121.37.156:9735"], // PeerName.com
["03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f", "34.239.230.56:9735"], // ACINQ
];
const randomNode = nodes[Math.floor(Math.random() * nodes.length)];
log.i(`Connecting to ${randomNode[0]}@${randomNode[1]} to get LN network graph`);
await injections.lndMobile.index.connectPeer(randomNode[0], randomNode[1]);
} catch (e) {
log.e("Connecting to node for channel graph failed in waitForChainSync firstSync=true", [e]);
}
}, 1000);
}
actions.setReady(true);
actions.setSyncedToChain(info.syncedToChain);
await setItemObject(StorageItem.timeSinceLastSync, new Date().getTime());
}),
waitForGraphSync: thunk(async (actions, _, { getState, injections }) => {
log.d("Start waiting for graph sync");
const { getInfo } = injections.lndMobile.index;
let info;
do {
info = await getInfo();
log.d(`syncedToGraph: ${info.syncedToGraph}`);
actions.setNodeInfo(info);
if (info.syncedToGraph !== true) {
await timeout(1100);
}
} while (!info.syncedToGraph);
actions.setSyncedToGraph(info.syncedToGraph);
if (info.syncedToChain === false) {
log.i("waitForGraphSync: syncedToChain flipped to false again, calling waitForChainSync");
actions.waitForChainSync();
}
}),
setNodeInfo: action((state, payload) => {
state.nodeInfo = payload;
if (state.initialKnownBlockheight === undefined) {
state.initialKnownBlockheight = payload.blockHeight ?? 0;
}
}),
setRPCServerReady: action((state, payload) => { state.rpcReady = payload; }),
setReady: action((state, payload) => { state.ready = payload; }),
setInitializeDone: action((state, payload) => { state.initializeDone = payload; }),
setSyncedToChain: action((state, payload) => { state.syncedToChain = payload; }),
setSyncedToGraph: action((state, payload) => { state.syncedToGraph = payload; }),
setRecoverInfo: action((state, payload) => { state.recoverInfo = payload }),
setFirstSync: action((state, payload) => { state.firstSync = payload; }),
setAutopilotSet: action((state, payload) => { state.autopilotSet = payload; }),
setLightningPeers: action((state, payload) => {
state.lightningPeers = payload.map((p) => ({
peer: lnrpc.Peer.create(p.peer),
node: lnrpc.LightningNode.create(p.node),
}));
}),
setBestBlockheight: action((state, payload) => { state.bestBlockheight = payload; }),
rpcReady: false,
ready: false,
initializeDone: false,
syncedToChain: computed((state) => (state.nodeInfo?.syncedToChain) ?? false),
syncedToGraph: computed((state) => (state.nodeInfo?.syncedToGraph) ?? false),
isRecoverMode: computed((state) => state.recoverInfo.recoveryMode),
recoverInfo: lnrpc.GetRecoveryInfoResponse.create({
progress: 0,
recoveryFinished: false,
recoveryMode: false,
}),
firstSync: false,
bestBlockheight: undefined,
lightningPeers: [],
};
const getNodeScores = async () => {
if (Chain === "testnet") {
return { "036b7130b27a23d6fe1d55c1d3bed9e6da5a17090588b0834e8200e0d50ee6886a": 1 };
} else if (Chain === "mainnet") {
return { "0230a5bca558e6741460c13dd34e636da28e52afd91cf93db87ed1b0392a7466eb": 1 };
}
// TODO(hsjoberg): needs cleanup
const url = Chain === "mainnet"
? "https://nodes.lightning.computer/availability/v1/btc.json"
: "https://nodes.lightning.computer/availability/v1/btctestnet.json";
const response = await fetch(url);
const json = await response.json();
const scores = json.scores.reduce((map, { public_key, score }) => {
if (typeof public_key !== 'string' || !Number.isInteger(score)) {
throw new Error('Invalid node score format!');
}
map[public_key] = score / 100000000.0;
return map;
}, {});
return scores;
} | the_stack |
import jsx from "@babel/plugin-syntax-jsx";
import { declare } from "@babel/helper-plugin-utils";
import { types as t } from "@babel/core";
import type { PluginPass } from "@babel/core";
import type { NodePath, Visitor } from "@babel/traverse";
import { addNamed, addNamespace, isModule } from "@babel/helper-module-imports";
import annotateAsPure from "@babel/helper-annotate-as-pure";
import type {
ArrowFunctionExpression,
CallExpression,
Class,
Expression,
FunctionParent,
Identifier,
JSXAttribute,
JSXElement,
JSXFragment,
JSXOpeningElement,
JSXSpreadAttribute,
MemberExpression,
ObjectExpression,
Program,
} from "@babel/types";
type Diff<T, U> = T extends U ? never : T;
const DEFAULT = {
importSource: "react",
runtime: "automatic",
pragma: "React.createElement",
pragmaFrag: "React.Fragment",
};
const JSX_SOURCE_ANNOTATION_REGEX =
/^\s*\*?\s*@jsxImportSource\s+([^\s]+)\s*$/m;
const JSX_RUNTIME_ANNOTATION_REGEX = /^\s*\*?\s*@jsxRuntime\s+([^\s]+)\s*$/m;
const JSX_ANNOTATION_REGEX = /^\s*\*?\s*@jsx\s+([^\s]+)\s*$/m;
const JSX_FRAG_ANNOTATION_REGEX = /^\s*\*?\s*@jsxFrag\s+([^\s]+)\s*$/m;
const get = (pass: PluginPass, name: string) =>
pass.get(`@babel/plugin-react-jsx/${name}`);
const set = (pass: PluginPass, name: string, v: any) =>
pass.set(`@babel/plugin-react-jsx/${name}`, v);
export default function createPlugin({ name, development }) {
return declare((api, options) => {
const {
pure: PURE_ANNOTATION,
throwIfNamespace = true,
// TODO (Babel 8): It should throw if this option is used with the automatic runtime
filter,
runtime: RUNTIME_DEFAULT = process.env.BABEL_8_BREAKING
? "automatic"
: development
? "automatic"
: "classic",
importSource: IMPORT_SOURCE_DEFAULT = DEFAULT.importSource,
pragma: PRAGMA_DEFAULT = DEFAULT.pragma,
pragmaFrag: PRAGMA_FRAG_DEFAULT = DEFAULT.pragmaFrag,
} = options;
if (process.env.BABEL_8_BREAKING) {
if ("useSpread" in options) {
throw new Error(
'@babel/plugin-transform-react-jsx: Since Babel 8, an inline object with spread elements is always used, and the "useSpread" option is no longer available. Please remove it from your config.',
);
}
if ("useBuiltIns" in options) {
const useBuiltInsFormatted = JSON.stringify(options.useBuiltIns);
throw new Error(
`@babel/plugin-transform-react-jsx: Since "useBuiltIns" is removed in Babel 8, you can remove it from the config.
- Babel 8 now transforms JSX spread to object spread. If you need to transpile object spread with
\`useBuiltIns: ${useBuiltInsFormatted}\`, you can use the following config
{
"plugins": [
"@babel/plugin-transform-react-jsx"
["@babel/plugin-proposal-object-rest-spread", { "loose": true, "useBuiltIns": ${useBuiltInsFormatted} }]
]
}`,
);
}
} else {
// eslint-disable-next-line no-var
var { useSpread = false, useBuiltIns = false } = options;
if (RUNTIME_DEFAULT === "classic") {
if (typeof useSpread !== "boolean") {
throw new Error(
"transform-react-jsx currently only accepts a boolean option for " +
"useSpread (defaults to false)",
);
}
if (typeof useBuiltIns !== "boolean") {
throw new Error(
"transform-react-jsx currently only accepts a boolean option for " +
"useBuiltIns (defaults to false)",
);
}
if (useSpread && useBuiltIns) {
throw new Error(
"transform-react-jsx currently only accepts useBuiltIns or useSpread " +
"but not both",
);
}
}
}
const injectMetaPropertiesVisitor: Visitor<PluginPass> = {
JSXOpeningElement(path, state) {
const attributes = [];
if (isThisAllowed(path)) {
attributes.push(
t.jsxAttribute(
t.jsxIdentifier("__self"),
t.jsxExpressionContainer(t.thisExpression()),
),
);
}
attributes.push(
t.jsxAttribute(
t.jsxIdentifier("__source"),
t.jsxExpressionContainer(makeSource(path, state)),
),
);
path.pushContainer("attributes", attributes);
},
};
return {
name,
inherits: jsx,
visitor: {
JSXNamespacedName(path) {
if (throwIfNamespace) {
throw path.buildCodeFrameError(
`Namespace tags are not supported by default. React's JSX doesn't support namespace tags. \
You can set \`throwIfNamespace: false\` to bypass this warning.`,
);
}
},
JSXSpreadChild(path) {
throw path.buildCodeFrameError(
"Spread children are not supported in React.",
);
},
Program: {
enter(path, state) {
const { file } = state;
let runtime: string = RUNTIME_DEFAULT;
let source: string = IMPORT_SOURCE_DEFAULT;
let pragma: string = PRAGMA_DEFAULT;
let pragmaFrag: string = PRAGMA_FRAG_DEFAULT;
let sourceSet = !!options.importSource;
let pragmaSet = !!options.pragma;
let pragmaFragSet = !!options.pragmaFrag;
if (file.ast.comments) {
for (const comment of file.ast.comments) {
const sourceMatches = JSX_SOURCE_ANNOTATION_REGEX.exec(
comment.value,
);
if (sourceMatches) {
source = sourceMatches[1];
sourceSet = true;
}
const runtimeMatches = JSX_RUNTIME_ANNOTATION_REGEX.exec(
comment.value,
);
if (runtimeMatches) {
runtime = runtimeMatches[1];
}
const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
if (jsxMatches) {
pragma = jsxMatches[1];
pragmaSet = true;
}
const jsxFragMatches = JSX_FRAG_ANNOTATION_REGEX.exec(
comment.value,
);
if (jsxFragMatches) {
pragmaFrag = jsxFragMatches[1];
pragmaFragSet = true;
}
}
}
set(state, "runtime", runtime);
if (runtime === "classic") {
if (sourceSet) {
throw path.buildCodeFrameError(
`importSource cannot be set when runtime is classic.`,
);
}
const createElement = toMemberExpression(pragma);
const fragment = toMemberExpression(pragmaFrag);
set(state, "id/createElement", () => t.cloneNode(createElement));
set(state, "id/fragment", () => t.cloneNode(fragment));
set(state, "defaultPure", pragma === DEFAULT.pragma);
} else if (runtime === "automatic") {
if (pragmaSet || pragmaFragSet) {
throw path.buildCodeFrameError(
`pragma and pragmaFrag cannot be set when runtime is automatic.`,
);
}
const define = (name: string, id: string) =>
set(state, name, createImportLazily(state, path, id, source));
define("id/jsx", development ? "jsxDEV" : "jsx");
define("id/jsxs", development ? "jsxDEV" : "jsxs");
define("id/createElement", "createElement");
define("id/fragment", "Fragment");
set(state, "defaultPure", source === DEFAULT.importSource);
} else {
throw path.buildCodeFrameError(
`Runtime must be either "classic" or "automatic".`,
);
}
if (development) {
path.traverse(injectMetaPropertiesVisitor, state);
}
},
// TODO (Babel 8): Decide if this should be removed or brought back.
// see: https://github.com/babel/babel/pull/12253#discussion_r513086528
//
// exit(path, state) {
// if (
// get(state, "runtime") === "classic" &&
// get(state, "pragmaSet") &&
// get(state, "usedFragment") &&
// !get(state, "pragmaFragSet")
// ) {
// throw new Error(
// "transform-react-jsx: pragma has been set but " +
// "pragmaFrag has not been set",
// );
// }
// },
},
JSXElement: {
exit(path, file) {
let callExpr;
if (
get(file, "runtime") === "classic" ||
shouldUseCreateElement(path)
) {
callExpr = buildCreateElementCall(path, file);
} else {
callExpr = buildJSXElementCall(path, file);
}
path.replaceWith(t.inherits(callExpr, path.node));
},
},
JSXFragment: {
exit(path, file) {
let callExpr;
if (get(file, "runtime") === "classic") {
callExpr = buildCreateElementFragmentCall(path, file);
} else {
callExpr = buildJSXFragmentCall(path, file);
}
path.replaceWith(t.inherits(callExpr, path.node));
},
},
JSXAttribute(path) {
if (t.isJSXElement(path.node.value)) {
path.node.value = t.jsxExpressionContainer(path.node.value);
}
},
} as Visitor<PluginPass>,
};
// Finds the closest parent function that provides `this`. Specifically, this looks for
// the first parent function that isn't an arrow function.
//
// Derived from `Scope#getFunctionParent`
function getThisFunctionParent(
path: NodePath,
): NodePath<Diff<FunctionParent, ArrowFunctionExpression>> | null {
let scope = path.scope;
do {
if (
scope.path.isFunctionParent() &&
!scope.path.isArrowFunctionExpression()
) {
// @ts-expect-error ts can not infer scope.path is Diff<FunctionParent, ArrowFunctionExpression>
return scope.path;
}
} while ((scope = scope.parent));
return null;
}
// Returns whether the class has specified a superclass.
function isDerivedClass(classPath: NodePath<Class>) {
return classPath.node.superClass !== null;
}
// Returns whether `this` is allowed at given path.
function isThisAllowed(path: NodePath<JSXOpeningElement>) {
// This specifically skips arrow functions as they do not rewrite `this`.
const parentMethodOrFunction = getThisFunctionParent(path);
if (parentMethodOrFunction === null) {
// We are not in a method or function. It is fine to use `this`.
return true;
}
if (!parentMethodOrFunction.isMethod()) {
// If the closest parent is a regular function, `this` will be rebound, therefore it is fine to use `this`.
return true;
}
// Current node is within a method, so we need to check if the method is a constructor.
if (parentMethodOrFunction.node.kind !== "constructor") {
// We are not in a constructor, therefore it is always fine to use `this`.
return true;
}
// Now we are in a constructor. If it is a derived class, we do not reference `this`.
return !isDerivedClass(
parentMethodOrFunction.parentPath.parentPath as NodePath<Class>,
);
}
function call(
pass: PluginPass,
name: string,
args: CallExpression["arguments"],
) {
const node = t.callExpression(get(pass, `id/${name}`)(), args);
if (PURE_ANNOTATION ?? get(pass, "defaultPure")) annotateAsPure(node);
return node;
}
// We want to use React.createElement, even in the case of
// jsx, for <div {...props} key={key} /> to distinguish it
// from <div key={key} {...props} />. This is an intermediary
// step while we deprecate key spread from props. Afterwards,
// we will stop using createElement in the transform.
function shouldUseCreateElement(path: NodePath<JSXElement>) {
const openingPath = path.get("openingElement");
const attributes = openingPath.node.attributes;
let seenPropsSpread = false;
for (let i = 0; i < attributes.length; i++) {
const attr = attributes[i];
if (
seenPropsSpread &&
t.isJSXAttribute(attr) &&
attr.name.name === "key"
) {
return true;
} else if (t.isJSXSpreadAttribute(attr)) {
seenPropsSpread = true;
}
}
return false;
}
function convertJSXIdentifier(node, parent) {
if (t.isJSXIdentifier(node)) {
if (node.name === "this" && t.isReferenced(node, parent)) {
return t.thisExpression();
} else if (t.isValidIdentifier(node.name, false)) {
// @ts-expect-error todo(flow->ts)
node.type = "Identifier";
} else {
return t.stringLiteral(node.name);
}
} else if (t.isJSXMemberExpression(node)) {
return t.memberExpression(
convertJSXIdentifier(node.object, node),
convertJSXIdentifier(node.property, node),
);
} else if (t.isJSXNamespacedName(node)) {
/**
* If the flag "throwIfNamespace" is false
* print XMLNamespace like string literal
*/
return t.stringLiteral(`${node.namespace.name}:${node.name.name}`);
}
return node;
}
function convertAttributeValue(node) {
if (t.isJSXExpressionContainer(node)) {
return node.expression;
} else {
return node;
}
}
function accumulateAttribute(
array: ObjectExpression["properties"],
attribute: NodePath<JSXAttribute | JSXSpreadAttribute>,
) {
if (t.isJSXSpreadAttribute(attribute.node)) {
const arg = attribute.node.argument;
// Collect properties into props array if spreading object expression
if (t.isObjectExpression(arg)) {
array.push(...arg.properties);
} else {
array.push(t.spreadElement(arg));
}
return array;
}
const value = convertAttributeValue(
attribute.node.name.name !== "key"
? attribute.node.value || t.booleanLiteral(true)
: attribute.node.value,
);
if (attribute.node.name.name === "key" && value === null) {
throw attribute.buildCodeFrameError(
'Please provide an explicit key value. Using "key" as a shorthand for "key={true}" is not allowed.',
);
}
if (
t.isStringLiteral(value) &&
!t.isJSXExpressionContainer(attribute.node.value)
) {
value.value = value.value.replace(/\n\s+/g, " ");
// "raw" JSXText should not be used from a StringLiteral because it needs to be escaped.
delete value.extra?.raw;
}
if (t.isJSXNamespacedName(attribute.node.name)) {
// @ts-expect-error mutating AST
attribute.node.name = t.stringLiteral(
attribute.node.name.namespace.name +
":" +
attribute.node.name.name.name,
);
} else if (t.isValidIdentifier(attribute.node.name.name, false)) {
// @ts-expect-error mutating AST
attribute.node.name.type = "Identifier";
} else {
// @ts-expect-error mutating AST
attribute.node.name = t.stringLiteral(attribute.node.name.name);
}
array.push(
t.inherits(
t.objectProperty(
// @ts-expect-error The attribute.node.name is an Identifier now
attribute.node.name,
value,
),
attribute.node,
),
);
return array;
}
function buildChildrenProperty(children: Expression[]) {
let childrenNode;
if (children.length === 1) {
childrenNode = children[0];
} else if (children.length > 1) {
childrenNode = t.arrayExpression(children);
} else {
return undefined;
}
return t.objectProperty(t.identifier("children"), childrenNode);
}
// Builds JSX into:
// Production: React.jsx(type, arguments, key)
// Development: React.jsxDEV(type, arguments, key, isStaticChildren, source, self)
function buildJSXElementCall(path: NodePath<JSXElement>, file: PluginPass) {
const openingPath = path.get("openingElement");
const args = [getTag(openingPath)];
const attribsArray = [];
const extracted = Object.create(null);
// for React.jsx, key, __source (dev), and __self (dev) is passed in as
// a separate argument rather than in the args object. We go through the
// props and filter out these three keywords so we can pass them in
// as separate arguments later
for (const attr of openingPath.get("attributes")) {
if (attr.isJSXAttribute() && t.isJSXIdentifier(attr.node.name)) {
const { name } = attr.node.name;
switch (name) {
case "__source":
case "__self":
if (extracted[name]) throw sourceSelfError(path, name);
/* falls through */
case "key": {
const keyValue = convertAttributeValue(attr.node.value);
if (keyValue === null) {
throw attr.buildCodeFrameError(
'Please provide an explicit key value. Using "key" as a shorthand for "key={true}" is not allowed.',
);
}
extracted[name] = keyValue;
break;
}
default:
attribsArray.push(attr);
}
} else {
attribsArray.push(attr);
}
}
const children = t.react.buildChildren(path.node);
let attribs: t.ObjectExpression;
if (attribsArray.length || children.length) {
attribs = buildJSXOpeningElementAttributes(
attribsArray,
//@ts-expect-error The children here contains JSXSpreadChild,
// which will be thrown later
children,
);
} else {
// attributes should never be null
attribs = t.objectExpression([]);
}
args.push(attribs);
if (development) {
// isStaticChildren, __source, and __self are only used in development
// automatically include __source and __self in this plugin
// so we can eliminate the need for separate Babel plugins in Babel 8
args.push(
extracted.key ?? path.scope.buildUndefinedNode(),
t.booleanLiteral(children.length > 1),
extracted.__source ?? path.scope.buildUndefinedNode(),
extracted.__self ?? path.scope.buildUndefinedNode(),
);
} else if (extracted.key !== undefined) {
args.push(extracted.key);
}
return call(file, children.length > 1 ? "jsxs" : "jsx", args);
}
// Builds props for React.jsx. This function adds children into the props
// and ensures that props is always an object
function buildJSXOpeningElementAttributes(
attribs: NodePath<JSXAttribute | JSXSpreadAttribute>[],
children: Expression[],
) {
const props = attribs.reduce(accumulateAttribute, []);
// In React.jsx, children is no longer a separate argument, but passed in
// through the argument object
if (children?.length > 0) {
props.push(buildChildrenProperty(children));
}
return t.objectExpression(props);
}
// Builds JSX Fragment <></> into
// Production: React.jsx(type, arguments)
// Development: React.jsxDEV(type, { children })
function buildJSXFragmentCall(
path: NodePath<JSXFragment>,
file: PluginPass,
) {
const args = [get(file, "id/fragment")()];
const children = t.react.buildChildren(path.node);
args.push(
t.objectExpression(
children.length > 0
? [
buildChildrenProperty(
//@ts-expect-error The children here contains JSXSpreadChild,
// which will be thrown later
children,
),
]
: [],
),
);
if (development) {
args.push(
path.scope.buildUndefinedNode(),
t.booleanLiteral(children.length > 1),
);
}
return call(file, children.length > 1 ? "jsxs" : "jsx", args);
}
// Builds JSX Fragment <></> into
// React.createElement(React.Fragment, null, ...children)
function buildCreateElementFragmentCall(
path: NodePath<JSXFragment>,
file: PluginPass,
) {
if (filter && !filter(path.node, file)) return;
return call(file, "createElement", [
get(file, "id/fragment")(),
t.nullLiteral(),
...t.react.buildChildren(path.node),
]);
}
// Builds JSX into:
// Production: React.createElement(type, arguments, children)
// Development: React.createElement(type, arguments, children, source, self)
function buildCreateElementCall(
path: NodePath<JSXElement>,
file: PluginPass,
) {
const openingPath = path.get("openingElement");
return call(file, "createElement", [
getTag(openingPath),
buildCreateElementOpeningElementAttributes(
file,
path,
openingPath.get("attributes"),
),
...t.react.buildChildren(path.node),
]);
}
function getTag(openingPath: NodePath<JSXOpeningElement>) {
const tagExpr = convertJSXIdentifier(
openingPath.node.name,
openingPath.node,
);
let tagName;
if (t.isIdentifier(tagExpr)) {
tagName = tagExpr.name;
} else if (t.isLiteral(tagExpr)) {
// @ts-expect-error todo(flow->ts) value in missing for NullLiteral
tagName = tagExpr.value;
}
if (t.react.isCompatTag(tagName)) {
return t.stringLiteral(tagName);
} else {
return tagExpr;
}
}
/**
* The logic for this is quite terse. It's because we need to
* support spread elements. We loop over all attributes,
* breaking on spreads, we then push a new object containing
* all prior attributes to an array for later processing.
*/
function buildCreateElementOpeningElementAttributes(
file: PluginPass,
path: NodePath<JSXElement>,
attribs: NodePath<JSXAttribute | JSXSpreadAttribute>[],
) {
const runtime = get(file, "runtime");
if (!process.env.BABEL_8_BREAKING) {
if (runtime !== "automatic") {
const objs = [];
const props = attribs.reduce(accumulateAttribute, []);
if (!useSpread) {
// Convert syntax to use multiple objects instead of spread
let start = 0;
props.forEach((prop, i) => {
if (t.isSpreadElement(prop)) {
if (i > start) {
objs.push(t.objectExpression(props.slice(start, i)));
}
objs.push(prop.argument);
start = i + 1;
}
});
if (props.length > start) {
objs.push(t.objectExpression(props.slice(start)));
}
} else if (props.length) {
objs.push(t.objectExpression(props));
}
if (!objs.length) {
return t.nullLiteral();
}
if (objs.length === 1) {
return objs[0];
}
// looks like we have multiple objects
if (!t.isObjectExpression(objs[0])) {
objs.unshift(t.objectExpression([]));
}
const helper = useBuiltIns
? t.memberExpression(t.identifier("Object"), t.identifier("assign"))
: file.addHelper("extends");
// spread it
return t.callExpression(helper, objs);
}
}
const props = [];
const found = Object.create(null);
for (const attr of attribs) {
const name =
t.isJSXAttribute(attr) &&
t.isJSXIdentifier(attr.name) &&
attr.name.name;
if (
runtime === "automatic" &&
(name === "__source" || name === "__self")
) {
if (found[name]) throw sourceSelfError(path, name);
found[name] = true;
}
accumulateAttribute(props, attr);
}
return props.length === 1 && t.isSpreadElement(props[0])
? props[0].argument
: props.length > 0
? t.objectExpression(props)
: t.nullLiteral();
}
});
function getSource(source: string, importName: string) {
switch (importName) {
case "Fragment":
return `${source}/${development ? "jsx-dev-runtime" : "jsx-runtime"}`;
case "jsxDEV":
return `${source}/jsx-dev-runtime`;
case "jsx":
case "jsxs":
return `${source}/jsx-runtime`;
case "createElement":
return source;
}
}
function createImportLazily(
pass: PluginPass,
path: NodePath<Program>,
importName: string,
source: string,
): () => Identifier | MemberExpression {
return () => {
const actualSource = getSource(source, importName);
if (isModule(path)) {
let reference = get(pass, `imports/${importName}`);
if (reference) return t.cloneNode(reference);
reference = addNamed(path, importName, actualSource, {
importedInterop: "uncompiled",
importPosition: "after",
});
set(pass, `imports/${importName}`, reference);
return reference;
} else {
let reference = get(pass, `requires/${actualSource}`);
if (reference) {
reference = t.cloneNode(reference);
} else {
reference = addNamespace(path, actualSource, {
importedInterop: "uncompiled",
});
set(pass, `requires/${actualSource}`, reference);
}
return t.memberExpression(reference, t.identifier(importName));
}
};
}
}
function toMemberExpression(id: string): Identifier | MemberExpression {
return (
id
.split(".")
.map(name => t.identifier(name))
// @ts-expect-error - The Array#reduce does not have a signature
// where the type of initialial value differs from callback return type
.reduce((object, property) => t.memberExpression(object, property))
);
}
function makeSource(path: NodePath, state: PluginPass) {
const location = path.node.loc;
if (!location) {
// the element was generated and doesn't have location information
return path.scope.buildUndefinedNode();
}
// @ts-expect-error todo: avoid mutating PluginPass
if (!state.fileNameIdentifier) {
const { filename = "" } = state;
const fileNameIdentifier = path.scope.generateUidIdentifier("_jsxFileName");
const scope = path.hub.getScope();
if (scope) {
scope.push({
id: fileNameIdentifier,
init: t.stringLiteral(filename),
});
}
// @ts-expect-error todo: avoid mutating PluginPass
state.fileNameIdentifier = fileNameIdentifier;
}
return makeTrace(
t.cloneNode(
// @ts-expect-error todo: avoid mutating PluginPass
state.fileNameIdentifier,
),
location.start.line,
location.start.column,
);
}
function makeTrace(
fileNameIdentifier: Identifier,
lineNumber?: number,
column0Based?: number,
) {
const fileLineLiteral =
lineNumber != null ? t.numericLiteral(lineNumber) : t.nullLiteral();
const fileColumnLiteral =
column0Based != null ? t.numericLiteral(column0Based + 1) : t.nullLiteral();
const fileNameProperty = t.objectProperty(
t.identifier("fileName"),
fileNameIdentifier,
);
const lineNumberProperty = t.objectProperty(
t.identifier("lineNumber"),
fileLineLiteral,
);
const columnNumberProperty = t.objectProperty(
t.identifier("columnNumber"),
fileColumnLiteral,
);
return t.objectExpression([
fileNameProperty,
lineNumberProperty,
columnNumberProperty,
]);
}
function sourceSelfError(path: NodePath, name: string) {
const pluginName = `transform-react-jsx-${name.slice(2)}`;
return path.buildCodeFrameError(
`Duplicate ${name} prop found. You are most likely using the deprecated ${pluginName} Babel plugin. Both __source and __self are automatically set when using the automatic runtime. Please remove transform-react-jsx-source and transform-react-jsx-self from your Babel config.`,
);
} | the_stack |
import { PDFPageProxy } from "pdfjs-dist/types/display/api";
import React from "react";
import { PageModel, Pages } from "../state";
import { BoundingBox } from "../api/types";
import { PDFPageView } from "../types/pdfjs-viewer";
import { Dimensions, Rectangle } from "../types/ui";
/*
* Corresponds to the 'elevation' property of 'Paper' and 'Card' components from Material UI.
* Can take on values of 0 to 24 inclusive. See
* https://material.io/design/environment/elevation.html#elevation-in-material-design
*/
export const TOOLTIP_ELEVATION = 8;
export function getMouseXY(event: React.MouseEvent) {
const rect = event.currentTarget.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
return { x, y };
}
export function isKeypressEscape(event: React.KeyboardEvent | KeyboardEvent) {
if (
event.key !== undefined &&
(event.key === "Esc" || event.key === "Escape")
) {
return true;
}
if (event.keyCode !== undefined && event.keyCode === 27) {
return true;
}
return false;
}
const PATTERN_NON_WORD_CHAR = /\W/;
const PATTERN_WORD_CHAR = /\w/;
const ELLIPSIS = "…";
/**
* Truncates the provided text such that no more than limit characters are rendered and adds an
* ellipsis upon truncation by default. If the text is shorter than the provided limit, the full
* text is returned.
*
* This method was ported from Semantic Scholar's UI codebase. It's a UI
* utility.
*
* @param {string} text The text to truncate.
* @param {number} limit The maximum number of characters to show.
* @param {boolean} withEllipis whether to include an ellipsis after the truncation, defaults to true
*
* @return {string} the truncated text, or full text if it's shorter than the provided limit.
*/
export function truncateText(
text: string,
limit: number,
withEllipsis: boolean = true
): string {
if (typeof limit !== "number") {
throw new Error("limit must be a number");
}
if (withEllipsis) {
limit -= ELLIPSIS.length;
}
if (text.length > limit) {
while (
limit > 1 &&
(!PATTERN_WORD_CHAR.test(text[limit - 1]) ||
!PATTERN_NON_WORD_CHAR.test(text[limit]))
) {
limit -= 1;
}
if (limit === 1) {
return text;
} else {
const truncatedText = text.substring(0, limit);
return withEllipsis ? truncatedText + ELLIPSIS : truncatedText + ".";
}
} else {
return text;
}
}
/**
* Find the parent element of a node matching a filter.
*/
export function findParentElement(
node: Node,
filter: (element: HTMLElement) => boolean
): HTMLElement | null {
let parent: HTMLElement | null =
node instanceof HTMLElement ? node : node.parentElement;
while (parent !== null) {
if (filter(parent)) {
return parent;
}
parent = parent.parentElement;
}
return null;
}
/**
* Get the page model (if any) that contains this node.
*/
export function getPageContainingNode(
node: Node,
pages: Pages
): PageModel | null {
const pageElement = findParentElement(
node,
(e) => e instanceof HTMLDivElement && e.classList.contains("page")
);
if (pageElement === null) {
return null;
}
for (const page of Object.values(pages)) {
if (page.view.div === pageElement) {
return page;
}
}
return null;
}
/**
* Convert a bounding box in ratio coordinates to PDF coordinates (i.e., in points). In the PDF
* coordinate system, 'top' is the number of points from the bottom of the page.
*/
export function convertBoxToPdfCoordinates(view: PDFPageView, box: Rectangle) {
/*
* Dimensions of the page in PDF coordinates are stored in a page's 'view' property.
* To see how these coordinates get loaded from PDF metadata (specifically, the "ViewArea"
* tags), see these two links:
* * https://github.com/mozilla/pdf.js/blob/cd6d0894894c97264eca993b10d0d9faa02fa829/src/core/document.js#L177
* * https://github.com/mozilla/pdf.js/blob/cd6d0894894c97264eca993b10d0d9faa02fa829/src/core/obj.js#L522
* Also see information about the "ViewArea" tag in the PDF spec, "PDF 32000-1:2008", page 628.
*/
//
const [pdfLeft, pdfBottom, pdfRight, pdfTop] = view.pdfPage.view;
const pdfWidth = pdfRight - pdfLeft;
const pdfHeight = pdfTop - pdfBottom;
return {
left: pdfLeft + box.left * pdfWidth,
top: pdfBottom + (1 - box.top) * pdfHeight,
width: box.width * pdfWidth,
height: box.height * pdfHeight,
};
}
/**
* Get the 'left', 'top', 'width', and 'height' CSS parameters for a paper annotation from a
* bounding box for that annotation. The bounding box is expected to be expressed in
* ratio coordinates (see the docstring for the BoundingBox type). The values returned will be
* absolute pixel positions. The caller can optionally specify a scaling favor (scaleCorrection).
* You shouldn't need to use it, though in past versions of this interface it was necessary to
* correct subtle issues in the positioning of annotations.
*/
export function getPositionInPageView(
pageView: PDFPageView,
box: Rectangle,
scaleCorrection?: number
) {
scaleCorrection = scaleCorrection || 1;
const pageDimensions = getPageViewDimensions(pageView);
return {
left: box.left * pageDimensions.width * scaleCorrection,
top: box.top * pageDimensions.height * scaleCorrection,
width: box.width * pageDimensions.width * scaleCorrection,
height: box.height * pageDimensions.height * scaleCorrection,
};
}
/**
* Get bounding boxes for all ranges in a text selection. Consecutive bounding boxes within a
* range are merged together, if sufficiently close to each other.
*/
export function getBoundingBoxesForSelection(
selection: Selection,
pages: Pages
) {
/*
* Get bounding boxes of all selected ranges.
*/
const boxes: BoundingBox[] = [];
for (let i = 0; i < selection.rangeCount; i++) {
const range = selection.getRangeAt(i);
/*
* Find the page that contains this range.
*/
const page = getPageContainingNode(range.commonAncestorContainer, pages);
/*
* If a page was found, save bounding boxes for the selection, in ratio coordinates
* relative to the page view 'div'.
*/
if (page !== null) {
const { pageNumber } = page.view.pdfPage;
const pageRect = page.view.div.getBoundingClientRect();
const rangeRects = range.getClientRects();
let lastBox = undefined;
for (let i = 0; i < rangeRects.length; i++) {
const rangeRect = rangeRects.item(i);
if (rangeRect !== null) {
/*
* Compute dimensions for a new box.
*/
const left = (rangeRect.left - pageRect.left) / pageRect.width;
const top = (rangeRect.top - pageRect.top) / pageRect.height;
const width = rangeRect.width / pageRect.width;
const height = rangeRect.height / pageRect.height;
const right = left + width;
const bottom = top + height;
/*
* If this box appears right after the last box and is vertically aligned
* with the last box, merge it with the last box. This loop takes advantage of
* how getClientRects() iterates over boxes in content order (see
* https://drafts.csswg.org/cssom-view/#dom-range-getclientrects).
*/
let boxMergedWithPrevious = false;
if (lastBox !== undefined) {
const lastBoxRight = lastBox.left + lastBox.width;
const lastBoxBottom = lastBox.top + lastBox.height;
const SMALL_HORIZONTAL_DELTA = 0.01; // 1% of page width
const SMALL_VERTICAL_DElTA = 0.01; // 1% of page height
if (
left - lastBoxRight < SMALL_HORIZONTAL_DELTA &&
Math.abs(top - lastBox.top) < SMALL_VERTICAL_DElTA &&
Math.abs(bottom - lastBoxBottom) < SMALL_VERTICAL_DElTA
) {
lastBox.width = right - lastBox.left;
lastBox.top = Math.min(top, lastBox.top);
lastBox.height = Math.max(bottom, lastBoxBottom) - lastBox.top;
boxMergedWithPrevious = true;
}
}
/*
* Create a new bounding box if it couldn't be merged with the previous box.
*/
if (!boxMergedWithPrevious) {
const box: BoundingBox = {
left,
top,
width,
height,
page: pageNumber - 1,
source: "human-annotation",
};
boxes.push(box);
lastBox = box;
}
}
}
}
}
return boxes;
}
/**
* Call this function whenever you want to get the width and height of a pageView object from
* PDF.js. This function avoids gotchas in computing the size of the page view. Width and
* height are returned in pixels.
*/
export function getPageViewDimensions(pageView: PDFPageView): Dimensions {
/*
* Use the viewport width and height here, instead of the scroll width and height of the
* pageView's <div/>. The reason is that the <div/> might increase in its width and height as
* we add annotations to it, though the viewport should be set once and stay constant each
* time that the page is rendered.
*/
return { width: pageView.viewport.width, height: pageView.viewport.height };
}
/**
* Get the page number for a PDFPageView of PDFPageProxy. While the page number used internally
* by pdf.js starts at 1, the numbers used by this application start at 0, so this function
* converts the pdf.js number to a 0-based number.
*/
export function getPageNumber(p: PDFPageView | PDFPageProxy) {
if ((p as any).pdfPage !== undefined) {
return (p as PDFPageView).pdfPage.pageNumber - 1;
} else {
return (p as PDFPageProxy).pageNumber - 1;
}
}
/**
* Programmatically trigger a click of a Material-UI button that makes it look like the button has
* actually been clicked. This requires simulating a 'mousedown' event, which starts a background
* 'ripple', followed by a 'mouseup' event. The ripple appears to last from the 'mousedown' event
* until the 'mouseup' event, and must have some duration. The 'click' event, however, is dispatched
* immediately so that the button click can be processed as soon as possible.
*/
export function simulateMaterialUiButtonClick(element: HTMLButtonElement) {
const MOUSE_EVENT_OPTIONS = { cancelable: true, bubbles: true };
const mouseDownEvent = new MouseEvent("mousedown", MOUSE_EVENT_OPTIONS);
const mouseUpEvent = new MouseEvent("mouseup", MOUSE_EVENT_OPTIONS);
const clickEvent = new MouseEvent("click", MOUSE_EVENT_OPTIONS);
/*
* Start the ripple effect.
*/
element.dispatchEvent(mouseDownEvent);
/*
* Trigger the click as soon as possible.
*/
element.dispatchEvent(clickEvent);
/*
* The ripple will continue to expand until the 'mouseup' event is dispatched. For it to look
* like the button has been pressed to a user, 'RIPPLE_TIME_MS' needs to be greater than 0,
* and is most visually salient if it is more than 100 ms.
*/
const RIPPLE_TIME_MS = 200;
setTimeout(() => {
element.dispatchEvent(mouseUpEvent);
}, RIPPLE_TIME_MS);
}
export function sortByFrequency(strings: string[]) {
/*
* Count up frequency of each item.
*/
const counts = strings.reduce((c, s) => {
c[s] = (c[s] || 0) + 1;
return c;
}, {} as { [s: string]: number });
/*
* Sort items by their frequency.
*/
const countsKeys = Object.keys(counts);
const indexes = countsKeys.map((_, i) => i);
indexes.sort((i1, i2) => {
const s1 = countsKeys[i1];
const s2 = countsKeys[i2];
return counts[s2] - counts[s1];
});
return indexes.map((i) => countsKeys[i]);
}
/**
* Join a list of strings into a text list, where strings are separated by commas with an
* 'and' before the last string.
*/
export function joinStrings(strings: string[]) {
if (strings.length === 0) {
return "";
}
if (strings.length === 1) {
return strings[0];
}
if (strings.length === 2) {
return strings[0] + " and " + strings[1];
}
if (strings.length > 2) {
return (
strings.slice(0, strings.length - 1).join(", ") +
", and" +
strings[strings.length - 1]
);
}
}
export function getScrollCoordinates(element: HTMLElement) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop,
scrollWidth: element.scrollWidth,
scrollHeight: element.scrollHeight,
clientWidth: element.clientWidth,
clientHeight: element.clientHeight,
};
}
export function getElementCoordinates(element: HTMLElement) {
return {
offsetLeft: element.offsetLeft,
offsetTop: element.offsetTop,
clientWidth: element.clientWidth,
clientHeight: element.clientHeight,
};
}
/**
* TODO(andrewhead): Handle the case of arXiv publications that have multiple versions. How do we
* make sure we're querying for the same version of paper data as the paper that was opened?
*/
export function extractArxivId(url: string): string | undefined {
const matches = url.match(/arxiv\.org\/pdf\/(.*)(?:\.pdf)/) || [];
return matches[1];
} | the_stack |
import {
INodeProperties,
} from 'n8n-workflow';
import {
billingAddress,
currencies,
makeCustomFieldsFixedCollection,
makeGetAllFields,
productDetailsOptions,
shippingAddress,
} from './SharedFields';
export const salesOrderOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
displayOptions: {
show: {
resource: [
'salesOrder',
],
},
},
options: [
{
name: 'Create',
value: 'create',
description: 'Create a sales order',
},
{
name: 'Create or Update',
value: 'upsert',
description: 'Create a new record, or update the current one if it already exists (upsert)',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a sales order',
},
{
name: 'Get',
value: 'get',
description: 'Get a sales order',
},
{
name: 'Get All',
value: 'getAll',
description: 'Get all sales orders',
},
{
name: 'Update',
value: 'update',
description: 'Update a sales order',
},
],
default: 'create',
description: 'Operation to perform',
},
];
export const salesOrderFields: INodeProperties[] = [
// ----------------------------------------
// salesOrder: create + upsert
// ----------------------------------------
{
displayName: 'Account ID',
name: 'accountId',
required: true,
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getAccounts',
},
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'create',
'upsert',
],
},
},
},
// ----------------------------------------
// salesOrder: create
// ----------------------------------------
{
displayName: 'Subject',
name: 'subject',
description: 'Subject or title of the sales order.',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'create',
],
},
},
},
// ----------------------------------------
// salesOrder: upsert
// ----------------------------------------
{
displayName: 'Subject',
name: 'subject',
description: 'Subject or title of the sales order. If a record with this subject exists it will be updated, otherwise a new one will be created.',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'upsert',
],
},
},
},
// ----------------------------------------
// salesOrder: create + upsert
// ----------------------------------------
{
displayName: 'Products',
name: 'Product_Details',
type: 'collection',
typeOptions: {
multipleValues: true,
multipleValueButtonText: 'Add Product',
},
default: {},
placeholder: 'Add Field',
options: productDetailsOptions,
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'create',
'upsert',
],
},
},
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'create',
'upsert',
],
},
},
options: [
{
displayName: 'Adjustment',
name: 'Adjustment',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Adjustment in the grand total, if any.',
},
billingAddress,
{
displayName: 'Carrier',
name: 'Carrier',
type: 'string',
default: '',
description: 'Name of the carrier.',
},
{
displayName: 'Contact ID',
name: 'contactId',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getContacts',
},
},
{
displayName: 'Currency',
name: 'Currency',
type: 'options',
default: 'USD',
description: 'Symbol of the currency in which revenue is generated.',
options: currencies,
},
makeCustomFieldsFixedCollection('salesOrder'),
{
displayName: 'Deal ID',
name: 'dealId',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getDeals',
},
},
{
displayName: 'Description',
name: 'Description',
type: 'string',
default: '',
},
{
displayName: 'Discount',
name: 'Discount',
type: 'number',
description: 'Discount applied to the sales order. For example, enter 12 for 12%.',
default: 0,
typeOptions: {
minValue: 0,
},
},
{
displayName: 'Due Date',
name: 'Due_Date',
type: 'dateTime',
default: '',
},
{
displayName: 'Exchange Rate',
name: 'Exchange_Rate',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Exchange rate of the default currency to the home currency.',
},
{
displayName: 'Grand Total',
name: 'Grand_Total',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Total amount for the product after deducting tax and discounts.',
},
{
displayName: 'Sales Order Number',
name: 'SO_Number',
type: 'string',
default: '',
description: 'ID of the sales order after creating a case.',
},
{
displayName: 'Sales Commission',
name: 'Sales_Commission',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Commission of sales person on deal closure as a percentage. For example, enter 12 for 12%.',
},
shippingAddress,
{
displayName: 'Status',
name: 'Status',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getSalesOrderStatus',
},
description: 'Status of the sales order.',
},
{
displayName: 'Sub Total',
name: 'Sub_Total',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Total amount for the product excluding tax.',
},
{
displayName: 'Tax',
name: 'Tax',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Tax amount as the sum of sales tax and value-added tax.',
},
{
displayName: 'Terms and Conditions',
name: 'Terms_and_Conditions',
type: 'string',
default: '',
description: 'Terms and conditions associated with the purchase order.',
},
],
},
// ----------------------------------------
// salesOrder: delete
// ----------------------------------------
{
displayName: 'Sales Order ID',
name: 'salesOrderId',
description: 'ID of the sales order to delete.',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'delete',
],
},
},
},
// ----------------------------------------
// salesOrder: get
// ----------------------------------------
{
displayName: 'Sales Order ID',
name: 'salesOrderId',
description: 'ID of the sales order to retrieve.',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'get',
],
},
},
},
// ----------------------------------------
// salesOrder: getAll
// ----------------------------------------
...makeGetAllFields('salesOrder'),
// ----------------------------------------
// salesOrder: update
// ----------------------------------------
{
displayName: 'Sales Order ID',
name: 'salesOrderId',
description: 'ID of the sales order to update.',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'update',
],
},
},
},
{
displayName: 'Update Fields',
name: 'updateFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'salesOrder',
],
operation: [
'update',
],
},
},
options: [
{
displayName: 'Account ID',
name: 'accountId',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getAccounts',
},
description: 'ID of the account associated with this invoice.',
},
{
displayName: 'Adjustment',
name: 'Adjustment',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Adjustment in the grand total, if any.',
},
billingAddress,
{
displayName: 'Carrier',
name: 'Carrier',
type: 'string',
default: '',
description: 'Name of the carrier.',
},
{
displayName: 'Contact ID',
name: 'contactId',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getContacts',
},
},
{
displayName: 'Currency',
name: 'Currency',
type: 'options',
default: 'USD',
description: 'Symbol of the currency in which revenue is generated.',
options: currencies,
},
makeCustomFieldsFixedCollection('salesOrder'),
{
displayName: 'Deal ID',
name: 'dealId',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getDeals',
},
},
{
displayName: 'Description',
name: 'Description',
type: 'string',
default: '',
},
{
displayName: 'Discount',
name: 'Discount',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
},
{
displayName: 'Due Date',
name: 'Due_Date',
type: 'dateTime',
default: '',
},
{
displayName: 'Exchange Rate',
name: 'Exchange_Rate',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Exchange rate of the default currency to the home currency.',
},
{
displayName: 'Grand Total',
name: 'Grand_Total',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Total amount for the product after deducting tax and discounts.',
},
{
displayName: 'Sales Order Number',
name: 'SO_Number',
type: 'string',
default: '',
description: 'ID of the sales order after creating a case.',
},
{
displayName: 'Sales Commission',
name: 'Sales_Commission',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Commission of sales person on deal closure as a percentage. For example, enter 12 for 12%.',
},
shippingAddress,
{
displayName: 'Status',
name: 'Status',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getSalesOrderStatus',
},
description: 'Status of the sales order.',
},
{
displayName: 'Sub Total',
name: 'Sub_Total',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Total amount for the product excluding tax.',
},
{
displayName: 'Subject',
name: 'Subject',
type: 'string',
default: '',
description: 'Subject or title of the sales order.',
},
{
displayName: 'Tax',
name: 'Tax',
type: 'number',
default: 0,
typeOptions: {
minValue: 0,
},
description: 'Tax amount as the sum of sales tax and value-added tax.',
},
{
displayName: 'Terms and Conditions',
name: 'Terms_and_Conditions',
type: 'string',
default: '',
description: 'Terms and conditions associated with the purchase order.',
},
],
},
]; | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [gamelift](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazongamelift.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Gamelift extends PolicyStatement {
public servicePrefix = 'gamelift';
/**
* Statement provider for service [gamelift](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazongamelift.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);
}
/**
* Grants permission to register player acceptance or rejection of a proposed FlexMatch match
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_AcceptMatch.html
*/
public toAcceptMatch() {
return this.to('AcceptMatch');
}
/**
* Grants permission to locate and reserve a game server to host a new game session
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ClaimGameServer.html
*/
public toClaimGameServer() {
return this.to('ClaimGameServer');
}
/**
* Grants permission to define a new alias for a fleet
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateAlias.html
*/
public toCreateAlias() {
return this.to('CreateAlias');
}
/**
* Grants permission to create a new game build using files stored in an Amazon S3 bucket
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateBuild.html
*/
public toCreateBuild() {
return this.to('CreateBuild');
}
/**
* Grants permission to create a new fleet of computing resources to run your game servers
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateFleet.html
*/
public toCreateFleet() {
return this.to('CreateFleet');
}
/**
* Grants permission to specify additional locations for a fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateFleetLocations.html
*/
public toCreateFleetLocations() {
return this.to('CreateFleetLocations');
}
/**
* Grants permission to create a new game server group, set up a corresponding Auto Scaling group, and launche instances to host game servers
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateGameServerGroup.html
*/
public toCreateGameServerGroup() {
return this.to('CreateGameServerGroup');
}
/**
* Grants permission to start a new game session on a specified fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateGameSession.html
*/
public toCreateGameSession() {
return this.to('CreateGameSession');
}
/**
* Grants permission to set up a new queue for processing game session placement requests
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateGameSessionQueue.html
*/
public toCreateGameSessionQueue() {
return this.to('CreateGameSessionQueue');
}
/**
* Grants permission to create a new FlexMatch matchmaker
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateMatchmakingConfiguration.html
*/
public toCreateMatchmakingConfiguration() {
return this.to('CreateMatchmakingConfiguration');
}
/**
* Grants permission to create a new matchmaking rule set for FlexMatch
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateMatchmakingRuleSet.html
*/
public toCreateMatchmakingRuleSet() {
return this.to('CreateMatchmakingRuleSet');
}
/**
* Grants permission to reserve an available game session slot for a player
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreatePlayerSession.html
*/
public toCreatePlayerSession() {
return this.to('CreatePlayerSession');
}
/**
* Grants permission to reserve available game session slots for multiple players
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreatePlayerSessions.html
*/
public toCreatePlayerSessions() {
return this.to('CreatePlayerSessions');
}
/**
* Grants permission to create a new Realtime Servers script
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateScript.html
*/
public toCreateScript() {
return this.to('CreateScript');
}
/**
* Grants permission to allow GameLift to create or delete a peering connection between a GameLift fleet VPC and a VPC on another AWS account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateVpcPeeringAuthorization.html
*/
public toCreateVpcPeeringAuthorization() {
return this.to('CreateVpcPeeringAuthorization');
}
/**
* Grants permission to establish a peering connection between your GameLift fleet VPC and a VPC on another account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_CreateVpcPeeringConnection.html
*/
public toCreateVpcPeeringConnection() {
return this.to('CreateVpcPeeringConnection');
}
/**
* Grants permission to delete an alias
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteAlias.html
*/
public toDeleteAlias() {
return this.to('DeleteAlias');
}
/**
* Grants permission to delete a game build
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteBuild.html
*/
public toDeleteBuild() {
return this.to('DeleteBuild');
}
/**
* Grants permission to delete an empty fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteFleet.html
*/
public toDeleteFleet() {
return this.to('DeleteFleet');
}
/**
* Grants permission to delete locations for a fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteFleetLocations.html
*/
public toDeleteFleetLocations() {
return this.to('DeleteFleetLocations');
}
/**
* Grants permission to permanently delete a game server group and terminate FleetIQ activity for the corresponding Auto Scaling group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteGameServerGroup.html
*/
public toDeleteGameServerGroup() {
return this.to('DeleteGameServerGroup');
}
/**
* Grants permission to delete an existing game session queue
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteGameSessionQueue.html
*/
public toDeleteGameSessionQueue() {
return this.to('DeleteGameSessionQueue');
}
/**
* Grants permission to delete an existing FlexMatch matchmaker
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteMatchmakingConfiguration.html
*/
public toDeleteMatchmakingConfiguration() {
return this.to('DeleteMatchmakingConfiguration');
}
/**
* Grants permission to delete an existing FlexMatch matchmaking rule set
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteMatchmakingRuleSet.html
*/
public toDeleteMatchmakingRuleSet() {
return this.to('DeleteMatchmakingRuleSet');
}
/**
* Grants permission to delete a set of auto-scaling rules
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteScalingPolicy.html
*/
public toDeleteScalingPolicy() {
return this.to('DeleteScalingPolicy');
}
/**
* Grants permission to delete a Realtime Servers script
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteScript.html
*/
public toDeleteScript() {
return this.to('DeleteScript');
}
/**
* Grants permission to cancel a VPC peering authorization
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteVpcPeeringAuthorization.html
*/
public toDeleteVpcPeeringAuthorization() {
return this.to('DeleteVpcPeeringAuthorization');
}
/**
* Grants permission to remove a peering connection between VPCs
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeleteVpcPeeringConnection.html
*/
public toDeleteVpcPeeringConnection() {
return this.to('DeleteVpcPeeringConnection');
}
/**
* Grants permission to remove a game server from a game server group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DeregisterGameServer.html
*/
public toDeregisterGameServer() {
return this.to('DeregisterGameServer');
}
/**
* Grants permission to retrieve properties for an alias
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeAlias.html
*/
public toDescribeAlias() {
return this.to('DescribeAlias');
}
/**
* Grants permission to retrieve properties for a game build
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeBuild.html
*/
public toDescribeBuild() {
return this.to('DescribeBuild');
}
/**
* Grants permission to retrieve the maximum allowed and current usage for EC2 instance types
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeEC2InstanceLimits.html
*/
public toDescribeEC2InstanceLimits() {
return this.to('DescribeEC2InstanceLimits');
}
/**
* Grants permission to retrieve general properties, including status, for fleets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetAttributes.html
*/
public toDescribeFleetAttributes() {
return this.to('DescribeFleetAttributes');
}
/**
* Grants permission to retrieve the current capacity setting for fleets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetCapacity.html
*/
public toDescribeFleetCapacity() {
return this.to('DescribeFleetCapacity');
}
/**
* Grants permission to retrieve entries from a fleet's event log
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetEvents.html
*/
public toDescribeFleetEvents() {
return this.to('DescribeFleetEvents');
}
/**
* Grants permission to retrieve general properties, including statuses, for a fleet's locations
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetLocationAttributes.html
*/
public toDescribeFleetLocationAttributes() {
return this.to('DescribeFleetLocationAttributes');
}
/**
* Grants permission to retrieve the current capacity setting for a fleet's location
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetLocationCapacity.html
*/
public toDescribeFleetLocationCapacity() {
return this.to('DescribeFleetLocationCapacity');
}
/**
* Grants permission to retrieve utilization statistics for fleet's location
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetLocationUtilization.html
*/
public toDescribeFleetLocationUtilization() {
return this.to('DescribeFleetLocationUtilization');
}
/**
* Grants permission to retrieve the inbound connection permissions for a fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetPortSettings.html
*/
public toDescribeFleetPortSettings() {
return this.to('DescribeFleetPortSettings');
}
/**
* Grants permission to retrieve utilization statistics for fleets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeFleetUtilization.html
*/
public toDescribeFleetUtilization() {
return this.to('DescribeFleetUtilization');
}
/**
* Grants permission to retrieve properties for a game server
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeGameServer.html
*/
public toDescribeGameServer() {
return this.to('DescribeGameServer');
}
/**
* Grants permission to retrieve properties for a game server group
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeGameServerGroup.html
*/
public toDescribeGameServerGroup() {
return this.to('DescribeGameServerGroup');
}
/**
* Grants permission to retrieve the status of EC2 instances in a game server group
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeGameServerInstances.html
*/
public toDescribeGameServerInstances() {
return this.to('DescribeGameServerInstances');
}
/**
* Grants permission to retrieve properties for game sessions in a fleet, including the protection policy
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeGameSessionDetails.html
*/
public toDescribeGameSessionDetails() {
return this.to('DescribeGameSessionDetails');
}
/**
* Grants permission to retrieve details of a game session placement request
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeGameSessionPlacement.html
*/
public toDescribeGameSessionPlacement() {
return this.to('DescribeGameSessionPlacement');
}
/**
* Grants permission to retrieve properties for game session queues
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeGameSessionQueues.html
*/
public toDescribeGameSessionQueues() {
return this.to('DescribeGameSessionQueues');
}
/**
* Grants permission to retrieve properties for game sessions in a fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeGameSessions.html
*/
public toDescribeGameSessions() {
return this.to('DescribeGameSessions');
}
/**
* Grants permission to retrieve information about instances in a fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeInstances.html
*/
public toDescribeInstances() {
return this.to('DescribeInstances');
}
/**
* Grants permission to retrieve details of matchmaking tickets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeMatchmaking.html
*/
public toDescribeMatchmaking() {
return this.to('DescribeMatchmaking');
}
/**
* Grants permission to retrieve properties for FlexMatch matchmakers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeMatchmakingConfigurations.html
*/
public toDescribeMatchmakingConfigurations() {
return this.to('DescribeMatchmakingConfigurations');
}
/**
* Grants permission to retrieve properties for FlexMatch matchmaking rule sets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeMatchmakingRuleSets.html
*/
public toDescribeMatchmakingRuleSets() {
return this.to('DescribeMatchmakingRuleSets');
}
/**
* Grants permission to retrieve properties for player sessions in a game session
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribePlayerSessions.html
*/
public toDescribePlayerSessions() {
return this.to('DescribePlayerSessions');
}
/**
* Grants permission to retrieve the current runtime configuration for a fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeRuntimeConfiguration.html
*/
public toDescribeRuntimeConfiguration() {
return this.to('DescribeRuntimeConfiguration');
}
/**
* Grants permission to retrieve all scaling policies that are applied to a fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeScalingPolicies.html
*/
public toDescribeScalingPolicies() {
return this.to('DescribeScalingPolicies');
}
/**
* Grants permission to retrieve properties for a Realtime Servers script
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeScript.html
*/
public toDescribeScript() {
return this.to('DescribeScript');
}
/**
* Grants permission to retrieve valid VPC peering authorizations
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeVpcPeeringAuthorizations.html
*/
public toDescribeVpcPeeringAuthorizations() {
return this.to('DescribeVpcPeeringAuthorizations');
}
/**
* Grants permission to retrieve details on active or pending VPC peering connections
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_DescribeVpcPeeringConnections.html
*/
public toDescribeVpcPeeringConnections() {
return this.to('DescribeVpcPeeringConnections');
}
/**
* Grants permission to retrieve the location of stored logs for a game session
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_GetGameSessionLogUrl.html
*/
public toGetGameSessionLogUrl() {
return this.to('GetGameSessionLogUrl');
}
/**
* Grants permission to request remote access to a specified fleet instance
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_GetInstanceAccess.html
*/
public toGetInstanceAccess() {
return this.to('GetInstanceAccess');
}
/**
* Grants permission to retrieve all aliases that are defined in the current region
*
* Access Level: List
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ListAliases.html
*/
public toListAliases() {
return this.to('ListAliases');
}
/**
* Grants permission to retrieve all game build in the current region
*
* Access Level: List
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ListBuilds.html
*/
public toListBuilds() {
return this.to('ListBuilds');
}
/**
* Grants permission to retrieve a list of fleet IDs for all fleets in the current region
*
* Access Level: List
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ListFleets.html
*/
public toListFleets() {
return this.to('ListFleets');
}
/**
* Grants permission to retrieve all game server groups that are defined in the current region
*
* Access Level: List
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ListGameServerGroups.html
*/
public toListGameServerGroups() {
return this.to('ListGameServerGroups');
}
/**
* Grants permission to retrieve all game servers that are currently running in a game server group
*
* Access Level: List
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ListGameServers.html
*/
public toListGameServers() {
return this.to('ListGameServers');
}
/**
* Grants permission to retrieve properties for all Realtime Servers scripts in the current region
*
* Access Level: List
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ListScripts.html
*/
public toListScripts() {
return this.to('ListScripts');
}
/**
* Grants permission to retrieve tags for GameLift resources
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to create or update a fleet auto-scaling policy
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_PutScalingPolicy.html
*/
public toPutScalingPolicy() {
return this.to('PutScalingPolicy');
}
/**
* Grants permission to notify GameLift FleetIQ when a new game server is ready to host gameplay
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_RegisterGameServer.html
*/
public toRegisterGameServer() {
return this.to('RegisterGameServer');
}
/**
* Grants permission to retrieve fresh upload credentials to use when uploading a new game build
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_RequestUploadCredentials.html
*/
public toRequestUploadCredentials() {
return this.to('RequestUploadCredentials');
}
/**
* Grants permission to retrieve the fleet ID associated with an alias
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ResolveAlias.html
*/
public toResolveAlias() {
return this.to('ResolveAlias');
}
/**
* Grants permission to reinstate suspended FleetIQ activity for a game server group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ResumeGameServerGroup.html
*/
public toResumeGameServerGroup() {
return this.to('ResumeGameServerGroup');
}
/**
* Grants permission to retrieve game sessions that match a set of search criteria
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_SearchGameSessions.html
*/
public toSearchGameSessions() {
return this.to('SearchGameSessions');
}
/**
* Grants permission to resume auto-scaling activity on a fleet after it was suspended with StopFleetActions()
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_StartFleetActions.html
*/
public toStartFleetActions() {
return this.to('StartFleetActions');
}
/**
* Grants permission to send a game session placement request to a game session queue
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_StartGameSessionPlacement.html
*/
public toStartGameSessionPlacement() {
return this.to('StartGameSessionPlacement');
}
/**
* Grants permission to request FlexMatch matchmaking to fill available player slots in an existing game session
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_StartMatchBackfill.html
*/
public toStartMatchBackfill() {
return this.to('StartMatchBackfill');
}
/**
* Grants permission to request FlexMatch matchmaking for one or a group of players and initiate game session placement
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_StartMatchmaking.html
*/
public toStartMatchmaking() {
return this.to('StartMatchmaking');
}
/**
* Grants permission to suspend auto-scaling activity on a fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_StopFleetActions.html
*/
public toStopFleetActions() {
return this.to('StopFleetActions');
}
/**
* Grants permission to cancel a game session placement request that is in progress
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_StopGameSessionPlacement.html
*/
public toStopGameSessionPlacement() {
return this.to('StopGameSessionPlacement');
}
/**
* Grants permission to cancel a matchmaking or match backfill request that is in progress
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_StopMatchmaking.html
*/
public toStopMatchmaking() {
return this.to('StopMatchmaking');
}
/**
* Grants permission to temporarily stop FleetIQ activity for a game server group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_SuspendGameServerGroup.html
*/
public toSuspendGameServerGroup() {
return this.to('SuspendGameServerGroup');
}
/**
* Grants permission to tag GameLift resources
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to untag GameLift resources
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update the properties of an existing alias
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateAlias.html
*/
public toUpdateAlias() {
return this.to('UpdateAlias');
}
/**
* Grants permission to update an existing build's metadata
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateBuild.html
*/
public toUpdateBuild() {
return this.to('UpdateBuild');
}
/**
* Grants permission to update the general properties of an existing fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateFleetAttributes.html
*/
public toUpdateFleetAttributes() {
return this.to('UpdateFleetAttributes');
}
/**
* Grants permission to adjust a fleet's capacity settings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateFleetCapacity.html
*/
public toUpdateFleetCapacity() {
return this.to('UpdateFleetCapacity');
}
/**
* Grants permission to adjust a fleet's port settings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateFleetPortSettings.html
*/
public toUpdateFleetPortSettings() {
return this.to('UpdateFleetPortSettings');
}
/**
* Grants permission to change game server properties, health status, or utilization status
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateGameServer.html
*/
public toUpdateGameServer() {
return this.to('UpdateGameServer');
}
/**
* Grants permission to update properties for game server group, including allowed instance types
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateGameServerGroup.html
*/
public toUpdateGameServerGroup() {
return this.to('UpdateGameServerGroup');
}
/**
* Grants permission to update the properties of an existing game session
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateGameSession.html
*/
public toUpdateGameSession() {
return this.to('UpdateGameSession');
}
/**
* Grants permission to update properties of an existing game session queue
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateGameSessionQueue.html
*/
public toUpdateGameSessionQueue() {
return this.to('UpdateGameSessionQueue');
}
/**
* Grants permission to update properties of an existing FlexMatch matchmaking configuration
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateMatchmakingConfiguration.html
*/
public toUpdateMatchmakingConfiguration() {
return this.to('UpdateMatchmakingConfiguration');
}
/**
* Grants permission to update how server processes are configured on instances in an existing fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateRuntimeConfiguration.html
*/
public toUpdateRuntimeConfiguration() {
return this.to('UpdateRuntimeConfiguration');
}
/**
* Grants permission to update the metadata and content of an existing Realtime Servers script
*
* Access Level: Write
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_UpdateScript.html
*/
public toUpdateScript() {
return this.to('UpdateScript');
}
/**
* Grants permission to validate the syntax of a FlexMatch matchmaking rule set
*
* Access Level: Read
*
* https://docs.aws.amazon.com/gamelift/latest/apireference/API_ValidateMatchmakingRuleSet.html
*/
public toValidateMatchmakingRuleSet() {
return this.to('ValidateMatchmakingRuleSet');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AcceptMatch",
"ClaimGameServer",
"CreateAlias",
"CreateBuild",
"CreateFleet",
"CreateFleetLocations",
"CreateGameServerGroup",
"CreateGameSession",
"CreateGameSessionQueue",
"CreateMatchmakingConfiguration",
"CreateMatchmakingRuleSet",
"CreatePlayerSession",
"CreatePlayerSessions",
"CreateScript",
"CreateVpcPeeringAuthorization",
"CreateVpcPeeringConnection",
"DeleteAlias",
"DeleteBuild",
"DeleteFleet",
"DeleteFleetLocations",
"DeleteGameServerGroup",
"DeleteGameSessionQueue",
"DeleteMatchmakingConfiguration",
"DeleteMatchmakingRuleSet",
"DeleteScalingPolicy",
"DeleteScript",
"DeleteVpcPeeringAuthorization",
"DeleteVpcPeeringConnection",
"DeregisterGameServer",
"PutScalingPolicy",
"RegisterGameServer",
"ResumeGameServerGroup",
"StartFleetActions",
"StartGameSessionPlacement",
"StartMatchBackfill",
"StartMatchmaking",
"StopFleetActions",
"StopGameSessionPlacement",
"StopMatchmaking",
"SuspendGameServerGroup",
"UpdateAlias",
"UpdateBuild",
"UpdateFleetAttributes",
"UpdateFleetCapacity",
"UpdateFleetPortSettings",
"UpdateGameServer",
"UpdateGameServerGroup",
"UpdateGameSession",
"UpdateGameSessionQueue",
"UpdateMatchmakingConfiguration",
"UpdateRuntimeConfiguration",
"UpdateScript"
],
"Read": [
"DescribeAlias",
"DescribeBuild",
"DescribeEC2InstanceLimits",
"DescribeFleetAttributes",
"DescribeFleetCapacity",
"DescribeFleetEvents",
"DescribeFleetLocationAttributes",
"DescribeFleetLocationCapacity",
"DescribeFleetLocationUtilization",
"DescribeFleetPortSettings",
"DescribeFleetUtilization",
"DescribeGameServer",
"DescribeGameServerGroup",
"DescribeGameServerInstances",
"DescribeGameSessionDetails",
"DescribeGameSessionPlacement",
"DescribeGameSessionQueues",
"DescribeGameSessions",
"DescribeInstances",
"DescribeMatchmaking",
"DescribeMatchmakingConfigurations",
"DescribeMatchmakingRuleSets",
"DescribePlayerSessions",
"DescribeRuntimeConfiguration",
"DescribeScalingPolicies",
"DescribeScript",
"DescribeVpcPeeringAuthorizations",
"DescribeVpcPeeringConnections",
"GetGameSessionLogUrl",
"GetInstanceAccess",
"ListTagsForResource",
"RequestUploadCredentials",
"ResolveAlias",
"SearchGameSessions",
"ValidateMatchmakingRuleSet"
],
"List": [
"ListAliases",
"ListBuilds",
"ListFleets",
"ListGameServerGroups",
"ListGameServers",
"ListScripts"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type alias to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_Alias.html
*
* @param aliasId - Identifier for the aliasId.
* @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 onAlias(aliasId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}::alias/${AliasId}';
arn = arn.replace('${AliasId}', aliasId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type build to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_Build.html
*
* @param buildId - Identifier for the buildId.
* @param accountId - 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 onBuild(buildId: string, accountId?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}:${AccountId}:build/${BuildId}';
arn = arn.replace('${BuildId}', buildId);
arn = arn.replace('${AccountId}', accountId || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type script to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_Script.html
*
* @param scriptId - Identifier for the scriptId.
* @param accountId - 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 onScript(scriptId: string, accountId?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}:${AccountId}:script/${ScriptId}';
arn = arn.replace('${ScriptId}', scriptId);
arn = arn.replace('${AccountId}', accountId || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type fleet to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_FleetAttributes.html
*
* @param fleetId - Identifier for the fleetId.
* @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 onFleet(fleetId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}:${Account}:fleet/${FleetId}';
arn = arn.replace('${FleetId}', fleetId);
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 gameSessionQueue to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_GameSessionQueue.html
*
* @param gameSessionQueueName - Identifier for the gameSessionQueueName.
* @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 onGameSessionQueue(gameSessionQueueName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}:${Account}:gamesessionqueue/${GameSessionQueueName}';
arn = arn.replace('${GameSessionQueueName}', gameSessionQueueName);
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 matchmakingConfiguration to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_MatchmakingConfiguration.html
*
* @param matchmakingConfigurationName - Identifier for the matchmakingConfigurationName.
* @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 onMatchmakingConfiguration(matchmakingConfigurationName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}:${Account}:matchmakingconfiguration/${MatchmakingConfigurationName}';
arn = arn.replace('${MatchmakingConfigurationName}', matchmakingConfigurationName);
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 matchmakingRuleSet to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_MatchmakingRuleSet.html
*
* @param matchmakingRuleSetName - Identifier for the matchmakingRuleSetName.
* @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 onMatchmakingRuleSet(matchmakingRuleSetName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}:${Account}:matchmakingruleset/${MatchmakingRuleSetName}';
arn = arn.replace('${MatchmakingRuleSetName}', matchmakingRuleSetName);
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 gameServerGroup to the statement
*
* https://docs.aws.amazon.com/gamelift/latest/developerguide/API_GameServerGroup.html
*
* @param gameServerGroupName - Identifier for the gameServerGroupName.
* @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 onGameServerGroup(gameServerGroupName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:gamelift:${Region}:${Account}:gameservergroup/${GameServerGroupName}';
arn = arn.replace('${GameServerGroupName}', gameServerGroupName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import path from 'path';
import { promisify } from 'util';
import { exec } from 'child_process';
import { DialogSetting, IBotProject } from '@botframework-composer/types';
import rimraf from 'rimraf';
import * as fs from 'fs-extra';
import { copyDir } from './copyDir';
import { IFileStorage } from './interface';
const execAsync = promisify(exec);
const removeDirAndFiles = promisify(rimraf);
const execTimeout = 5 * 60 * 1000; // timeout after 5 minutes
/**
* Used to set values for Azure Functions runtime environment variables
* This is used to set the "sensitive values" when using Azure Functions
* @param name name of key
* @param value value of key
* @param cwd path where the command will be run
*/
const writeLocalFunctionsSetting = async (name: string, value: string, cwd: string, log) => {
// only set if there is both a setting and a value.
if (name && value && cwd) {
const { stderr: err } = await execAsync(`func settings add ${name} ${value}`, { cwd: cwd });
if (err) {
log('Error calling func settings add', err);
throw new Error(err);
}
}
};
const writeAllLocalFunctionsSettings = async (fullSettings: DialogSetting, port: number, runtimePath: string, log) => {
await writeLocalFunctionsSetting('MicrosoftAppPassword', fullSettings.MicrosoftAppPassword, runtimePath, log);
await writeLocalFunctionsSetting(
'luis:endpointKey',
fullSettings.luis?.endpointKey || fullSettings.luis?.authoringKey,
runtimePath,
log
);
await writeLocalFunctionsSetting('qna:endpointKey', fullSettings.qna?.endpointKey, runtimePath, log);
let skillHostEndpoint;
if (isSkillHostUpdateRequired(fullSettings?.skillHostEndpoint)) {
// Update skillhost endpoint only if ngrok url not set meaning empty or localhost url
skillHostEndpoint = `http://127.0.0.1:${port}/api/skills`;
}
await writeLocalFunctionsSetting('SkillHostEndpoint', skillHostEndpoint, runtimePath, log);
};
// eslint-disable-next-line security/detect-unsafe-regex
const localhostRegex = /^https?:\/\/(localhost|127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|::1)/;
const isLocalhostUrl = (matchUrl: string) => {
return localhostRegex.test(matchUrl);
};
const isSkillHostUpdateRequired = (skillHostEndpoint?: string) => {
return !skillHostEndpoint || isLocalhostUrl(skillHostEndpoint);
};
export default async (composer: any): Promise<void> => {
/**
* these are the new 2.0 adaptive runtime definitions
*/
composer.addRuntimeTemplate({
key: 'adaptive-runtime-dotnet-webapp',
name: 'C# - Web App',
build: async (runtimePath: string, project: IBotProject) => {
composer.log(`BUILD THIS C# WEBAPP PROJECT! at ${runtimePath}...`);
composer.log('Run dotnet user-secrets init...');
// TODO: capture output of this and store it somewhere useful
const { stderr: initErr } = await execAsync(`dotnet user-secrets init --project ${project.name}.csproj`, {
cwd: runtimePath,
});
if (initErr) {
throw new Error(initErr);
}
composer.log('Run dotnet build...');
const { stderr: buildErr } = await execAsync(`dotnet build ${project.name}.csproj`, { cwd: runtimePath });
if (buildErr) {
throw new Error(buildErr);
}
composer.log('FINISHED BUILDING!');
},
installComponent: async (
runtimePath: string,
packageName: string,
version: string,
source: string,
project: IBotProject,
isPreview = false
): Promise<string> => {
// run dotnet install on the project
const command = `dotnet add ${project.name}.csproj package "${packageName}"${
version ? ' --version="' + version + '"' : ''
}${source ? ' --source="' + source + '"' : ''}${isPreview ? ' --prerelease' : ''}`;
composer.log('EXEC:', command);
const { stderr: installError, stdout: installOutput } = await execAsync(command, {
cwd: path.join(runtimePath),
});
if (installError) {
throw new Error(installError);
}
return installOutput;
},
uninstallComponent: async (runtimePath: string, packageName: string, project: IBotProject): Promise<string> => {
// run dotnet install on the project
composer.log(`EXECUTE: dotnet remove ${project.name}.csproj package ${packageName}`);
const { stderr: installError, stdout: installOutput } = await execAsync(
`dotnet remove ${project.name}.csproj package ${packageName}`,
{
cwd: path.join(runtimePath),
}
);
if (installError) {
throw new Error(installError);
}
return installOutput;
},
identifyManifest: (runtimePath: string, projName?: string): string => {
return path.join(runtimePath, `${projName}.csproj`);
},
run: async (project: IBotProject, localDisk: IFileStorage) => {
composer.log('RUN THIS C# PROJECT!');
},
buildDeploy: async (
runtimePath: string,
project: IBotProject,
settings: DialogSetting,
profileName: string
): Promise<string> => {
composer.log('BUILD FOR DEPLOY TO AZURE!');
// find publishing profile in list
const profile = project.settings.publishTargets.find((p) => p.name === profileName);
const csproj = `${project.name}.csproj`;
const publishFolder = path.join(runtimePath, 'bin', 'release', 'publishTarget');
const deployFilePath = path.join(runtimePath, '.deployment');
const dotnetProjectPath = path.join(runtimePath, csproj);
// Check for existing .deployment file, if missing, write it.
if (!(await fs.pathExists(deployFilePath))) {
const data = `[config]\nproject = ${csproj}`;
await fs.writeFile(deployFilePath, data);
}
// do the dotnet publish
try {
const configuration = JSON.parse(profile.configuration);
const runtimeIdentifier = configuration.runtimeIdentifier;
// if runtime identifier set, make dotnet runtime to self contained, default runtime identifier is win-x64, please refer to https://docs.microsoft.com/en-us/dotnet/core/rid-catalog
const buildCommand = `dotnet publish "${dotnetProjectPath}" -c release -o "${publishFolder}" -v q --self-contained true -r ${
runtimeIdentifier ?? 'win-x64'
}`;
// }
const { stdout, stderr } = await execAsync(buildCommand, {
cwd: runtimePath,
});
composer.log('OUTPUT FROM BUILD', stdout);
if (stderr) {
composer.log('ERR FROM BUILD: ', stderr);
}
} catch (err) {
composer.log('Error doing dotnet publish', err);
throw err;
return;
}
// return the location of the build artifiacts
return publishFolder;
},
setSkillManifest: async (
dstRuntimePath: string,
dstStorage: IFileStorage,
srcManifestDir: string,
srcStorage: IFileStorage,
mode = 'azurewebapp' // set default as azurewebapp
) => {
// update manifst into runtime wwwroot
if (mode === 'azurewebapp') {
const manifestDstDir = path.resolve(dstRuntimePath, 'wwwroot', 'manifests');
if (await fs.pathExists(manifestDstDir)) {
await removeDirAndFiles(manifestDstDir);
}
if (await fs.pathExists(srcManifestDir)) {
await copyDir(srcManifestDir, srcStorage, manifestDstDir, dstStorage);
}
}
},
});
composer.addRuntimeTemplate({
key: 'adaptive-runtime-dotnet-functions',
name: 'C# - Functions',
// startCommand: 'dotnet run',
// path: dotnetTemplatePath,
build: async (runtimePath: string, project: IBotProject, fullSettings?: DialogSetting, port?: number) => {
composer.log(`BUILD THIS C# FUNCTIONS PROJECT! at ${runtimePath}...`);
composer.log('Run dotnet user-secrets init...');
if (fullSettings && port) {
// we need to update the local.settings.json file with sensitive settings
await writeAllLocalFunctionsSettings(fullSettings, port, runtimePath, composer.log);
}
// TODO: capture output of this and store it somewhere useful
const { stderr: initErr } = await execAsync(`dotnet user-secrets init --project ${project.name}.csproj`, {
cwd: runtimePath,
});
if (initErr) {
throw new Error(initErr);
}
composer.log('Run dotnet build...');
const { stderr: buildErr } = await execAsync(`dotnet build ${project.name}.csproj`, { cwd: runtimePath });
if (buildErr) {
throw new Error(buildErr);
}
composer.log('FINISHED BUILDING!');
},
installComponent: async (
runtimePath: string,
packageName: string,
version: string,
source: string,
project: IBotProject,
isPreview = false
): Promise<string> => {
// run dotnet install on the project
const command = `dotnet add ${project.name}.csproj package "${packageName}"${
version ? ' --version="' + version + '"' : ''
}${source ? ' --source="' + source + '"' : ''}${isPreview ? ' --prerelease' : ''}`;
composer.log('EXEC:', command);
const { stderr: installError, stdout: installOutput } = await execAsync(command, {
cwd: path.join(runtimePath),
});
if (installError) {
throw new Error(installError);
}
return installOutput;
},
uninstallComponent: async (runtimePath: string, packageName: string, project: IBotProject): Promise<string> => {
// run dotnet install on the project
composer.log(`EXECUTE: dotnet remove ${project.name}.csproj package ${packageName}`);
const { stderr: installError, stdout: installOutput } = await execAsync(
`dotnet remove ${project.name}.csproj package ${packageName}`,
{
cwd: path.join(runtimePath),
}
);
if (installError) {
throw new Error(installError);
}
return installOutput;
},
identifyManifest: (runtimePath: string, projName?: string): string => {
return path.join(runtimePath, `${projName}.csproj`);
},
run: async (project: IBotProject, localDisk: IFileStorage) => {
composer.log('RUN THIS C# PROJECT!');
},
buildDeploy: async (
runtimePath: string,
project: IBotProject,
settings: DialogSetting,
profileName: string
): Promise<string> => {
composer.log('BUILD FOR DEPLOY TO AZURE!');
// find publishing profile in list
const profile = project.settings.publishTargets.find((p) => p.name === profileName);
const csproj = `${project.name}.csproj`;
const publishFolder = path.join(runtimePath, 'bin', 'release', 'publishTarget');
const deployFilePath = path.join(runtimePath, '.deployment');
const dotnetProjectPath = path.join(runtimePath, csproj);
// Check for existing .deployment file, if missing, write it.
if (!(await fs.pathExists(deployFilePath))) {
const data = `[config]\nproject = ${csproj}`;
await fs.writeFile(deployFilePath, data);
}
// do the dotnet publish
try {
const buildCommand = `dotnet publish "${dotnetProjectPath}" -c release -o "${publishFolder}" -v q`;
const { stdout, stderr } = await execAsync(buildCommand, {
cwd: runtimePath,
});
composer.log('OUTPUT FROM BUILD', stdout);
if (stderr) {
composer.log('ERR FROM BUILD: ', stderr);
}
} catch (err) {
composer.log('Error doing dotnet publish', err);
throw err;
return;
}
// return the location of the build artifiacts
return publishFolder;
},
});
/**
* This is support for the new javascript runtime
*/
composer.addRuntimeTemplate({
key: 'adaptive-runtime-js-webapp',
name: 'JS - Web App (preview)',
// startCommand: 'node ./lib/webapp.js',
// path: nodeTemplatePath,
build: async (runtimePath: string, _project: IBotProject) => {
// do stuff
composer.log('BUILD THIS JS PROJECT');
// install dev dependencies in production, make sure typescript is installed
const { stderr: installErr } = await execAsync('npm install && npm install --only=dev', {
cwd: runtimePath,
timeout: execTimeout,
});
if (installErr) {
// in order to not throw warning, we just log all warning and error message
composer.log(`npm install timeout, ${installErr}`);
}
composer.log('BUILD COMPLETE');
},
installComponent: async (
runtimePath: string,
packageName: string,
version: string,
source: string,
_project: IBotProject,
isPreview = false
): Promise<string> => {
// run dotnet install on the project
const { stderr: installError, stdout: installOutput } = await execAsync(
`npm install --loglevel=error --save ${packageName}${version ? '@' + version : ''}`,
{
cwd: path.join(runtimePath),
}
);
if (installError) {
throw new Error(installError);
}
return installOutput;
},
uninstallComponent: async (runtimePath: string, packageName: string): Promise<string> => {
// run dotnet install on the project
const { stderr: installError, stdout: installOutput } = await execAsync(
`npm uninstall --loglevel=error --save ${packageName}`,
{
cwd: path.join(runtimePath),
}
);
if (installError) {
throw new Error(installError);
}
return installOutput;
},
identifyManifest: (runtimePath: string, projName?: string): string => {
return path.join(runtimePath, 'package.json');
},
buildDeploy: async (
runtimePath: string,
project: IBotProject,
settings: DialogSetting,
profileName: string
): Promise<string> => {
// do stuff
composer.log(`BUILD THIS JS PROJECT in ${runtimePath}`);
const { stderr: installErr } = await execAsync('npm install', {
cwd: path.resolve(runtimePath, '.'),
});
if (installErr) {
composer.log(installErr);
}
composer.log('BUILD COMPLETE');
return path.resolve(runtimePath, '.');
},
});
composer.addRuntimeTemplate({
key: 'adaptive-runtime-js-functions',
name: 'JS - Functions (preview)',
build: async (runtimePath: string, _project: IBotProject, fullSettings?: DialogSetting, port?: number) => {
// do stuff
composer.log('BUILD THIS JS PROJECT');
// install dev dependencies in production, make sure typescript is installed
const { stderr: installErr } = await execAsync('npm install && npm install --only=dev', {
cwd: runtimePath,
timeout: execTimeout,
});
if (installErr) {
// in order to not throw warning, we just log all warning and error message
composer.log(`npm install timeout, ${installErr}`);
}
if (fullSettings && port) {
// we need to update the local.settings.json file with sensitive settings
await writeAllLocalFunctionsSettings(fullSettings, port, runtimePath, composer.log);
}
composer.log('BUILD COMPLETE');
},
installComponent: async (
runtimePath: string,
packageName: string,
version: string,
source: string,
_project: IBotProject,
isPreview = false
): Promise<string> => {
// run dotnet install on the project
const { stderr: installError, stdout: installOutput } = await execAsync(
`npm install --loglevel=error --save ${packageName}${version ? '@' + version : ''}`,
{
cwd: path.join(runtimePath),
}
);
if (installError) {
throw new Error(installError);
}
return installOutput;
},
uninstallComponent: async (runtimePath: string, packageName: string): Promise<string> => {
// run dotnet install on the project
const { stderr: installError, stdout: installOutput } = await execAsync(
`npm uninstall --loglevel=error --save ${packageName}`,
{
cwd: path.join(runtimePath),
}
);
if (installError) {
throw new Error(installError);
}
return installOutput;
},
identifyManifest: (runtimePath: string, projName?: string): string => {
return path.join(runtimePath, 'package.json');
},
buildDeploy: async (
runtimePath: string,
project: IBotProject,
settings: DialogSetting,
profileName: string
): Promise<string> => {
// do stuff
composer.log(`BUILD THIS JS PROJECT in ${runtimePath}`);
const { stderr: installErr } = await execAsync('npm ci', {
cwd: path.resolve(runtimePath, '.'),
});
if (installErr) {
composer.log(installErr);
}
composer.log('BUILD COMPLETE');
return path.resolve(runtimePath, '.');
},
});
}; | the_stack |
import {Injectable} from "@angular/core";
import * as Yaml from "js-yaml";
import {LoadOptions} from "js-yaml";
import {Observable} from "rxjs/Observable";
import {ReplaySubject} from "rxjs/ReplaySubject";
import {App} from "../../../electron/src/sbg-api-client/interfaces/app";
import {Project} from "../../../electron/src/sbg-api-client/interfaces";
import {RawApp} from "../../../electron/src/sbg-api-client/interfaces/raw-app";
import {AppMeta, AppMetaEntry} from "../../../electron/src/storage/types/app-meta";
import {RecentAppTab} from "../../../electron/src/storage/types/recent-app-tab";
import {TabData} from "../../../electron/src/storage/types/tab-data-interface";
import {IpcService} from "../services/ipc.service";
import {AuthService} from "../auth/auth.service";
import {
map,
take,
flatMap,
catchError,
switchMap,
withLatestFrom
} from "rxjs/operators";
import {combineLatest} from "rxjs/observable/combineLatest";
import {of} from "rxjs/observable/of";
import {_throw} from "rxjs/observable/throw";
@Injectable()
export class PlatformRepositoryService {
private apps: ReplaySubject<App[]> = new ReplaySubject(1);
private publicApps: ReplaySubject<App[]> = new ReplaySubject(1);
private projects: ReplaySubject<Project[]> = new ReplaySubject(1);
private openProjects: ReplaySubject<string[]> = new ReplaySubject(1);
private expandedNodes: ReplaySubject<string[]> = new ReplaySubject(1);
private openTabs: ReplaySubject<TabData<any>[]> = new ReplaySubject(1);
private recentApps: ReplaySubject<RecentAppTab[]> = new ReplaySubject(1);
private appMeta: ReplaySubject<AppMeta[]> = new ReplaySubject(1);
constructor(private ipc: IpcService, private auth: AuthService) {
this.listen("apps").subscribe(this.apps);
this.listen("projects").subscribe(this.projects);
this.listen("openTabs").subscribe(this.openTabs);
this.listen("publicApps").subscribe(this.publicApps);
this.listen("recentApps").subscribe(this.recentApps);
this.listen("openProjects").subscribe(this.openProjects);
this.listen("expandedNodes").subscribe(this.expandedNodes);
this.listen("appMeta").subscribe(this.appMeta);
}
getOpenTabs(): Observable<TabData<any>[] | null> {
return this.openTabs;
}
getAppsForProject(projectID): Observable<App[]> {
return this.apps.pipe(
// Apps may not be present, fallback to an empty array
map(apps => {
return (apps || []).filter(app => app.project === projectID);
})
);
}
getProjects(): Observable<Project[]> {
return this.projects;
}
setProjects(projects: Project[]) {
return this.patch({projects: projects});
}
getPublicApps(): Observable<App[] | null> {
return this.publicApps;
}
getPrivateApps(): Observable<App[]> {
return this.apps;
}
getRecentApps(): Observable<RecentAppTab[]> {
return this.recentApps;
}
fetch(): Observable<any> {
return this.ipc.request("fetchPlatformData");
}
getOpenProjects(): Observable<Project[]> {
return combineLatest(this.projects, this.openProjects).pipe(
map(data => {
// If either of them is null, then we don't know which projects are open
if (~data.indexOf(null)) {
return null;
}
const [all, open] = data;
if (open.length === 0) {
return [];
}
const mapped = all.reduce((acc, item) => ({...acc, [item.id]: item}), {});
return open.map(id => mapped[id] || undefined).filter(v => v);
})
);
}
private listen(key: string) {
return this.ipc.watch("watchUserRepository", {key});
}
private patch(data: { [key: string]: any }) {
return this.ipc.request("patchUserRepository", data);
}
setNodeExpansion(nodesToExpand: string | string [], isExpanded: boolean): void {
this.expandedNodes.pipe(
take(1)
).subscribe(expandedNodes => {
const patch = new Set(expandedNodes);
let modified = false;
[].concat(nodesToExpand).forEach((item) => {
const oldSize = patch.size;
isExpanded ? patch.add(item) : patch.delete(item);
if (oldSize !== patch.size) {
modified = true;
}
});
if (modified) {
this.patch({
expandedNodes: Array.from(patch)
});
}
});
}
addOpenProjects(projectIDs: string[], expandNodes: boolean = false) {
return this.openProjects.pipe(
take(1)
).toPromise().then(openProjects => {
const missing = projectIDs.filter(id => openProjects.indexOf(id) === -1);
if (missing.length === 0) {
return Promise.resolve();
}
if (expandNodes) {
this.auth.getActive().pipe(
take(1)
).subscribe((active) => {
// Expand added projects
this.setNodeExpansion(missing.concat(active.getHash()), true);
});
}
return this.patch({openProjects: openProjects.concat(missing)}).toPromise();
});
}
removeOpenProjects(...projectIDs: string[]) {
return this.openProjects.pipe(
take(1)
).toPromise().then(openProjects => {
const update = openProjects.filter(id => projectIDs.indexOf(id) === -1);
if (update.length !== openProjects.length) {
return this.patch({openProjects: update}).toPromise();
}
return Promise.resolve();
});
}
getExpandedNodes() {
return this.expandedNodes;
}
createApp(appID: string, content: string): Promise<string> {
const appContent = Yaml.safeLoad(content, { json: true } as LoadOptions);
return this.ipc.request("createPlatformApp", {
id: appID,
content: JSON.stringify(appContent, null, 4)
}).toPromise();
}
saveAppRevision(appID: string, content: string, revisionNote?: string): Promise<string> {
const appContent = Yaml.safeLoad(content, {json: true} as LoadOptions);
if (typeof revisionNote === "string") {
appContent["sbg:revisionNotes"] = revisionNote;
}
content = JSON.stringify(appContent, null, 4);
return this.ipc.request("saveAppRevision", {
id: appID,
content: content
}).toPromise();
}
pushRecentApp(recentTabData: RecentAppTab, limit = 20): Promise<any> {
return this.getRecentApps().pipe(
map(apps => apps || []),
take(1)
).toPromise().then((entries) => {
const update = [recentTabData].concat(entries).filter((val, idx, arr) => {
const duplicateIndex = arr.findIndex(el => el.id === val.id);
return duplicateIndex === idx;
}).slice(0, limit);
return this.patch({recentApps: update}).toPromise();
});
}
setOpenTabs(openTabs: TabData<any>[]): Promise<any> {
return this.patch({openTabs}).toPromise();
}
getUpdates(appIDs: string[]): Promise<{
id: string;
name: string;
revision: number;
}[]> {
return this.ipc.request("getAppUpdates", {appIDs})
.pipe(
catchError(err => {
if (err.error && err.error.status === 404) {
return of([]);
}
return _throw(err);
})
)
.toPromise();
}
getApp(id: string, forceFetch = false): Promise<RawApp> {
return this.ipc.request("getPlatformApp", {id, forceFetch}).toPromise().then((appText: string) => {
return JSON.parse(appText);
});
}
getAppContent(id: string, forceFetch = false): Promise<string> {
return this.ipc.request("getPlatformApp", {id, forceFetch}).toPromise();
}
getProject(projectSlug: string): Promise<Project> {
return this.ipc.request("getProject", projectSlug).toPromise();
}
searchProjects(name: string): Observable<Project[]> {
return this.ipc.request("searchUserProjects", name)
.pipe();
}
fetchAppsForProjects(projectIds: string[]): Observable<App[]> {
return this.ipc.request("getAppsForProjects", projectIds)
.pipe(
catchError<App[], App[]>(() => []),
withLatestFrom(this.apps),
map(([newApps, currentApps]) => {
const filtered = currentApps.filter((value) => {
return !newApps.find(app => value.id === app.id);
});
return newApps.concat(filtered);
}),
switchMap(allApps => {
return this.patch({apps: allApps});
})
);
}
searchAppsFromOpenProjects(substring?: string): Observable<App[]> {
const term = substring.toLowerCase();
return this.getOpenProjects().pipe(
map(projects => projects || []),
flatMap(openProjects => {
const openProjectIDs = openProjects.map(project => project.id);
return this.getPrivateApps().pipe(
map(apps => {
return (apps || []).filter(app => {
if (openProjectIDs.indexOf(app.project) === -1) {
return false;
}
if (!substring) {
return true;
}
const appID = app.id.toLowerCase();
const appName = app.label.toLowerCase();
return appID.indexOf(term) !== -1 || appName.indexOf(term) !== -1;
});
})
);
})
);
}
searchPublicApps(substring?: string): Observable<App[]> {
const term = substring.toLowerCase();
return this.getPublicApps().pipe(
map(apps => {
return (apps || []).filter(app => {
if (!substring) {
return true;
}
const appID = app.id.toLowerCase();
const appName = app.label.toLowerCase();
return appID.indexOf(term) !== -1 || appName.indexOf(term) !== -1;
});
})
);
}
getAppMeta<T extends keyof AppMetaEntry>(appID: string, key: T): Observable<AppMetaEntry[T]> {
return this.appMeta.pipe(
map(meta => {
if (meta === null) {
return meta;
}
const data = meta[appID];
if (key && data) {
return data[key];
}
})
);
}
patchAppMeta(appID: string, key: keyof AppMetaEntry, value: any): Promise<any> {
return this.ipc.request("patchAppMeta", {
profile: "user",
appID,
key,
value
}).toPromise();
}
} | the_stack |
import React, { Component } from "react";
import {
withStyles,
Paper,
Typography,
Button,
TextField,
Fade,
Link,
CircularProgress,
Tooltip,
Dialog,
DialogTitle,
DialogActions,
DialogContent,
List,
ListItem,
ListItemText,
ListItemAvatar,
ListItemSecondaryAction,
IconButton,
InputAdornment
} from "@material-ui/core";
import { styles } from "./WelcomePage.styles";
import Mastodon from "megalodon";
import { SaveClientSession } from "../types/SessionData";
import {
createHyperspaceApp,
getRedirectAddress,
inDisallowedDomains,
instancesBearerKey
} from "../utilities/login";
import { parseUrl } from "query-string";
import { getConfig } from "../utilities/settings";
import { isDarwinApp } from "../utilities/desktop";
import axios from "axios";
import { withSnackbar, withSnackbarProps } from "notistack";
import { Config } from "../types/Config";
import {
getAccountRegistry,
loginWithAccount,
removeAccountFromRegistry
} from "../utilities/accounts";
import { MultiAccount } from "../types/Account";
import AccountCircleIcon from "@material-ui/icons/AccountCircle";
import CloseIcon from "@material-ui/icons/Close";
/**
* Basic props for Welcome page
*/
interface IWelcomeProps extends withSnackbarProps {
classes: any;
}
/**
* Basic state for welcome page
*/
interface IWelcomeState {
/**
* The custom-defined URL to the logo to display
*/
logoUrl?: string;
/**
* The custom-defined URL to the background image to display
*/
backgroundUrl?: string;
/**
* The custom-defined brand name of this app
*/
brandName?: string;
/**
* The custom-defined server address to register to
*/
registerBase?: string;
/**
* Whether this version of Hyperspace has federation
*/
federates?: boolean;
/**
* Whether Hyperspace is ready to get the auth code
*/
proceedToGetCode: boolean;
/**
* The currently "logged-in" user after the first step
*/
user: string;
/**
* Whether the user's input errors
*/
userInputError: boolean;
/**
* The user input error message, if any
*/
userInputErrorMessage: string;
/**
* The app's client ID, if registered
*/
clientId?: string;
/**
* The app's client secret, if registered
*/
clientSecret?: string;
/**
* The authorization URL provided by Mastodon from the
* client ID and secret
*/
authUrl?: string;
/**
* Whether a previous login attempt is present
*/
foundSavedLogin: boolean;
/**
* Whether Hyperspace is in the process of authorizing
*/
authorizing: boolean;
/**
* The custom-defined license for the Hyperspace source code
*/
license?: string;
/**
* The custom-defined URL to the source code of Hyperspace
*/
repo?: string;
/**
* The default address to redirect to. Used in login inits and
* when the authorization code completes.
*/
defaultRedirectAddress: string;
/**
* Whether the redirect address is set to 'dynamic'.
*/
redirectAddressIsDynamic: boolean;
/**
* Whether the authorization dialog for the emergency login is
* open.
*/
openAuthDialog: boolean;
/**
* The authorization code to fetch an access token with
*/
authCode: string;
/**
* Whether the Emergency Mode has been initiated
*/
emergencyMode: boolean;
/**
* The current app version
*/
version: string;
/**
* Whether we are in the process of adding a new account or not
*/
willAddAccount: boolean;
}
/**
* The base class for the Welcome page.
*
* The Welcome page is responsible for handling the registration,
* login, and authorization of accounts into the Hyperspace app.
*/
class WelcomePage extends Component<IWelcomeProps, IWelcomeState> {
/**
* The associated Mastodon client to handle logins/authorizations
* with
*/
client: any;
/**
* Construct the state and other components of the Welcome page
* @param props The properties passed onto the page
*/
constructor(props: any) {
super(props);
// Set up our state
this.state = {
proceedToGetCode: false,
user: "",
userInputError: false,
foundSavedLogin: false,
authorizing: false,
userInputErrorMessage: "",
defaultRedirectAddress: "",
redirectAddressIsDynamic: false,
openAuthDialog: false,
authCode: "",
emergencyMode: false,
version: "",
willAddAccount: false
};
// Read the configuration data and update the state
getConfig()
.then((result: any) => {
if (result !== undefined) {
let config: Config = result;
// Warn if the location is dynamic (unexpected behavior)
if (config.location === "dynamic") {
console.warn(
"Redirect URI is set to dynamic, which may affect how sign-in works for some users. Careful!"
);
}
// Reset to mastodon.online if the location is a disallowed
// domain.
if (
inDisallowedDomains(result.registration.defaultInstance)
) {
console.warn(
`The default instance field in config.json contains an unsupported domain (${result.registration.defaultInstance}), so it's been reset to mastodon.online.`
);
result.registration.defaultInstance = "mastodon.online";
}
// Update the state as per the configuration
this.setState({
logoUrl: config.branding?.logo ?? "logo.png",
backgroundUrl:
config.branding?.background ?? "background.png",
brandName: config.branding?.name ?? "Hyperspace",
registerBase:
result.registration?.defaultInstance ?? "",
federates: config.federation.universalLogin,
license: config.license.url,
repo: config.repository,
defaultRedirectAddress:
config.location !== "dynamic"
? config.location
: `https://${window.location.host}`,
redirectAddressIsDynamic: config.location === "dynamic",
version: config.version
});
}
})
// Print an error if the config wasn't found.
.catch(() => {
console.error(
"config.json is missing. If you want to customize Hyperspace, please include config.json"
);
});
}
/**
* Look for any existing logins and tokens before presenting
* the login page
*/
componentDidMount() {
if (localStorage.getItem("login")) {
this.getSavedSession();
this.setState({
foundSavedLogin: true
});
this.checkForToken();
}
}
/**
* Update the user field in the state
* @param user The string to update the state to
*/
updateUserInfo(user: string) {
this.checkForErrors(user);
this.setState({ user });
}
/**
* Update the auth code in the state
* @param code The authorization code to update the state to
*/
updateAuthCode(code: string) {
this.setState({ authCode: code });
}
/**
* Toggle the visibility of the authorization dialog
*/
toggleAuthDialog() {
this.setState({ openAuthDialog: !this.state.openAuthDialog });
}
/**
* Determine whether the app is ready to open the authorization
* process.
*/
readyForAuth() {
return localStorage.getItem("baseurl") !== null;
}
/**
* Clear the current access token and base URL
*/
clear() {
localStorage.removeItem("access_token");
localStorage.removeItem("baseurl");
}
/**
* Get the current saved session from the previous login
* attempt and update the state
*/
getSavedSession() {
if (localStorage.getItem("login") === null) {
return;
}
let loginData = localStorage.getItem("login") as string;
let session: SaveClientSession = JSON.parse(loginData);
this.setState({
clientId: session.clientId,
clientSecret: session.clientSecret,
authUrl: session.authUrl,
emergencyMode: session.emergency
});
}
/**
* Start the emergency login mode.
*/
startEmergencyLogin() {
if (!this.state.emergencyMode) {
this.createEmergencyLogin();
}
this.toggleAuthDialog();
}
/**
* Start the registration process.
* @returns A URL pointing to the signup page of the base as defined
* in the config's `registerBase` field
*/
startRegistration() {
return this.state.registerBase
? "https://" + this.state.registerBase + "/auth/sign_up"
: "https://joinmastodon.org/#getting-started";
}
/**
* Watch the keyboard and start the login procedure if the user
* presses the ENTER/RETURN key
* @param event The keyboard event
*/
watchUsernameField(event: any) {
if (event.keyCode === 13) this.startLogin();
}
/**
* Watch the keyboard and start the emergency login auth procedure
* if the user presses the ENTER/RETURN key
* @param event The keyboard event
*/
watchAuthField(event: any) {
if (event.keyCode === 13) this.authorizeEmergencyLogin();
}
/**
* Get the "logged-in" user by reading the username string
* from the first field on the login page.
* @param user The user string to parse
* @returns The base URL of the user
*/
getLoginUser(user: string) {
// Did the user include "@"? They probably are not from the
// server defined in config
if (user.includes("@")) {
if (this.state.federates) {
let newUser = user;
this.setState({ user: newUser });
return "https://" + newUser.split("@")[1];
} else {
let newUser = `${user}@${this.state.registerBase ??
"mastodon.online"}`;
this.setState({ user: newUser });
return (
"https://" + (this.state.registerBase ?? "mastodon.online")
);
}
}
// Otherwise, treat them as if they're from the server
else {
let newUser = `${user}@${this.state.registerBase ??
"mastodon.online"}`;
this.setState({ user: newUser });
return "https://" + (this.state.registerBase ?? "mastodon.online");
}
}
/**
* Check the user string for any errors and then create a client with an
* ID and secret to start the authorization process.
* @param bypassChecks Whether to bypass the checks in place.
*/
startLogin(bypassChecks: boolean = false) {
// Check if we have errored
let error = this.checkForErrors(this.state.user, bypassChecks);
// If we didn't, create the Hyperspace app to register onto that Mastodon
// server.
if (!error) {
// Define the app's scopes and base URL
const scopes = "read write follow";
const baseurl = this.getLoginUser(this.state.user);
localStorage.setItem("baseurl", baseurl);
// Create the Hyperspace app
createHyperspaceApp(
this.state.brandName ?? "Hyperspace",
scopes,
baseurl,
getRedirectAddress(this.state.defaultRedirectAddress)
)
// If we succeeded, create a login attempt for later reference
.then((resp: any) => {
let saveSessionForCrashing: SaveClientSession = {
clientId: resp.clientId,
clientSecret: resp.clientSecret,
authUrl: resp.url,
emergency: false
};
localStorage.setItem(
"login",
JSON.stringify(saveSessionForCrashing)
);
// Finally, update the state
this.setState({
clientId: resp.clientId,
clientSecret: resp.clientSecret,
authUrl: resp.url,
proceedToGetCode: true
});
})
.catch((err: Error) => {
this.props.enqueueSnackbar(
`Failed to register app at ${baseurl.replace(
"https://",
""
)}`
);
console.error(err);
});
}
}
/**
* Create an emergency mode login. This is usually initiated when the
* "click-to-authorize" method fails and the user needs to copy and paste
* an authorization code manually.
*/
createEmergencyLogin() {
console.log("Creating an emergency login...");
// Set up the scopes and base URL
const scopes = "read write follow";
const baseurl =
localStorage.getItem("baseurl") ||
this.getLoginUser(this.state.user);
// Register the Mastodon app with the Mastodon server
Mastodon.registerApp(
this.state.brandName ?? "Hyperspace",
{
scopes: scopes
},
baseurl
)
// If we succeed, create a login attempt for later reference
.then((appData: any) => {
let saveSessionForCrashing: SaveClientSession = {
clientId: appData.clientId,
clientSecret: appData.clientSecret,
authUrl: appData.url,
emergency: true
};
localStorage.setItem(
"login",
JSON.stringify(saveSessionForCrashing)
);
// Finally, update the state
this.setState({
clientId: appData.clientId,
clientSecret: appData.clientSecret,
authUrl: appData.url
});
});
}
/**
* Open the URL to redirect to an authorization sequence from an emergency
* login.
*
* Since Hyperspace reads the auth code from the URL, we need to redirect to
* a URL with the code inside to trigger an auth
*/
authorizeEmergencyLogin() {
let redirAddress =
this.state.defaultRedirectAddress === "desktop"
? "hyperspace://hyperspace/app/"
: this.state.defaultRedirectAddress;
window.location.href = `${redirAddress}/?code=${this.state.authCode}#/`;
}
/**
* Restore a login attempt from a session
*/
resumeLogin() {
let loginData = localStorage.getItem("login");
if (loginData) {
let session: SaveClientSession = JSON.parse(loginData);
this.setState({
clientId: session.clientId,
clientSecret: session.clientSecret,
authUrl: session.authUrl,
emergencyMode: session.emergency,
proceedToGetCode: true
});
}
}
/**
* Check the user input string for any possible errors
* @param username The username to read and check for errors
* @param bypassesInstanceNameCheck Whether to bypass the instance name validation process. Defaults to false.
* @return Whether an error has occured in the validation.
*/
checkForErrors(
username: string,
bypassesInstanceNameCheck: boolean = false
): boolean {
let userInputError = false;
let userInputErrorMessage = "";
// Is the user string blank?
if (username === "") {
userInputError = true;
userInputErrorMessage = "Username cannot be blank.";
this.setState({ userInputError, userInputErrorMessage });
return true;
} else {
if (username.includes("@")) {
if (this.state.federates && this.state.federates === true) {
let baseUrl = username.split("@")[1];
// Is the user's domain in the disallowed list?
if (inDisallowedDomains(baseUrl)) {
this.setState({
userInputError: true,
userInputErrorMessage: `Signing in with an account from ${baseUrl} isn't supported.`
});
return true;
} else {
if (bypassesInstanceNameCheck) {
return false;
}
// Are we unable to ping the server?
axios
.get(
"https://instances.social/api/1.0/instances/show?name=" +
baseUrl,
{
headers: {
Authorization: `Bearer ${instancesBearerKey}`
}
}
)
.catch((err: Error) => {
let userInputError = true;
let userInputErrorMessage =
"We couldn't recognize this instance.";
this.setState({
userInputError,
userInputErrorMessage
});
return true;
});
}
} else if (
username.includes(
this.state.registerBase ?? "mastodon.online"
)
) {
this.setState({ userInputError, userInputErrorMessage });
return false;
} else {
userInputError = true;
userInputErrorMessage =
"You cannot sign in with this username.";
this.setState({ userInputError, userInputErrorMessage });
return true;
}
} else {
this.setState({ userInputError, userInputErrorMessage });
return false;
}
this.setState({ userInputError, userInputErrorMessage });
return false;
}
}
/**
* Read the URL and determine whether or not there's an auth code
* in the URL. If there is, try to authorize and get the access
* token for storage.
*/
checkForToken() {
let location = window.location.href;
// Is there an auth code?
if (location.includes("?code=")) {
let code = parseUrl(location).query.code as string;
this.setState({ authorizing: true });
let loginData = localStorage.getItem("login");
// If there's login data, try to fetch an access token
if (loginData) {
let clientLoginSession: SaveClientSession = JSON.parse(
loginData
);
getConfig().then((resp: any) => {
if (resp === undefined) {
return;
}
let conf: Config = resp;
let redirectUrl: string | undefined =
this.state.emergencyMode ||
clientLoginSession.authUrl.includes(
"urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob"
)
? undefined
: getRedirectAddress(conf.location);
Mastodon.fetchAccessToken(
clientLoginSession.clientId,
clientLoginSession.clientSecret,
code,
localStorage.getItem("baseurl") as string,
redirectUrl
)
.then((tokenData: any) => {
localStorage.setItem(
"access_token",
tokenData.access_token
);
window.location.href =
window.location.protocol === "hyperspace:"
? "hyperspace://hyperspace/app/"
: this.state.defaultRedirectAddress;
})
.catch((err: Error) => {
this.props.enqueueSnackbar(
`Couldn't authorize ${this.state.brandName ??
"Hyperspace"}: ${err.name}`,
{ variant: "error" }
);
console.error(err.message);
});
});
}
}
}
/**
* Redirect to the app's main view after a login.
*/
redirectToApp() {
window.location.href =
window.location.protocol === "hyperspace:"
? "hyperspace://hyperspace/app/"
: this.state.redirectAddressIsDynamic
? `https://${window.location.host}/#/`
: this.state.defaultRedirectAddress + "/#/";
}
/**
* Render the title bar for macOS
*/
titlebar() {
const { classes } = this.props;
if (isDarwinApp()) {
return (
<div className={classes.titleBarRoot}>
<Typography className={classes.titleBarText}>
{this.state.brandName ?? "Hyperspace"}
</Typography>
</div>
);
}
}
/**
* Show the multi-user account panel
*/
showMultiAccount() {
const { classes } = this.props;
return (
<div>
<Typography variant="h5">Select an account</Typography>
<Typography>from the list below or add a new one</Typography>
<List>
{getAccountRegistry().map(
(account: MultiAccount, index: number) => (
<ListItem
onClick={() => {
loginWithAccount(account);
this.redirectToApp();
}}
button={true}
>
<ListItemAvatar>
<AccountCircleIcon color="action" />
</ListItemAvatar>
<ListItemText
primary={`@${account.username}`}
secondary={account.host}
/>
<ListItemSecondaryAction>
<IconButton
onClick={(e: any) => {
e.preventDefault();
removeAccountFromRegistry(index);
window.location.reload();
}}
>
<CloseIcon />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
)
)}
</List>
<div className={classes.middlePadding} />
<Button
onClick={() => {
this.setState({ willAddAccount: true });
this.clear();
}}
color={"primary"}
variant={"contained"}
>
Add Account
</Button>
</div>
);
}
/**
* Show the main landing panel
*/
showLanding() {
const { classes } = this.props;
return (
<div>
<Typography variant="h5">Sign in</Typography>
<Typography>with your fediverse account</Typography>
<div className={classes.middlePadding} />
<TextField
variant="outlined"
label="Username"
fullWidth
placeholder="example@mastodon.example"
onChange={event => this.updateUserInfo(event.target.value)}
onKeyDown={event => this.watchUsernameField(event)}
error={this.state.userInputError}
InputProps={{
startAdornment: (
<InputAdornment position="start">@</InputAdornment>
)
}}
/>
{this.state.userInputError ? (
<Typography color="error">
{this.state.userInputErrorMessage}
{this.state.userInputErrorMessage ===
"We couldn't recognize this instance." ? (
<span>
<br />
<Link
// className={classes.welcomeLink}
onClick={() => this.startLogin(true)}
>
Try anyway
</Link>
</span>
) : null}
</Typography>
) : null}
<br />
{this.state.registerBase && this.state.federates ? (
<Typography variant="caption">
Not from{" "}
<b>{this.state.registerBase ?? "noinstance"}</b>? Sign
in with your{" "}
<Link
href="https://docs.joinmastodon.org/user/signup/#address"
target="_blank"
rel="noopener noreferrer"
color="secondary"
>
full username
</Link>
.
</Typography>
) : null}
<br />
{this.state.foundSavedLogin ? (
<Typography>
Signing in from a previous session?{" "}
<Link
className={classes.welcomeLink}
onClick={() => this.resumeLogin()}
>
Continue login
</Link>
.
</Typography>
) : null}
<div className={classes.middlePadding} />
<div style={{ display: "flex" }}>
<Tooltip title="Create account on site">
<Button
href={this.startRegistration()}
target="_blank"
rel="noreferrer"
>
Create account
</Button>
</Tooltip>
<div className={classes.flexGrow} />
<Tooltip title="Continue sign-in">
<Button
color="primary"
variant="contained"
onClick={() => this.startLogin()}
>
Next
</Button>
</Tooltip>
</div>
</div>
);
}
/**
* Show the login auth panel
*/
showLoginAuth() {
const { classes } = this.props;
return (
<div>
<Typography variant="h5">
Howdy, {this.state.user?.split("@")[0] ?? "user"}
</Typography>
<Typography>
To continue, finish signing in on your instance's website
and authorize {this.state.brandName ?? "Hyperspace"}.
</Typography>
<div className={classes.middlePadding} />
<div style={{ display: "flex" }}>
<div className={classes.flexGrow} />
<Button
color="primary"
variant="contained"
size="large"
href={this.state.authUrl ?? ""}
>
Authorize
</Button>
<div className={classes.flexGrow} />
</div>
<div className={classes.middlePadding} />
<Typography>
Having trouble signing in?{" "}
<Link
onClick={() => this.startEmergencyLogin()}
className={classes.welcomeLink}
>
Sign in with a code.
</Link>
</Typography>
</div>
);
}
/**
* Show the emergency login panel
*/
showAuthDialog() {
return (
<Dialog
open={this.state.openAuthDialog}
disableBackdropClick
disableEscapeKeyDown
maxWidth="sm"
fullWidth={true}
>
<DialogTitle>Authorize with a code</DialogTitle>
<DialogContent>
<Typography paragraph>
If you're having trouble authorizing Hyperspace, you can
manually request for an authorization code. Click
'Request Code' and then paste the code in the
authorization code box to continue.
</Typography>
<Button
color="primary"
variant="contained"
href={this.state.authUrl ?? ""}
target="_blank"
rel="noopener noreferrer"
>
Request Code
</Button>
<br />
<br />
<TextField
variant="outlined"
label="Authorization code"
fullWidth
onChange={event =>
this.updateAuthCode(event.target.value)
}
onKeyDown={event => this.watchAuthField(event)}
/>
</DialogContent>
<DialogActions>
<Button onClick={() => this.toggleAuthDialog()}>
Cancel
</Button>
<Button
color="secondary"
onClick={() => this.authorizeEmergencyLogin()}
>
Authorize
</Button>
</DialogActions>
</Dialog>
);
}
/**
* Show the authorizing panel
*/
showAuthorizationLoader() {
const { classes } = this.props;
return (
<div>
<Typography variant="h5">Authorizing</Typography>
<Typography>
Please wait while Hyperspace authorizes with your instance.
This shouldn't take long...
</Typography>
<div className={classes.middlePadding} />
<div style={{ display: "flex" }}>
<div className={classes.flexGrow} />
<CircularProgress />
<div className={classes.flexGrow} />
</div>
<div className={classes.middlePadding} />
</div>
);
}
/**
* Render the page
*/
render() {
const { classes } = this.props;
return (
<div>
{this.titlebar()}
<div
className={classes.root}
style={{
backgroundImage: `url(${this.state.backgroundUrl ??
"background.png"})`
}}
>
<Paper className={classes.paper}>
<img
className={classes.logo}
alt={this.state.brandName ?? "Hyperspace"}
src={this.state.logoUrl ?? "logo.png"}
/>
<br />
<Fade in={true}>
{this.state.authorizing
? this.showAuthorizationLoader()
: this.state.proceedToGetCode
? this.showLoginAuth()
: getAccountRegistry().length > 0 &&
!this.state.willAddAccount
? this.showMultiAccount()
: this.showLanding()}
</Fade>
<br />
<Typography variant="caption">
© {new Date().getFullYear()}{" "}
{this.state.brandName &&
this.state.brandName !== "Hyperspace"
? `${this.state.brandName} developers and the `
: ""}{" "}
<Link
className={classes.welcomeLink}
href="https://hyperspace.marquiskurt.net"
target="_blank"
rel="noreferrer"
>
Hyperspace
</Link>{" "}
developers. All rights reserved.
</Typography>
<Typography variant="caption">
{this.state.repo ? (
<span>
<Link
className={classes.welcomeLink}
href={
this.state.repo ??
"https://github.com/hyperspacedev"
}
target="_blank"
rel="noreferrer"
>
Source code
</Link>{" "}
|{" "}
</span>
) : null}
<Link
className={classes.welcomeLink}
href={
this.state.license ??
"https://thufie.lain.haus/NPL.html"
}
target="_blank"
rel="noreferrer"
>
License
</Link>{" "}
|{" "}
<Link
className={classes.welcomeLink}
href="https://github.com/hyperspacedev/hyperspace/issues/new"
target="_blank"
rel="noreferrer"
>
File an Issue
</Link>
</Typography>
<Typography variant="caption" color="textSecondary">
{this.state.brandName ?? "Hypersapce"} v.
{this.state.version}{" "}
{this.state.brandName &&
this.state.brandName !== "Hyperspace"
? "(Hyperspace-like)"
: null}
</Typography>
</Paper>
{this.showAuthDialog()}
</div>
</div>
);
}
}
export default withStyles(styles)(withSnackbar(WelcomePage)); | the_stack |
import { AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild } from '@angular/core';
import { ChartDataSets, ChartOptions, ChartPoint } from 'chart.js';
import { BaseChartDirective, Color, Label } from 'ng2-charts';
import { ExerciseScoresChartService, ExerciseScoresDTO } from 'app/overview/visualizations/exercise-scores-chart.service';
import { AlertService } from 'app/core/util/alert.service';
import { onError } from 'app/shared/util/global.utils';
import { finalize } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { ExerciseType } from 'app/entities/exercise.model';
import { round } from 'app/shared/util/utils';
import { sortBy } from 'lodash-es';
// this exercise information is needed for tooltip generation and to navigate to an exercise page
export class CustomChartPoint implements ChartPoint {
y: number;
exerciseId: number;
exerciseTitle: string;
exerciseType: ExerciseType;
}
@Component({
selector: 'jhi-exercise-scores-chart',
templateUrl: './exercise-scores-chart.component.html',
styleUrls: ['./exercise-scores-chart.component.scss'],
})
export class ExerciseScoresChartComponent implements AfterViewInit, OnDestroy {
@Input()
courseId: number;
isLoading = false;
public exerciseScores: ExerciseScoresDTO[] = [];
@ViewChild(BaseChartDirective)
chartDirective: BaseChartDirective;
chartInstance: Chart;
@ViewChild('chartDiv')
chartDiv: ElementRef;
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private alertService: AlertService,
private exerciseScoresChartService: ExerciseScoresChartService,
private translateService: TranslateService,
) {}
ngOnDestroy() {
// important to prevent memory leaks
this.chartInstance.destroy();
}
ngAfterViewInit() {
this.chartInstance = this.chartDirective.chart;
this.activatedRoute.parent!.params.subscribe((params) => {
this.courseId = +params['courseId'];
if (this.courseId) {
this.loadDataAndInitializeChart();
}
});
}
private loadDataAndInitializeChart() {
this.isLoading = true;
this.exerciseScoresChartService
.getExerciseScoresForCourse(this.courseId)
.pipe(
finalize(() => {
this.isLoading = false;
}),
)
.subscribe(
(exerciseScoresResponse) => {
this.exerciseScores = exerciseScoresResponse.body!;
this.initializeChart();
},
(errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse),
);
}
private initializeChart() {
// we calculate the chart width depending on the number of exercises we have to show. If you look into
// exercise-scores-chart.component.scss you will see that we show a horizontal navigation bar when the
// chart has reached a certain width
let chartWidth = 80 * this.exerciseScores.length;
if (chartWidth < 1200) {
chartWidth = 1200;
}
this.chartDiv.nativeElement.setAttribute('style', `width: ${chartWidth}px;`);
this.chartInstance.resize();
// we show all the exercises ordered by their release data
const sortedExerciseScores = sortBy(this.exerciseScores, (exerciseScore) => exerciseScore.releaseDate);
this.addData(this.chartInstance, sortedExerciseScores);
}
private addData(chart: Chart, exerciseScoresDTOs: ExerciseScoresDTO[]) {
for (const exerciseScoreDTO of exerciseScoresDTOs) {
const extraInformation = {
exerciseId: exerciseScoreDTO.exerciseId,
exerciseTitle: exerciseScoreDTO.exerciseTitle,
exerciseType: exerciseScoreDTO.exerciseType,
};
chart.data.labels!.push(exerciseScoreDTO.exerciseTitle!);
// from each dto we generate a data point for each of three data sets
(chart.data.datasets![0].data as CustomChartPoint[])!.push({
y: exerciseScoreDTO.scoreOfStudent,
...extraInformation,
} as CustomChartPoint);
(chart.data.datasets![1].data as CustomChartPoint[])!.push({
y: exerciseScoreDTO.averageScoreAchieved,
...extraInformation,
} as CustomChartPoint);
(chart.data.datasets![2].data as CustomChartPoint[])!.push({
y: exerciseScoreDTO.maxScoreAchieved,
...extraInformation,
} as CustomChartPoint);
}
this.chartInstance.update();
}
/**
* We navigate to the exercise sub page when the user clicks on a data point
*/
navigateToExercise(exerciseId: number) {
this.router.navigate(['courses', this.courseId, 'exercises', exerciseId]);
}
/* ------------------------------ Settings for the Chart ------------------------------ */
/**
* For each exercise we show three data points, hence we need three data sets:
* 1.) Score achieved by the user in the exercise
* 2.) Average score achieved by all users in the exercise
* 3.) Best score achieved by a user in the exercise
*/
public dataSets: ChartDataSets[] = [
// score of logged in user in exercise
{
fill: false,
data: [],
label: this.translateService.instant('artemisApp.exercise-scores-chart.yourScoreLabel'),
pointStyle: 'circle',
borderWidth: 3,
lineTension: 0,
spanGaps: true,
},
// average score in exercise
{
fill: false,
data: [],
label: this.translateService.instant('artemisApp.exercise-scores-chart.averageScoreLabel'),
pointStyle: 'rect',
borderWidth: 3,
lineTension: 0,
spanGaps: true,
borderDash: [1, 1],
},
// best score in exercise
{
fill: false,
data: [],
label: this.translateService.instant('artemisApp.exercise-scores-chart.maximumScoreLabel'),
pointStyle: 'triangle',
borderWidth: 3,
lineTension: 0,
spanGaps: true,
borderDash: [15, 3, 3, 3],
},
];
public labels: Label[] = this.exerciseScores.map((exerciseScoreDTO) => exerciseScoreDTO.exerciseTitle!);
public chartOptions: ChartOptions = {
// we show the pointer to indicate to the user that a data point is clickable (navigation to exercise)
onHover: (event: any, chartElement) => {
event.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
},
// when the user clicks on a data point, we navigate to the subpage of the corresponding exercise
onClick: (evt) => {
const point: any = this.chartInstance.getElementAtEvent(evt)[0];
if (point) {
const value: any = this.chartInstance.data.datasets![point._datasetIndex]!.data![point._index];
if (value.exerciseId) {
this.navigateToExercise(value.exerciseId);
}
}
},
tooltips: {
callbacks: {
label(tooltipItem, data) {
let label = data.datasets![tooltipItem.datasetIndex!].label || '';
if (label) {
label += ': ';
}
label += round(tooltipItem.yLabel as number, 2);
label += ' %';
return label;
},
footer(tooltipItem, data) {
const dataset = data.datasets![tooltipItem[0].datasetIndex!].data![tooltipItem[0].index!];
const exerciseType = (dataset as any).exerciseType;
return [`Exercise Type: ${exerciseType}`];
},
},
},
responsive: true,
maintainAspectRatio: false,
title: {
display: false,
},
legend: {
position: 'left',
},
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: this.translateService.instant('artemisApp.exercise-scores-chart.yAxis'),
fontSize: 12,
},
ticks: {
suggestedMax: 100,
suggestedMin: 0,
beginAtZero: true,
precision: 0,
fontSize: 12,
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: this.translateService.instant('artemisApp.exercise-scores-chart.xAxis'),
fontSize: 12,
},
ticks: {
autoSkip: false,
fontSize: 12,
callback(exerciseTitle: string) {
if (exerciseTitle.length > 20) {
// shorten exercise title if too long (will be displayed in full in tooltip)
return exerciseTitle.substr(0, 20) + '...';
} else {
return exerciseTitle;
}
},
},
},
],
},
};
public chartColors: Color[] = [
// score of logged in user in exercise
{
borderColor: 'skyBlue',
backgroundColor: 'skyBlue',
hoverBackgroundColor: 'black',
hoverBorderColor: 'black',
},
// average score in exercise
{
borderColor: 'salmon',
backgroundColor: 'salmon',
hoverBackgroundColor: 'black',
hoverBorderColor: 'black',
},
// best score in exercise
{
borderColor: 'limeGreen',
backgroundColor: 'limeGreen',
hoverBackgroundColor: 'black',
hoverBorderColor: 'black',
},
];
} | the_stack |
require('source-map-support').install();
import {SourceMapGenerator} from 'source-map';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import {TranspilerBase} from './base';
import mkdirP from './mkdirp';
import CallTranspiler from './call';
import DeclarationTranspiler from './declaration';
import ExpressionTranspiler from './expression';
import ModuleTranspiler from './module';
import StatementTranspiler from './statement';
import TypeTranspiler from './type';
import LiteralTranspiler from './literal';
import {FacadeConverter} from './facade_converter';
import * as dartStyle from 'dart-style';
export interface TranspilerOptions {
/**
* Fail on the first error, do not collect multiple. Allows easier debugging as stack traces lead
* directly to the offending line.
*/
failFast?: boolean;
/** Whether to generate 'library a.b.c;' names from relative file paths. */
generateLibraryName?: boolean;
/** Whether to generate source maps. */
generateSourceMap?: boolean;
/** A tsconfig.json to use to configure TypeScript compilation. */
tsconfig?: string;
/**
* A base path to relativize absolute file paths against. This is useful for library name
* generation (see above) and nicer file names in error messages.
*/
basePath?: string;
/**
* Translate calls to builtins, i.e. seemlessly convert from `Array` to `List`, and convert the
* corresponding methods. Requires type checking.
*/
translateBuiltins?: boolean;
/**
* Enforce conventions of public/private keyword and underscore prefix
*/
enforceUnderscoreConventions?: boolean;
}
export const COMPILER_OPTIONS: ts.CompilerOptions = {
allowNonTsExtensions: true,
experimentalDecorators: true,
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES6,
};
export class Transpiler {
private output: Output;
private currentFile: ts.SourceFile;
// Comments attach to all following AST nodes before the next 'physical' token. Track the earliest
// offset to avoid printing comments multiple times.
private lastCommentIdx: number = -1;
private errors: string[] = [];
private transpilers: TranspilerBase[];
private fc: FacadeConverter;
constructor(private options: TranspilerOptions = {}) {
// TODO: Remove the angular2 default when angular uses typingsRoot.
this.fc = new FacadeConverter(this);
this.transpilers = [
new CallTranspiler(this, this.fc), // Has to come before StatementTranspiler!
new DeclarationTranspiler(this, this.fc, options.enforceUnderscoreConventions),
new ExpressionTranspiler(this, this.fc),
new LiteralTranspiler(this, this.fc),
new ModuleTranspiler(this, this.fc, options.generateLibraryName),
new StatementTranspiler(this),
new TypeTranspiler(this, this.fc),
];
}
/**
* Transpiles the given files to Dart.
* @param fileNames The input files.
* @param destination Location to write files to. Creates files next to their sources if absent.
*/
transpile(fileNames: string[], destination?: string): void {
if (this.options.basePath) {
this.options.basePath = this.normalizeSlashes(path.resolve(this.options.basePath));
}
fileNames = fileNames.map((f) => this.normalizeSlashes(path.resolve(f)));
let host: ts.CompilerHost;
let compilerOpts: ts.CompilerOptions;
if (this.options.tsconfig) {
let {config, error} =
ts.readConfigFile(this.options.tsconfig, (f) => fs.readFileSync(f, 'utf-8'));
if (error) throw new Error(ts.flattenDiagnosticMessageText(error.messageText, '\n'));
let {options, errors} = ts.convertCompilerOptionsFromJson(
config.compilerOptions, path.dirname(this.options.tsconfig));
if (errors && errors.length) {
throw new Error(errors.map((d) => this.diagnosticToString(d)).join('\n'));
}
host = ts.createCompilerHost(options, /*setParentNodes*/ true);
compilerOpts = options;
if (compilerOpts.rootDir != null && this.options.basePath == null) {
// Use the tsconfig's rootDir if basePath is not set.
this.options.basePath = compilerOpts.rootDir;
}
if (compilerOpts.outDir != null && destination == null) {
destination = compilerOpts.outDir;
}
} else {
host = this.createCompilerHost();
compilerOpts = this.getCompilerOptions();
}
if (this.options.basePath) this.options.basePath = path.resolve(this.options.basePath);
if (this.options.basePath && destination === undefined) {
throw new Error(
'Must have a destination path when a basePath is specified ' + this.options.basePath);
}
let destinationRoot = destination || this.options.basePath || '';
let program = ts.createProgram(fileNames, compilerOpts, host);
if (this.options.translateBuiltins) {
this.fc.initializeTypeBasedConversion(program.getTypeChecker(), compilerOpts, host);
}
// Only write files that were explicitly passed in.
let fileSet: {[s: string]: boolean} = {};
fileNames.forEach((f) => fileSet[f] = true);
this.errors = [];
program.getSourceFiles()
.filter((sourceFile) => fileSet[sourceFile.fileName])
// Do not generate output for .d.ts files.
.filter((sourceFile: ts.SourceFile) => !sourceFile.fileName.match(/\.d\.ts$/))
.forEach((f: ts.SourceFile) => {
let dartCode = this.translate(f);
let outputFile = this.getOutputPath(f.fileName, destinationRoot);
mkdirP(path.dirname(outputFile));
fs.writeFileSync(outputFile, dartCode);
});
this.checkForErrors(program);
}
translateProgram(program: ts.Program, host: ts.CompilerHost): {[path: string]: string} {
if (this.options.translateBuiltins) {
this.fc.initializeTypeBasedConversion(
program.getTypeChecker(), program.getCompilerOptions(), host);
}
let paths: {[path: string]: string} = {};
this.errors = [];
program.getSourceFiles()
.filter(
(sourceFile: ts.SourceFile) =>
(!sourceFile.fileName.match(/\.d\.ts$/) && !!sourceFile.fileName.match(/\.[jt]s$/)))
.forEach((f) => paths[f.fileName] = this.translate(f));
this.checkForErrors(program);
return paths;
}
private getCompilerOptions() {
let opts: ts.CompilerOptions = {};
for (let k of Object.keys(COMPILER_OPTIONS)) opts[k] = COMPILER_OPTIONS[k];
opts.rootDir = this.options.basePath;
return opts;
}
private createCompilerHost(): ts.CompilerHost {
let defaultLibFileName = ts.getDefaultLibFileName(COMPILER_OPTIONS);
defaultLibFileName = this.normalizeSlashes(defaultLibFileName);
let compilerHost: ts.CompilerHost = {
getSourceFile: (sourceName, languageVersion) => {
let sourcePath = sourceName;
if (sourceName === defaultLibFileName) {
sourcePath = ts.getDefaultLibFilePath(COMPILER_OPTIONS);
}
if (!fs.existsSync(sourcePath)) return undefined;
let contents = fs.readFileSync(sourcePath, 'UTF-8');
return ts.createSourceFile(sourceName, contents, COMPILER_OPTIONS.target, true);
},
writeFile(name, text, writeByteOrderMark) { fs.writeFile(name, text); },
fileExists: (filename) => fs.existsSync(filename),
readFile: (filename) => fs.readFileSync(filename, 'utf-8'),
getDefaultLibFileName: () => defaultLibFileName,
useCaseSensitiveFileNames: () => true,
getCanonicalFileName: (filename) => filename,
getCurrentDirectory: () => '',
getNewLine: () => '\n',
};
compilerHost.resolveModuleNames = getModuleResolver(compilerHost);
return compilerHost;
}
// Visible for testing.
getOutputPath(filePath: string, destinationRoot: string): string {
let relative = this.getRelativeFileName(filePath);
let dartFile = relative.replace(/.(js|es6|ts)$/, '.dart');
return this.normalizeSlashes(path.join(destinationRoot, dartFile));
}
private translate(sourceFile: ts.SourceFile): string {
this.currentFile = sourceFile;
this.output = new Output(
sourceFile, this.getRelativeFileName(sourceFile.fileName), this.options.generateSourceMap);
this.lastCommentIdx = -1;
this.visit(sourceFile);
let result = this.output.getResult();
return this.formatCode(result, sourceFile);
}
private formatCode(code: string, context: ts.Node) {
let result = dartStyle.formatCode(code);
if (result.error) {
this.reportError(context, result.error);
}
return result.code;
}
private checkForErrors(program: ts.Program) {
let errors = this.errors;
let diagnostics = program.getGlobalDiagnostics().concat(program.getSyntacticDiagnostics());
if ((errors.length || diagnostics.length) && this.options.translateBuiltins) {
// Only report semantic diagnostics if ts2dart failed; this code is not a generic compiler, so
// only yields TS errors if they could be the cause of ts2dart issues.
// This greatly speeds up tests and execution.
diagnostics = diagnostics.concat(program.getSemanticDiagnostics());
}
let diagnosticErrs = diagnostics.map((d) => this.diagnosticToString(d));
if (diagnosticErrs.length) errors = errors.concat(diagnosticErrs);
if (errors.length) {
let e = new Error(errors.join('\n'));
e.name = 'TS2DartError';
throw e;
}
}
private diagnosticToString(diagnostic: ts.Diagnostic): string {
let msg = '';
if (diagnostic.file) {
let pos = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
let fn = this.getRelativeFileName(diagnostic.file.fileName);
msg += ` ${fn}:${pos.line + 1}:${pos.character + 1}`;
}
msg += ': ';
msg += ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
return msg;
}
/**
* Returns `filePath`, relativized to the program's `basePath`.
* @param filePath path to relativize.
*/
getRelativeFileName(filePath: string) {
let base = this.options.basePath || '';
if (filePath[0] === '/' && filePath.indexOf(base) !== 0 && !filePath.match(/\.d\.ts$/)) {
throw new Error(`Files must be located under base, got ${filePath} vs ${base}`);
}
let rel = path.relative(base, filePath);
if (rel.indexOf('../') === 0) {
// filePath is outside of rel, just use it directly.
rel = filePath;
}
return this.normalizeSlashes(rel);
}
emit(s: string) { this.output.emit(s); }
emitNoSpace(s: string) { this.output.emitNoSpace(s); }
reportError(n: ts.Node, message: string) {
let file = n.getSourceFile() || this.currentFile;
let fileName = this.getRelativeFileName(file.fileName);
let start = n.getStart(file);
let pos = file.getLineAndCharacterOfPosition(start);
// Line and character are 0-based.
let fullMessage = `${fileName}:${pos.line + 1}:${pos.character + 1}: ${message}`;
if (this.options.failFast) throw new Error(fullMessage);
this.errors.push(fullMessage);
}
visit(node: ts.Node) {
this.output.addSourceMapping(node);
try {
let comments = ts.getLeadingCommentRanges(this.currentFile.text, node.getFullStart());
if (comments) {
comments.forEach((c) => {
if (c.pos <= this.lastCommentIdx) return;
this.lastCommentIdx = c.pos;
let text = this.currentFile.text.substring(c.pos, c.end);
this.emitNoSpace('\n');
this.emit(this.translateComment(text));
if (c.hasTrailingNewLine) this.emitNoSpace('\n');
});
}
for (let i = 0; i < this.transpilers.length; i++) {
if (this.transpilers[i].visitNode(node)) return;
}
this.reportError(
node, `Unsupported node type ${(<any>ts).SyntaxKind[node.kind]}: ${node.getFullText()}`);
} catch (e) {
this.reportError(node, 'ts2dart crashed ' + e.stack);
}
}
private normalizeSlashes(path: string) { return path.replace(/\\/g, '/'); }
private translateComment(comment: string): string {
comment = comment.replace(/\{@link ([^\}]+)\}/g, '[$1]');
// Remove the following tags and following comments till end of line.
comment = comment.replace(/@param.*$/gm, '');
comment = comment.replace(/@throws.*$/gm, '');
comment = comment.replace(/@return.*$/gm, '');
// Remove the following tags.
comment = comment.replace(/@module/g, '');
comment = comment.replace(/@description/g, '');
comment = comment.replace(/@deprecated/g, '');
return comment;
}
}
export function getModuleResolver(compilerHost: ts.CompilerHost) {
return (moduleNames: string[], containingFile: string): ts.ResolvedModule[] => {
let res: ts.ResolvedModule[] = [];
for (let mod of moduleNames) {
let lookupRes =
ts.nodeModuleNameResolver(mod, containingFile, COMPILER_OPTIONS, compilerHost);
if (lookupRes.resolvedModule) {
res.push(lookupRes.resolvedModule);
continue;
}
lookupRes = ts.classicNameResolver(mod, containingFile, COMPILER_OPTIONS, compilerHost);
if (lookupRes.resolvedModule) {
res.push(lookupRes.resolvedModule);
continue;
}
res.push(undefined);
}
return res;
};
}
class Output {
private result: string = '';
private column: number = 1;
private line: number = 1;
// Position information.
private generateSourceMap: boolean;
private sourceMap: SourceMapGenerator;
constructor(
private currentFile: ts.SourceFile, private relativeFileName: string,
generateSourceMap: boolean) {
if (generateSourceMap) {
this.sourceMap = new SourceMapGenerator({file: relativeFileName + '.dart'});
this.sourceMap.setSourceContent(relativeFileName, this.currentFile.text);
}
}
emit(str: string) {
this.emitNoSpace(' ');
this.emitNoSpace(str);
}
emitNoSpace(str: string) {
this.result += str;
for (let i = 0; i < str.length; i++) {
if (str[i] === '\n') {
this.line++;
this.column = 0;
} else {
this.column++;
}
}
}
getResult(): string { return this.result + this.generateSourceMapComment(); }
addSourceMapping(n: ts.Node) {
if (!this.generateSourceMap) return; // source maps disabled.
let file = n.getSourceFile() || this.currentFile;
let start = n.getStart(file);
let pos = file.getLineAndCharacterOfPosition(start);
let mapping: SourceMap.Mapping = {
original: {line: pos.line + 1, column: pos.character},
generated: {line: this.line, column: this.column},
source: this.relativeFileName,
};
this.sourceMap.addMapping(mapping);
}
private generateSourceMapComment() {
if (!this.sourceMap) return '';
let base64map = new Buffer(JSON.stringify(this.sourceMap)).toString('base64');
return '\n\n//# sourceMappingURL=data:application/json;base64,' + base64map;
}
}
function showHelp() {
console.log(`
Usage: ts2dart [input-files] [arguments]
--help show this dialog
--failFast Fail on the first error, do not collect multiple. Allows easier debugging
as stack traces lead directly to the offending line
--generateLibraryName Whether to generate 'library a.b.c;' names from relative file paths.
--generateSourceMap Whether to generate source maps.
--tsconfig A tsconfig.json to use to configure TypeScript compilation.
--basePath A base path to relativize absolute file paths against. This
is useful for library name generation (see above) and nicer
file names in error messages.
--translateBuiltins Translate calls to builtins, i.e. seemlessly convert from \` Array\` to \` List\`,
and convert the corresponding methods. Requires type checking.
--enforceUnderscoreConventions Enforce conventions of public/private keyword and underscore prefix
`);
process.exit(0);
}
// CLI entry point
if (require.main === module) {
let args = require('minimist')(process.argv.slice(2), {base: 'string'});
if (args.help) showHelp();
try {
let transpiler = new Transpiler(args);
console.error('Transpiling', args._, 'to', args.destination);
transpiler.transpile(args._, args.destination);
} catch (e) {
if (e.name !== 'TS2DartError') throw e;
console.error(e.message);
process.exit(1);
}
} | the_stack |
export interface PackMeta {
texture?: PackMeta.Texture;
animation?: PackMeta.Animation;
pack?: PackMeta.Pack;
language: PackMeta.Language;
}
/**
* The block model json format
*/
export interface BlockModel {
/**
* For Block:
*
* Loads a different model from the given path, starting in assets/minecraft/models. If both "parent" and "elements" are set, the "elements" tag overrides the "elements" tag from the previous model.
* Can be set to "builtin/generated" to use a model that is created out of the specified icon. Note that only the first layer is supported, and rotation can only be achieved using block states files.
*
* For Item:
*
* Loads a different model from the given path, starting in assets/minecraft/models. If both "parent" and "elements" are set, the "elements" tag overrides the "elements" tag from the previous model.
* Can be set to "builtin/generated" to use a model that is created out of the specified icon.
* Can be set to "builtin/entity" to load a model from an entity file. As you can not specify the entity, this does not work for all items (only for chests, ender chests, mob heads, shields and banners).
* Needs to be set to "builtin/compass" or "builtin/clock" for the compass and the clock.
*/
parent?: string;
ambientocclusion?: boolean;
/**
* Holds the different places where item models are displayed.
*/
display?: BlockModel.Display;
/**
* Holds the textures of the model. Each texture starts in assets/minecraft/textures or can be another texture variable.
*/
textures?: {
/**
* What texture to load particles from. This texture is used if you are in a nether portal. Note: All breaking particles from non-model blocks are hard-coded.
*/
particle?: string;
[variant: string]: string | undefined;
};
/**
* Contains all the elements of the model. they can only have cubic forms. If both "parent" and "elements" are set, the "elements" tag overrides the "elements" tag from the previous model.
*/
elements?: BlockModel.Element[];
/**
* Determines cases which a different model should be used based on item tags.
* All cases are evaluated in order from top to bottom and last predicate that mathches will override.
* However, overrides are ignored if it has been already overriden once, for example this avoids recursion on overriding to the same model.
*/
overrides?: Array<{
/**
* predicate: Holds the cases.
*/
prediction: { [attribute: string]: number };
/**
* The path to the model to use if the case is met, starting in assets/minecraft/models/
*/
model: string;
}>;
}
export namespace PackMeta {
export interface Language {
/**
* Language code for a language, corresponding to a .json file with the same name in the folder assets/<namespace>/lang.
*/
[lang: string]: {
/**
* The full name of the language
*/
name: string;
/**
* The country or region name
*/
region: string;
/**
* If true, the language reads right to left.
*/
bidirectional: boolean;
};
}
/**
* Holds the resource pack information
*/
export interface Pack {
/**
* Pack version. If this number does not match the current required number, the resource pack will display an error and required additional confirmation to load the pack.
* Requires 1 for 1.6.1–1.8.9, 2 for 1.9–1.10.2, 3 for 1.11–1.12.2, and 4 for 1.13–1.14.4.
*/
pack_format: number;
/**
* Text that will be shown below the pack name in the resource pack menu.
* The text will be shown on two lines. If the text is too long it will be cut off.
*
* Contains a raw JSON text object that will be shown instead as the pack description in the resource pack menu.
* Same behavior as the string version of the description tag, but they cannot exist together.[
*/
description: string | object;
}
export interface Animation {
/**
* If true, Minecraft will generate additional frames between frames with a frame time greater than 1 between them. Defaults to false.
*/
interpolate: boolean;
/**
* The width of the tile, as a direct ratio rather than in pixels. This is unused in vanilla but can be used by mods to have frames that are not perfect squares.
*/
width: number;
/**
* The height of the tile in direct pixels, as a ratio rather than in pixels. This is unused in vanilla but can be used by mods to have frames that are not perfect squares.
*/
height: number;
/**
* Sets the default time for each frame in increments of one game tick. Defaults to `1`.
*/
frametime: number;
frames: Array<{ index: number; time: number }>;
}
export interface Texture {
/**
* Causes the texture to blur when viewed from close up. Defaults to `false`
*/
blur: boolean;
/**
* Causes the texture to stretch instead of tiling in cases where it otherwise would, such as on the shadow. Defaults to `false`
*/
clamp: boolean;
/**
* Custom mipmap values for the texture
*/
mipmaps: string[];
}
}
type Vec3 = [number, number, number];
type Vec4 = [number, number, number, number];
export namespace BlockModel {
export type Direction = "up" | "down" | "north" | "south" | "west" | "east";
export interface Display {
thirdperson_righthand: Transform;
thirdperson_lefthand: Transform;
firstperson_righthand: Transform;
firstperson_lefthand: Transform;
gui: Transform;
head: Transform;
ground: Transform;
fixed: Transform;
}
export interface Element {
/**
* Start point of a cube according to the scheme [x, y, z]. Values must be between -16 and 32.
*/
from: Vec3;
/**
* Stop point of a cube according to the scheme [x, y, z]. Values must be between -16 and 32.
*/
to: Vec3;
/**
* Defines the rotation of an element.
*/
rotation?: {
/**
* Sets the center of the rotation according to the scheme [x, y, z], defaults to [8, 8, 8].
*/
origin: Vec3;
/**
* Specifies the direction of rotation, can be "x", "y" or "z".
*/
axis: "x" | "y" | "z";
/**
* Specifies the angle of rotation. Can be 45 through -45 degrees in 22.5 degree increments. Defaults to 0.
*/
angle: number;
/**
* Specifies whether or not to scale the faces across the whole block. Can be true or false. Defaults to false.
*/
rescale: boolean;
};
/**
* Defines if shadows are rendered (true - default), not (false).
*/
shade?: boolean;
faces?: {
up?: Face;
down?: Face;
north?: Face;
south?: Face;
east?: Face;
west?: Face;
};
}
export interface Face {
/**
* Defines the area of the texture to use according to the scheme [x1, y1, x2, y2].
* If unset, it defaults to values equal to xyz position of the element.
* The texture behavior will be inconsistent if UV extends below 0 or above 16.
* If the numbers of x1 and x2 are swapped (e.g. from 0, 0, 16, 16 to 16, 0, 0, 16), the texture will be flipped. UV is optional, and if not supplied it will automatically generate based on the element's position.
*/
uv?: Vec4;
/**
* Specifies the texture in form of the texture variable prepended with a #.
*/
texture: string;
/**
* Specifies whether a face does not need to be rendered when there is a block touching it in the specified position.
* The position can be: down, up, north, south, west, or east. It will also determine which side of the block to use the light level from for lighting the face,
* and if unset, defaults to the side.
*/
cullface?: Direction;
/**
* Rotates the texture by the specified number of degrees.
* Can be 0, 90, 180, or 270. Defaults to 0. Rotation does not affect which part of the texture is used.
* Instead, it amounts to permutation of the selected texture vertexes (selected implicitly, or explicitly though uv).
*/
rotation?: 0 | 90 | 180 | 270;
/**
* Determines whether to tint the texture using a hardcoded tint index. The default is not using the tint, and any number causes it to use tint. Note that only certain blocks have a tint index, all others will be unaffected.
*/
tintindex?: number;
}
export interface Transform {
/**
* Specifies the rotation of the model according to the scheme [x, y, z].
*/
rotation: Vec3;
/**
* Specifies the position of the model according to the scheme [x, y, z]. If the value is greater than 80, it is displayed as 80. If the value is less then -80, it is displayed as -80.
*/
translation: Vec3;
/**
* Specifies the scale of the model according to the scheme [x, y, z]. If the value is greater than 4, it is displayed as 4.
*/
scale: Vec3;
}
export type Resolved = Omit<Required<BlockModel>, "parent" | "override" | "elements"> & {
overrides?: BlockModel["overrides"];
elements: Array<Omit<Element, "faces"> & {
faces: {
up?: Face;
down?: Face;
north?: Face;
south?: Face;
east?: Face;
west?: Face;
}
}>
};
} | the_stack |
import { Action, Dispatcher, Reducer } from '@ngrx/store';
import { difference, liftAction } from './utils';
import { ActionTypes } from './actions';
export const INIT_ACTION = { type: Dispatcher.INIT };
export interface LiftedState {
monitorState: any;
nextActionId: number;
actionsById: { [id: number]: { action: Action } };
stagedActionIds: number[];
skippedActionIds: number[];
committedState: any;
currentStateIndex: number;
computedStates: { state: any, error: any }[];
}
/**
* Computes the next entry in the log by applying an action.
*/
function computeNextEntry(reducer, action, state, error) {
if (error) {
return {
state,
error: 'Interrupted by an error up the chain'
};
}
let nextState = state;
let nextError;
try {
nextState = reducer(state, action);
} catch (err) {
nextError = err.toString();
console.error(err.stack || err);
}
return {
state: nextState,
error: nextError
};
}
/**
* Runs the reducer on invalidated actions to get a fresh computation log.
*/
function recomputeStates(
computedStates,
minInvalidatedStateIndex,
reducer,
committedState,
actionsById,
stagedActionIds,
skippedActionIds
) {
// Optimization: exit early and return the same reference
// if we know nothing could have changed.
if (
minInvalidatedStateIndex >= computedStates.length &&
computedStates.length === stagedActionIds.length
) {
return computedStates;
}
const nextComputedStates = computedStates.slice(0, minInvalidatedStateIndex);
for (let i = minInvalidatedStateIndex; i < stagedActionIds.length; i++) {
const actionId = stagedActionIds[i];
const action = actionsById[actionId].action;
const previousEntry = nextComputedStates[i - 1];
const previousState = previousEntry ? previousEntry.state : committedState;
const previousError = previousEntry ? previousEntry.error : undefined;
const shouldSkip = skippedActionIds.indexOf(actionId) > -1;
const entry = shouldSkip ?
previousEntry :
computeNextEntry(reducer, action, previousState, previousError);
nextComputedStates.push(entry);
}
return nextComputedStates;
}
export function liftInitialState(initialCommittedState?: any, monitorReducer?: any): LiftedState {
return {
monitorState: monitorReducer(undefined, {}),
nextActionId: 1,
actionsById: { 0: liftAction(INIT_ACTION) },
stagedActionIds: [0],
skippedActionIds: [],
committedState: initialCommittedState,
currentStateIndex: 0,
computedStates: []
};
}
/**
* Creates a history state reducer from an app's reducer.
*/
export function liftReducerWith(
initialCommittedState: any,
initialLiftedState: LiftedState,
monitorReducer?: any,
options: { maxAge?: number } = {}
) {
/**
* Manages how the history actions modify the history state.
*/
return reducer => (liftedState, liftedAction) => {
let {
monitorState,
actionsById,
nextActionId,
stagedActionIds,
skippedActionIds,
committedState,
currentStateIndex,
computedStates
} = liftedState || initialLiftedState;
if (!liftedState) {
// Prevent mutating initialLiftedState
actionsById = Object.create(actionsById);
}
function commitExcessActions(n) {
// Auto-commits n-number of excess actions.
let excess = n;
let idsToDelete = stagedActionIds.slice(1, excess + 1);
for (let i = 0; i < idsToDelete.length; i++) {
if (computedStates[i + 1].error) {
// Stop if error is found. Commit actions up to error.
excess = i;
idsToDelete = stagedActionIds.slice(1, excess + 1);
break;
} else {
delete actionsById[idsToDelete[i]];
}
}
skippedActionIds = skippedActionIds.filter(id => idsToDelete.indexOf(id) === -1);
stagedActionIds = [0, ...stagedActionIds.slice(excess + 1)];
committedState = computedStates[excess].state;
computedStates = computedStates.slice(excess);
currentStateIndex = currentStateIndex > excess
? currentStateIndex - excess
: 0;
}
// By default, agressively recompute every state whatever happens.
// This has O(n) performance, so we'll override this to a sensible
// value whenever we feel like we don't have to recompute the states.
let minInvalidatedStateIndex = 0;
switch (liftedAction.type) {
case ActionTypes.RESET: {
// Get back to the state the store was created with.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = initialCommittedState;
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.COMMIT: {
// Consider the last committed state the new starting point.
// Squash any staged actions into a single committed state.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = computedStates[currentStateIndex].state;
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.ROLLBACK: {
// Forget about any staged actions.
// Start again from the last committed state.
actionsById = { 0: liftAction(INIT_ACTION) };
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
currentStateIndex = 0;
computedStates = [];
break;
}
case ActionTypes.TOGGLE_ACTION: {
// Toggle whether an action with given ID is skipped.
// Being skipped means it is a no-op during the computation.
const { id: actionId } = liftedAction;
const index = skippedActionIds.indexOf(actionId);
if (index === -1) {
skippedActionIds = [actionId, ...skippedActionIds];
} else {
skippedActionIds = skippedActionIds.filter(id => id !== actionId);
}
// Optimization: we know history before this action hasn't changed
minInvalidatedStateIndex = stagedActionIds.indexOf(actionId);
break;
}
case ActionTypes.SET_ACTIONS_ACTIVE: {
// Toggle whether an action with given ID is skipped.
// Being skipped means it is a no-op during the computation.
const { start, end, active } = liftedAction;
const actionIds = [];
for (let i = start; i < end; i++) actionIds.push(i);
if (active) {
skippedActionIds = difference(skippedActionIds, actionIds);
} else {
skippedActionIds = [...skippedActionIds, ...actionIds];
}
// Optimization: we know history before this action hasn't changed
minInvalidatedStateIndex = stagedActionIds.indexOf(start);
break;
}
case ActionTypes.JUMP_TO_STATE: {
// Without recomputing anything, move the pointer that tell us
// which state is considered the current one. Useful for sliders.
currentStateIndex = liftedAction.index;
// Optimization: we know the history has not changed.
minInvalidatedStateIndex = Infinity;
break;
}
case ActionTypes.SWEEP: {
// Forget any actions that are currently being skipped.
stagedActionIds = difference(stagedActionIds, skippedActionIds);
skippedActionIds = [];
currentStateIndex = Math.min(currentStateIndex, stagedActionIds.length - 1);
break;
}
case ActionTypes.PERFORM_ACTION: {
// Auto-commit as new actions come in.
if (options.maxAge && stagedActionIds.length === options.maxAge) {
commitExcessActions(1);
}
if (currentStateIndex === stagedActionIds.length - 1) {
currentStateIndex++;
}
const actionId = nextActionId++;
// Mutation! This is the hottest path, and we optimize on purpose.
// It is safe because we set a new key in a cache dictionary.
actionsById[actionId] = liftedAction;
stagedActionIds = [...stagedActionIds, actionId];
// Optimization: we know that only the new action needs computing.
minInvalidatedStateIndex = stagedActionIds.length - 1;
break;
}
case ActionTypes.IMPORT_STATE: {
// Completely replace everything.
({
monitorState,
actionsById,
nextActionId,
stagedActionIds,
skippedActionIds,
committedState,
currentStateIndex,
computedStates
} = liftedAction.nextLiftedState);
break;
}
case Reducer.REPLACE:
case Dispatcher.INIT: {
// Always recompute states on hot reload and init.
minInvalidatedStateIndex = 0;
if (options.maxAge && stagedActionIds.length > options.maxAge) {
// States must be recomputed before committing excess.
computedStates = recomputeStates(
computedStates,
minInvalidatedStateIndex,
reducer,
committedState,
actionsById,
stagedActionIds,
skippedActionIds
);
commitExcessActions(stagedActionIds.length - options.maxAge);
// Avoid double computation.
minInvalidatedStateIndex = Infinity;
}
break;
}
default: {
// If the action is not recognized, it's a monitor action.
// Optimization: a monitor action can't change history.
minInvalidatedStateIndex = Infinity;
break;
}
}
computedStates = recomputeStates(
computedStates,
minInvalidatedStateIndex,
reducer,
committedState,
actionsById,
stagedActionIds,
skippedActionIds
);
monitorState = monitorReducer(monitorState, liftedAction);
return {
monitorState,
actionsById,
nextActionId,
stagedActionIds,
skippedActionIds,
committedState,
currentStateIndex,
computedStates
};
};
} | the_stack |
import uuidv4 from 'uuid/v4'
import { takeLatest, put, select, call, delay, take } from 'redux-saga/effects'
import {
ADD_ITEM,
AddItemAction,
provisionScene,
RESET_ITEM,
ResetItemAction,
UPDATE_TRANSFORM,
UpdateTransfromAction,
DUPLICATE_ITEM,
DELETE_ITEM,
DuplicateItemAction,
DeleteItemAction,
SET_GROUND,
SetGroundAction,
ApplyLayoutAction,
APPLY_LAYOUT,
SET_SCRIPT_VALUES,
SetScriptValuesAction,
SYNC_SCENE_ASSETS_REQUEST,
SyncSceneAssetsRequestAction,
FIX_LEGACY_NAMESPACES_REQUEST,
FixLegacyNamespacesRequestAction,
fixLegacyNamespacesSuccess,
syncSceneAssetsSuccess
} from 'modules/scene/actions'
import {
getGLTFsByAssetId,
getCurrentScene,
getEntityComponentsByType,
getComponentsByEntityId,
getData as getScenes,
getCollectiblesByURL,
getShapesByEntityId
} from 'modules/scene/selectors'
import { ComponentType, Scene, ComponentDefinition, ShapeComponent, AnyComponent } from 'modules/scene/types'
import { getSelectedEntityIds, isReady } from 'modules/editor/selectors'
import { setSelectedEntities, SET_EDITOR_READY } from 'modules/editor/actions'
import { getCurrentBounds, getData as getProjects } from 'modules/project/selectors'
import { PARCEL_SIZE } from 'modules/project/constants'
import { EditorWindow } from 'components/Preview/Preview.types'
import { COLLECTIBLE_ASSET_PACK_ID } from 'modules/ui/sidebar/utils'
import {
snapToGrid,
snapToBounds,
cloneEntities,
filterEntitiesWithComponent,
getEntityName,
getDefaultValues,
renameEntity,
removeEntityReferences
} from './utils'
import { getData as getAssets, getGroundAssets, getAssetsByEntityName } from 'modules/asset/selectors'
import { Asset } from 'modules/asset/types'
import { loadAssets } from 'modules/asset/actions'
import { getData as getAssetPacks } from 'modules/assetPack/selectors'
import { getMetrics } from 'components/AssetImporter/utils'
import { DataByKey } from 'decentraland-dapps/dist/lib/types'
const editorWindow = window as EditorWindow
export function* sceneSaga() {
yield takeLatest(ADD_ITEM, handleAddItem)
yield takeLatest(UPDATE_TRANSFORM, handleUpdateTransfrom)
yield takeLatest(RESET_ITEM, handleResetItem)
yield takeLatest(DUPLICATE_ITEM, handleDuplicateItem)
yield takeLatest(DELETE_ITEM, handleDeleteItem)
yield takeLatest(SET_GROUND, handleSetGround)
yield takeLatest(FIX_LEGACY_NAMESPACES_REQUEST, handleFixLegacyNamespacesRequest)
yield takeLatest(SYNC_SCENE_ASSETS_REQUEST, handleSyncSceneAssetsAction)
yield takeLatest(APPLY_LAYOUT, handleApplyLayout)
yield takeLatest(SET_SCRIPT_VALUES, handleSetScriptParameters)
}
function* handleAddItem(action: AddItemAction) {
const isEditorReady: boolean = yield select(isReady)
if (!isEditorReady) {
yield take(SET_EDITOR_READY)
}
const scene: Scene = yield select(getCurrentScene)
if (!scene) return
let shapeId: string | null
let scriptId: string | null = null
let { position } = action.payload
const { asset } = action.payload
const transformId = uuidv4()
const newComponents = { ...scene.components }
if (!position) {
position = yield call(editorWindow.editor.getCameraTarget)
position!.y = 0
}
if (asset.assetPackId === COLLECTIBLE_ASSET_PACK_ID) {
const collectibles: ReturnType<typeof getCollectiblesByURL> = yield select(getCollectiblesByURL)
const collectible = collectibles[asset.model]
shapeId = collectible ? collectibles[asset.model].id : null
if (!shapeId) {
shapeId = uuidv4()
newComponents[shapeId] = {
id: shapeId,
type: ComponentType.NFTShape,
data: {
url: asset.model
}
}
}
position = { ...position!, y: 1.72 }
} else {
const gltfs: ReturnType<typeof getGLTFsByAssetId> = yield select(getGLTFsByAssetId)
const gltf = gltfs[asset.id]
shapeId = gltf ? gltf.id : null
if (!shapeId) {
shapeId = uuidv4()
newComponents[shapeId] = {
id: shapeId,
type: ComponentType.GLTFShape,
data: {
assetId: asset.id
}
} as ComponentDefinition<ComponentType.GLTFShape>
}
}
const bounds: ReturnType<typeof getCurrentBounds> = yield select(getCurrentBounds)
if (bounds) {
position = snapToBounds(position!, bounds)
}
position = snapToGrid(position!)
newComponents[transformId] = {
id: transformId,
type: ComponentType.Transform,
data: {
position,
rotation: { x: 0, y: 0, z: 0, w: 1 },
scale: { x: 1, y: 1, z: 1 }
}
} as ComponentDefinition<ComponentType.Transform>
const scriptPath = Object.keys(asset.contents).find(path => path.endsWith('.js'))
if (scriptPath) {
scriptId = uuidv4()
newComponents[scriptId] = {
id: scriptId,
type: ComponentType.Script,
data: {
assetId: asset.id,
src: asset.contents[scriptPath],
values: {}
}
} as ComponentDefinition<ComponentType.Script>
}
const newEntities = { ...scene.entities }
const entityId = uuidv4()
const entityComponents = [transformId, shapeId]
if (scriptId) {
// Scripts components must go first
entityComponents.unshift(scriptId)
}
const newScene = { ...scene, components: newComponents, entities: newEntities }
const assets: DataByKey<Asset> = yield select(getAssets)
const entityName = getEntityName(newScene, entityComponents, assets)
newEntities[entityId] = { id: entityId, components: entityComponents, name: entityName }
newScene.assets[asset.id] = asset
if (scriptId) {
const assets: Record<string, Asset> = yield select(getAssetsByEntityName)
const comp = newScene.components[scriptId] as ComponentDefinition<ComponentType.Script>
comp.data.values = getDefaultValues(entityName, asset.parameters, assets)
}
yield put(setSelectedEntities([])) // deselect all currently selected entities
yield put(provisionScene(newScene))
yield delay(500) // gotta wait for the webworker to process the updateEditor action
// wait for entity to finish loading
while (editorWindow.editor.getLoadingEntities() !== null && (editorWindow.editor.getLoadingEntities() as string[]).includes(entityId)) {
yield delay(200)
}
yield put(setSelectedEntities([entityId]))
}
function* handleUpdateTransfrom(action: UpdateTransfromAction) {
const scene: Scene = yield select(getCurrentScene)
if (!scene) return
const { components } = action.payload
const newComponents: Scene['components'] = { ...scene.components }
for (let componentData of components) {
if (componentData.componentId in scene.components) {
newComponents[componentData.componentId] = {
...newComponents[componentData.componentId],
data: {
position: {
...componentData.data.position
},
rotation: {
...componentData.data.rotation
},
scale: {
...componentData.data.scale
}
}
}
}
}
yield put(provisionScene({ ...scene, components: newComponents }))
}
function* handleResetItem(_: ResetItemAction) {
const scene: Scene = yield select(getCurrentScene)
if (!scene) return
const selectedEntityIds: ReturnType<typeof getSelectedEntityIds> = yield select(getSelectedEntityIds)
if (selectedEntityIds.length === 0) return
const components: ReturnType<typeof getEntityComponentsByType> = yield select(getEntityComponentsByType)
const newComponents = {
...scene.components
}
for (let entityId of selectedEntityIds) {
const transform = components[entityId][ComponentType.Transform] as ComponentDefinition<ComponentType.Transform>
if (transform) {
newComponents[transform.id] = {
...transform,
data: {
...transform.data,
position: snapToGrid(transform.data.position),
rotation: { x: 0, y: 0, z: 0, w: 1 },
scale: { x: 1, y: 1, z: 1 }
}
}
}
}
yield put(provisionScene({ ...scene, components: newComponents }))
}
function* handleDuplicateItem(_: DuplicateItemAction) {
const assets: DataByKey<Asset> = yield select(getAssets)
const scene: Scene = yield select(getCurrentScene)
if (!scene) return
const selectedEntityIds: ReturnType<typeof getSelectedEntityIds> = yield select(getSelectedEntityIds)
if (selectedEntityIds.length === 0) return
const newComponents = { ...scene.components }
const newEntities = { ...scene.entities }
const newEntityIds: string[] = []
for (let entityId of selectedEntityIds) {
const entityComponents = []
const shapes: Record<string, ShapeComponent> = yield select(getShapesByEntityId)
const shape = shapes[entityId]
entityComponents.push(shape.id)
if (shape && shape.type === ComponentType.NFTShape) continue
const components: ReturnType<typeof getEntityComponentsByType> = yield select(getEntityComponentsByType)
const transform = components[entityId][ComponentType.Transform] as ComponentDefinition<ComponentType.Transform>
const script = components[entityId][ComponentType.Script] as ComponentDefinition<ComponentType.Script>
if (!shape || !transform) continue
// copy transform
const {
data: { position, rotation, scale }
} = transform
const transformId = uuidv4()
newComponents[transformId] = {
id: transformId,
type: ComponentType.Transform,
data: {
position: { ...position },
rotation: { ...rotation },
scale: { ...scale }
}
}
entityComponents.push(transformId)
const newEntityId = uuidv4()
// WARNING: we use entityComponents here because we can already generate the name which will be used for the Script component.
// This means that we use components before we are done creating all of them.
const entityName = getEntityName({ ...scene, components: newComponents, entities: newEntities }, entityComponents, assets)
newEntities[newEntityId] = { id: newEntityId, components: entityComponents, name: entityName }
newEntityIds.push(newEntityId)
// copy script
if (script) {
const {
data: { values: parameters, assetId }
} = script
const scriptId = uuidv4()
const values = JSON.parse(JSON.stringify(parameters))
renameEntity(assets[assetId].parameters, values, scene.entities[entityId].name, entityName)
newComponents[scriptId] = {
id: scriptId,
type: ComponentType.Script,
data: {
values,
assetId
}
} as ComponentDefinition<ComponentType.Script>
// Scripts components must go first
entityComponents.unshift(scriptId)
}
}
yield put(setSelectedEntities([]))
yield put(provisionScene({ ...scene, components: newComponents, entities: newEntities }))
yield delay(300) // gotta wait for the webworker to process the updateEditor action
// wait for entities to finish loading
while (
editorWindow.editor.getLoadingEntities() !== null &&
(editorWindow.editor.getLoadingEntities() as string[]).some(id => newEntityIds.includes(id))
) {
yield delay(200)
}
yield put(setSelectedEntities(newEntityIds))
}
function* handleDeleteItem(_: DeleteItemAction) {
const scene: Scene = yield select(getCurrentScene)
if (!scene) return
const selectedEntityIds: ReturnType<typeof getSelectedEntityIds> = yield select(getSelectedEntityIds)
if (selectedEntityIds.length === 0) return
const newComponents = { ...scene.components }
const newEntities = { ...scene.entities }
const newAssets = { ...scene.assets }
for (let entityId of selectedEntityIds) {
const componentsByEntityId: Record<string, AnyComponent[]> = yield select(getComponentsByEntityId)
const entityComponents = componentsByEntityId[entityId]
const idsToDelete = entityComponents ? entityComponents.filter(component => !!component).map(component => component.id) : []
delete newEntities[entityId]
for (const componentId of idsToDelete) {
// check if commponentId is not used by other entities
if (Object.values(newEntities).some(entity => entity.components.some(id => componentId === id))) {
continue
}
delete newComponents[componentId]
}
for (let componentId in newComponents) {
const component = newComponents[componentId] as ComponentDefinition<ComponentType.Script>
if (component.type === ComponentType.Script) {
removeEntityReferences(newAssets[component.data.assetId].parameters, component.data.values, scene.entities[entityId].name)
}
}
}
// TODO: refactor
// gather all the models used by gltf shapes
const ids = Object.values(newComponents).reduce((set, component) => {
if (component.type === ComponentType.GLTFShape || component.type === ComponentType.Script) {
const gltfShape = component as ComponentDefinition<ComponentType.GLTFShape>
set.add(gltfShape.data.assetId)
}
return set
}, new Set<string>())
// remove assets that are not in the set
for (const asset of Object.values(newAssets)) {
if (ids.has(asset.id)) {
continue
}
delete newAssets[asset.id]
}
yield put(setSelectedEntities([]))
yield put(provisionScene({ ...scene, components: newComponents, entities: newEntities, assets: newAssets }))
}
function* handleSetGround(action: SetGroundAction) {
const { asset, projectId } = action.payload
const projects: ReturnType<typeof getProjects> = yield select(getProjects)
const currentProject = projects[projectId]
if (!currentProject) return
const scenes: ReturnType<typeof getScenes> = yield select(getScenes)
const scene = scenes[currentProject.sceneId]
if (!scene) return
const { rows, cols } = currentProject.layout
if (asset) {
yield applyGround(scene, rows, cols, asset)
}
}
function* handleFixLegacyNamespacesRequest(action: FixLegacyNamespacesRequestAction) {
/* The purspose of this saga is to fix old namespaces in gltshapes that used to be asset pack ids,
and change them for the asset id instead.
For gltf shapes that don't have a corresponding asset, a dummy one will be created
*/
const { scene } = action.payload
const newComponents: Record<string, ComponentDefinition<ComponentType.GLTFShape>> = {}
const newAssets: Record<string, Asset> = {}
// get asset packs
const assetPacks: ReturnType<typeof getAssetPacks> = yield select(getAssetPacks)
// get assets
const assets: ReturnType<typeof getAssets> = yield select(getAssets)
// gather all gltf shapes
const gltfShapes = Object.values(scene.components).filter(component => component.type === ComponentType.GLTFShape) as ComponentDefinition<
ComponentType.GLTFShape
>[]
for (const gltfShape of gltfShapes) {
const src = (gltfShape.data as any)['src']
// if it doesn't have src, we continue
if (!src) continue
// if the src looks like <uuid>/<model-url> then it's legacy
const legacyRegex = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}/ // check if the path starts with a UUID
const isLegacy = legacyRegex.test(src.split('/')[0])
if (isLegacy) {
const [assetPackId, ...rest] = src.split('/')
const model = rest.join('/')
const assetPack = assetPacks[assetPackId]
// if there's an asset pack, we look for the asset and fix the legacy componment
if (assetPack) {
const asset = assetPack.assets.map(assetId => assets[assetId]).find(asset => asset.model === model)
if (asset) {
const newGltfShape: ComponentDefinition<ComponentType.GLTFShape> = {
...gltfShape,
data: { assetId: asset.id }
}
newComponents[newGltfShape.id] = newGltfShape
continue
}
}
// if there's no asset pack but there are mappings, we generate a dummy asset from the mappings
if ('mappings' in gltfShape.data) {
const contents: Record<string, string> = {}
// TODO: Type this correctly, mappings does not appear anywhere in ComponentDefinition
const mappings: Record<string, string> = (gltfShape.data as Record<string, any>)['mappings']
for (const namespacedPath of Object.keys(mappings)) {
const path = namespacedPath // remove the namespace
.split('/') // ['<uuid>', 'folder', 'Model.gltf']
.slice(1) // ['folder', 'Model.gltf']
.join('/') // 'folder/Model.gltf'
contents[path] = mappings[namespacedPath]
}
const id = uuidv4()
const newAsset: Asset = {
id,
model,
assetPackId,
contents,
name: 'Dummy',
script: null,
thumbnail: '',
tags: [],
category: 'decorations',
metrics: getMetrics(),
parameters: [],
actions: []
}
newAssets[id] = newAsset
const newGltfShape: ComponentDefinition<ComponentType.GLTFShape> = {
...gltfShape,
data: {
...gltfShape.data!,
assetId: newAsset.id
}
}
newComponents[newGltfShape.id] = newGltfShape
} else {
// noop
}
}
}
let fixedScene = scene
const hasUpdates = Object.keys(newComponents).length > 0
if (hasUpdates) {
fixedScene = {
...scene,
assets: { ...scene.assets, ...newAssets },
components: { ...scene.components, ...newComponents }
}
}
yield put(fixLegacyNamespacesSuccess(fixedScene))
}
function* handleSyncSceneAssetsAction(action: SyncSceneAssetsRequestAction) {
const { scene } = action.payload
// assets that need to be updated in the scene
const updatedSceneAssets: Record<string, Asset> = {}
// assets that are present in the scene but not in the store
const missingSceneAssets: Record<string, Asset> = {}
// all assets in the store
const assets: ReturnType<typeof getAssets> = yield select(getAssets)
for (const component of Object.values(scene.components)) {
if (component.type === ComponentType.GLTFShape) {
const gltfShape = component as ComponentDefinition<ComponentType.GLTFShape>
const { assetId } = gltfShape.data
const storeAsset = assets[assetId]
if (storeAsset) {
updatedSceneAssets[storeAsset.id] = storeAsset
} else {
const sceneAsset = scene.assets[assetId]
if (sceneAsset) {
missingSceneAssets[sceneAsset.id] = {
...sceneAsset,
assetPackId: 'dummy-asset-pack-id' // we change this so it won't show up in the sidebar
}
}
}
}
}
// generate new scene
const newScene = { ...scene, assets: { ...scene.assets, ...updatedSceneAssets } }
// load scene assets into redux store
yield put(loadAssets(missingSceneAssets))
// update the scene assets
yield put(syncSceneAssetsSuccess(newScene))
}
function* handleApplyLayout(action: ApplyLayoutAction) {
const { project } = action.payload
const { rows, cols } = project.layout
const scenes: ReturnType<typeof getScenes> = yield select(getScenes)
const scene = scenes[project.sceneId]
if (scene && scene.ground) {
const groundId = scene.ground.assetId
const assets: ReturnType<typeof getGroundAssets> = yield select(getGroundAssets)
const ground = assets[groundId]
yield applyGround(scene, rows, cols, ground)
}
}
function* applyGround(scene: Scene, rows: number, cols: number, asset: Asset) {
const assets: DataByKey<Asset> = yield select(getAssets)
let sceneComponents = { ...scene.components }
let sceneAssets = { ...scene.assets }
let entities = cloneEntities(scene)
let gltfId: string = uuidv4()
if (asset) {
const gltfs: ReturnType<typeof getGLTFsByAssetId> = yield select(getGLTFsByAssetId)
const gltf = gltfs[asset.id]
const foundId = gltf ? gltf.id : null
// Create the Shape component if necessary
if (!foundId) {
sceneComponents[gltfId] = {
id: gltfId,
type: ComponentType.GLTFShape,
data: {
assetId: asset.id
}
}
} else {
gltfId = foundId
}
if (scene.ground) {
entities = filterEntitiesWithComponent(scene.ground.componentId, entities)
}
for (let j = 0; j < cols; j++) {
for (let i = 0; i < rows; i++) {
const entityId = uuidv4()
const transformId = uuidv4()
sceneComponents[transformId] = {
id: transformId,
type: ComponentType.Transform,
data: {
position: { x: i * PARCEL_SIZE + PARCEL_SIZE / 2, y: 0, z: j * PARCEL_SIZE + PARCEL_SIZE / 2 },
rotation: { x: 0, y: 0, z: 0, w: 1 },
scale: { x: 1, y: 1, z: 1 }
}
}
const newComponents = [gltfId, transformId]
entities[entityId] = {
id: entityId,
components: newComponents,
disableGizmos: true,
name: getEntityName({ ...scene, entities }, newComponents, assets)
}
}
}
} else if (scene.ground) {
entities = filterEntitiesWithComponent(scene.ground.componentId, entities)
}
const ground = asset ? { assetId: asset.id, componentId: gltfId } : null
// remove unused components
for (const component of Object.values(sceneComponents)) {
if (!Object.values(entities).some(entity => entity.components.some(componentId => componentId === component.id))) {
delete sceneComponents[component.id]
}
}
// update assets removing the old ground and adding the new one
if (scene.ground) {
delete sceneAssets[scene.ground.assetId]
}
if (ground) {
sceneAssets[ground.assetId] = asset
}
yield put(provisionScene({ ...scene, components: sceneComponents, entities, ground, assets: sceneAssets }))
}
function* handleSetScriptParameters(action: SetScriptValuesAction) {
const { entityId, values } = action.payload
const scene: Scene | null = yield select(getCurrentScene)
if (scene) {
const components = scene.entities[entityId].components
const componentId = components.find(id => scene.components[id].type === ComponentType.Script)
if (componentId) {
const newScene: Scene = {
...scene,
components: {
...scene.components,
[componentId]: {
...scene.components[componentId],
data: {
...scene.components[componentId].data,
values: {
...(scene.components[componentId] as ComponentDefinition<ComponentType.Script>).data.values,
...values
}
}
}
}
}
yield put(provisionScene(newScene))
}
}
} | the_stack |
* Unit tests for LayerVariables.
*/
import * as tfc from '@tensorflow/tfjs-core';
import {randomUniform, scalar, tensor1d, tensor2d, zeros} from '@tensorflow/tfjs-core';
import * as K from './backend/tfjs_backend';
import {nameScope} from './common';
import * as tfl from './index';
import {describeMathCPU, describeMathCPUAndGPU, expectTensorsClose} from './utils/test_utils';
import * as V from './variables';
/**
* Unit tests for Variable.
*/
describeMathCPU('Variable', () => {
it('Variable constructor: no explicit name', () => {
const v1 = new V.LayerVariable(zeros([2]));
expect(v1.name.indexOf('Variable')).toEqual(0);
expect(v1.dtype).toEqual('float32');
expect(v1.shape).toEqual([2]);
expect(v1.trainable).toEqual(true);
expect(v1.read().dataSync()).toEqual(new Float32Array([0, 0]));
const v2 = new V.LayerVariable(zeros([2, 2]));
expect(v2.name.indexOf('Variable')).toEqual(0);
expect(v2.dtype).toEqual('float32');
expect(v2.shape).toEqual([2, 2]);
expect(v2.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
expect(v2.name === v1.name).toBe(false);
});
it('Variable constructor: explicit name', () => {
const v1 = new V.LayerVariable(zeros([]), undefined, 'foo');
expect(v1.name.indexOf('foo')).toEqual(0);
expect(v1.dtype).toEqual('float32');
expect(v1.shape).toEqual([]);
expect(v1.trainable).toEqual(true);
expect(v1.read().dataSync()).toEqual(new Float32Array([0]));
const v2 = new V.LayerVariable(zeros([2, 2, 1]));
expect(v1.name.indexOf('foo')).toEqual(0);
expect(v2.dtype).toEqual('float32');
expect(v2.shape).toEqual([2, 2, 1]);
expect(v2.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
expect(v2.name.length).toBeGreaterThan(0);
expect(v2.name === v1.name).toBe(false);
});
it('Variable constructor: explicit name with name scope', () => {
let v1: V.LayerVariable;
nameScope('barScope', () => {
nameScope('bazScope', () => {
v1 = new V.LayerVariable(scalar(0), undefined, 'foo');
});
});
expect(v1.name.indexOf('barScope/bazScope/foo')).toEqual(0);
expect(v1.dtype).toEqual('float32');
expect(v1.shape).toEqual([]);
expect(v1.trainable).toEqual(true);
expect(v1.read().dataSync()).toEqual(new Float32Array([0]));
});
it('Variable trainable property', () => {
const v1 = new V.LayerVariable(zeros([]), null, 'foo', false);
expect(v1.trainable).toEqual(false);
});
it('Variable works if name is null or undefined', () => {
expect((new V.LayerVariable(zeros([]), null)).name.indexOf('Variable'))
.toEqual(0);
expect((new V.LayerVariable(zeros([]), undefined)).name.indexOf('Variable'))
.toEqual(0);
});
it('int32 dtype', () => {
expect(new V.LayerVariable(zeros([]), 'int32').dtype).toEqual('int32');
});
it('bool dtype', () => {
expect(new V.LayerVariable(zeros([]), 'bool').dtype).toEqual('bool');
});
it('Read value', () => {
const v1 = new V.LayerVariable(scalar(10), null, 'foo');
expect(v1.read().dataSync()).toEqual(new Float32Array([10]));
});
it('Update value: Compatible shape', () => {
const v = new V.LayerVariable(tensor1d([10, -10]), null, 'bar');
expect(v.name.indexOf('bar')).toEqual(0);
expect(v.shape).toEqual([2]);
expect(v.read().dataSync()).toEqual(new Float32Array([10, -10]));
v.write(tensor1d([10, 50]));
expect(v.name.indexOf('bar')).toEqual(0);
expect(v.shape).toEqual([2]);
expect(v.read().dataSync()).toEqual(new Float32Array([10, 50]));
});
it('Update value: w/ constraint', () => {
const v = new V.LayerVariable(
tensor1d([10, -10]), null, 'bar', true, tfl.constraints.nonNeg());
v.write(tensor1d([-10, 10]));
expect(v.read().dataSync()).toEqual(new Float32Array([0, 10]));
});
it('Update value: Incompatible shape', () => {
const v = new V.LayerVariable(zeros([2, 2]), null, 'qux');
expect(() => {
v.write(zeros([4]));
}).toThrowError();
});
it('Generates unique ID', () => {
const v1 = new V.LayerVariable(scalar(1), null, 'foo');
const v2 = new V.LayerVariable(scalar(1), null, 'foo');
expect(v1.id).not.toEqual(v2.id);
});
it('Generates unique IDs for Tensors and Variables', () => {
const v1 = scalar(1);
const v2 = new V.LayerVariable(scalar(1), null, 'foo');
expect(v1.id).not.toEqual(v2.id);
});
it('dispose() frees memory', () => {
const v = new V.LayerVariable(tensor1d([10, -10]), null, 'gralk');
const numTensors0 = tfc.memory().numTensors;
v.dispose();
expect(tfc.memory().numTensors).toEqual(numTensors0 - 1);
});
it('Disposing LayersVariable twices leads to Error', () => {
const v = new V.LayerVariable(tensor1d([10, -10]), null, 'gralk');
v.dispose();
expect(() => v.dispose()).toThrowError(/LayersVariable .*gralk.* disposed/);
});
it('read() after dispose() leads to Error', () => {
const v = new V.LayerVariable(tensor1d([10, -10]), null, 'gralk');
v.dispose();
expect(() => v.read()).toThrowError(/LayersVariable .*gralk.* disposed/);
});
it('write() after dispose() leads to Error', () => {
const v = new V.LayerVariable(tensor1d([10, -10]), null, 'gralk');
v.dispose();
expect(() => v.write(tensor1d([20, -20])))
.toThrowError(/LayersVariable .*gralk.* disposed/);
});
it('Setting trainable sets the trainable of underlying tfc.Variable', () => {
const v1 = new V.LayerVariable(scalar(1), null, 'foo', true);
// tslint:disable-next-line:no-any
const coreVariable = (v1 as any).val as tfc.Variable;
expect(coreVariable.trainable).toEqual(true);
v1.trainable = false;
expect(coreVariable.trainable).toEqual(false);
v1.trainable = true;
expect(coreVariable.trainable).toEqual(true);
});
});
describeMathCPUAndGPU('Create Variable', () => {
it('From Tensor, no explicit name', () => {
const v = V.variable(zeros([2, 2]));
expect(v.name.indexOf('Variable')).toEqual(0);
expect(v.shape).toEqual([2, 2]);
expect(v.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
});
it('From Tensor, no explicit name', () => {
const v = V.variable(zeros([3]));
expect(v.name.indexOf('Variable')).toEqual(0);
expect(v.shape).toEqual([3]);
expect(v.read().dataSync()).toEqual(new Float32Array([0, 0, 0]));
});
it('From Tensor, explicit name', () => {
const v = V.variable(zeros([3]), undefined, 'Var1');
expect(v.name.indexOf('Var1')).toEqual(0);
expect(v.shape).toEqual([3]);
expect(v.read().dataSync()).toEqual(new Float32Array([0, 0, 0]));
});
});
describeMathCPUAndGPU('ZerosVariable', () => {
it('Scalar', () => {
const s = V.zerosVariable([], 'float32', 'Scalar');
expect(s.name.indexOf('Scalar')).toEqual(0);
expect(s.read().shape).toEqual([]);
expect(s.read().dataSync()).toEqual(new Float32Array([0]));
});
it('Vector', () => {
const v = V.zerosVariable([3], 'float32', 'Vector');
expect(v.name.indexOf('Vector')).toEqual(0);
expect(v.read().shape).toEqual([3]);
expect(v.read().dataSync()).toEqual(new Float32Array([0, 0, 0]));
});
it('Matrix', () => {
const m = V.zerosVariable([2, 2], 'float32', 'Matrix');
expect(m.name.indexOf('Matrix')).toEqual(0);
expect(m.read().shape).toEqual([2, 2]);
expect(m.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
});
it('3D', () => {
const t = V.zerosVariable([2, 2, 2], 'float32', 'Tertiary');
expect(t.name.indexOf('Tertiary')).toEqual(0);
expect(t.read().shape).toEqual([2, 2, 2]);
expect(t.read().dataSync()).toEqual(new Float32Array([
0, 0, 0, 0, 0, 0, 0, 0
]));
});
it('4D', () => {
const q = V.zerosVariable([1, 2, 1, 3], 'float32', 'Quaternary');
expect(q.name.indexOf('Quaternary')).toEqual(0);
expect(q.read().shape).toEqual([1, 2, 1, 3]);
expect(q.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0, 0, 0]));
});
});
describeMathCPUAndGPU('OnesVariable', () => {
it('Scalar', () => {
const s = V.onesVariable([], 'float32', 'Scalar');
expect(s.name.indexOf('Scalar')).toEqual(0);
expect(s.read().shape).toEqual([]);
expect(s.read().dataSync()).toEqual(new Float32Array([1]));
});
it('Vector', () => {
const v = V.onesVariable([3], 'float32', 'Vector');
expect(v.name.indexOf('Vector')).toEqual(0);
expect(v.read().shape).toEqual([3]);
expect(v.read().dataSync()).toEqual(new Float32Array([1, 1, 1]));
});
it('Matrix', () => {
const m = V.onesVariable([2, 2], 'float32', 'Matrix');
expect(m.name.indexOf('Matrix')).toEqual(0);
expect(m.read().shape).toEqual([2, 2]);
expect(m.read().dataSync()).toEqual(new Float32Array([1, 1, 1, 1]));
});
it('3D', () => {
const t = V.onesVariable([2, 2, 2], 'float32', 'Tertiary');
expect(t.name.indexOf('Tertiary')).toEqual(0);
expect(t.read().shape).toEqual([2, 2, 2]);
expect(t.read().dataSync()).toEqual(new Float32Array([
1, 1, 1, 1, 1, 1, 1, 1
]));
});
it('4D', () => {
const q = V.onesVariable([1, 2, 1, 3], 'float32', 'Quaternary');
expect(q.name.indexOf('Quaternary')).toEqual(0);
expect(q.read().shape).toEqual([1, 2, 1, 3]);
expect(q.read().dataSync()).toEqual(new Float32Array([1, 1, 1, 1, 1, 1]));
});
});
describeMathCPUAndGPU('ZerosLike', () => {
it('Scalar', () => {
const s = V.zerosLike(randomUniform([], -10, 10));
expect(s.read().shape).toEqual([]);
expect(s.read().dataSync()).toEqual(new Float32Array([0]));
});
it('Vector', () => {
const v = V.zerosLike(randomUniform([3], -10, 10));
expect(v.read().shape).toEqual([3]);
expect(v.read().dataSync()).toEqual(new Float32Array([0, 0, 0]));
});
it('Matrix', () => {
const m = V.zerosLike(randomUniform([2, 2], -10, 10));
expect(m.read().shape).toEqual([2, 2]);
expect(m.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
});
it('3D', () => {
const t = V.zerosLike(randomUniform([2, 2, 2], -10, 10));
expect(t.read().shape).toEqual([2, 2, 2]);
expect(t.read().dataSync()).toEqual(new Float32Array([
0, 0, 0, 0, 0, 0, 0, 0
]));
});
it('4D', () => {
const q = V.zerosLike(randomUniform([1, 2, 1, 3], -10, 10));
expect(q.read().shape).toEqual([1, 2, 1, 3]);
expect(q.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0, 0, 0]));
});
});
describeMathCPUAndGPU('OnesLike', () => {
it('Scalar', () => {
const s = V.onesLike(randomUniform([], -10, 10));
expect(s.read().shape).toEqual([]);
expect(s.read().dataSync()).toEqual(new Float32Array([1]));
});
it('Vector', () => {
const v = V.onesLike(randomUniform([3], -10, 10));
expect(v.read().shape).toEqual([3]);
expect(v.read().dataSync()).toEqual(new Float32Array([1, 1, 1]));
});
it('Matrix', () => {
const m = V.onesLike(randomUniform([2, 2], -10, 10));
expect(m.read().shape).toEqual([2, 2]);
expect(m.read().dataSync()).toEqual(new Float32Array([1, 1, 1, 1]));
});
it('3D', () => {
const t = V.onesLike(randomUniform([2, 2, 2], -10, 10));
expect(t.read().shape).toEqual([2, 2, 2]);
expect(t.read().dataSync()).toEqual(new Float32Array([
1, 1, 1, 1, 1, 1, 1, 1
]));
});
it('4D', () => {
const q = V.onesLike(randomUniform([1, 2, 1, 3], -10, 10));
expect(q.read().shape).toEqual([1, 2, 1, 3]);
expect(q.read().dataSync()).toEqual(new Float32Array([1, 1, 1, 1, 1, 1]));
});
});
describeMathCPUAndGPU('eye (I-matrix builder)', () => {
it('Variable Zero sized 2D matrix works', () => {
const v = V.eyeVariable(0);
expect(v.shape).toEqual([0, 0]);
});
it('Variable 1 sized 2D matrix', () => {
const I = V.eyeVariable(1);
expect(I.shape).toEqual([1, 1]);
expect(I.read().dataSync()).toEqual(new Float32Array([1]));
});
it('Variable 2 sized 2D matrix', () => {
const I = V.eyeVariable(2);
expect(I.shape).toEqual([2, 2]);
expect(I.read().dataSync()).toEqual(new Float32Array([1, 0, 0, 1]));
});
});
describeMathCPUAndGPU('Variable update', () => {
it('Update', () => {
const v = new V.LayerVariable(scalar(10.0));
V.update(v, scalar(20.0));
expectTensorsClose(v.read(), scalar(20.0));
});
it('Update: Incompatible shape', () => {
const v = new V.LayerVariable(tensor1d([10.0, 20.0]));
const x = tensor1d([10.0, 20.0, 30.0]);
expect(() => V.update(v, x)).toThrowError();
});
it('UpdateAdd', () => {
const v = new V.LayerVariable(scalar(10.0));
V.updateAdd(v, scalar(20.0));
expectTensorsClose(v.read(), scalar(30.0));
});
it('UpdateAdd: Incompatible shape', () => {
const v = new V.LayerVariable(tensor1d([10.0, 20.0]));
const x = tensor1d([0.0, 10.0, 20.0]);
expect(() => V.updateAdd(v, x)).toThrowError();
});
it('UpdateSub', () => {
const v = new V.LayerVariable(scalar(10.0));
V.updateSub(v, scalar(20.0));
const vNew = v.read();
expectTensorsClose(vNew, scalar(-10.0));
});
it('UpdateSub: Incompatible shape', () => {
const v = new V.LayerVariable(tensor1d([10.0, 20.0]));
const x = tensor1d([0.0, 10.0, 20.0]);
expect(() => V.updateSub(v, x)).toThrowError();
});
});
describeMathCPUAndGPU('batchGetValue', () => {
it('Legnth-3 Array, Mixed Tensor and Variable', () => {
const v1 = V.variable(zeros([]));
const v2 = V.variable(zeros([2]));
const v3 = V.variable(zeros([2, 2]));
const values = V.batchGetValue([v1, v2, v3]);
expect(values.length).toEqual(3);
expect(values[0].shape).toEqual([]);
expect(values[0].dataSync()).toEqual(new Float32Array([0]));
expect(values[1].shape).toEqual([2]);
expect(values[1].dataSync()).toEqual(new Float32Array([0, 0]));
expect(values[2].shape).toEqual([2, 2]);
expect(values[2].dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
});
});
describeMathCPUAndGPU('batchSetValue', () => {
it('Update using Tensor values', () => {
const v1 = V.randomUniformVariable([2], 0, 1);
const v2 = V.randomUniformVariable([2, 2], 0, 1);
V.batchSetValue([[v1, zeros([2])], [v2, zeros([2, 2])]]);
expect(v1.shape).toEqual([2]);
expect(v1.read().dataSync()).toEqual(new Float32Array([0, 0]));
expect(v2.shape).toEqual([2, 2]);
expect(v2.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
});
it('Update using Tensor values', () => {
const v1 = V.randomUniformVariable([], 0, 1);
const v2 = V.randomUniformVariable([2, 2, 1], 0, 1);
V.batchSetValue([[v1, zeros([])], [v2, zeros([2, 2, 1])]]);
expect(v1.shape).toEqual([]);
expect(v1.read().dataSync()).toEqual(new Float32Array([0]));
expect(v2.shape).toEqual([2, 2, 1]);
expect(v2.read().dataSync()).toEqual(new Float32Array([0, 0, 0, 0]));
});
it('Update empty Array', () => {
V.batchSetValue([]);
});
});
describeMathCPUAndGPU('gradients', () => {
it('Simple mean: 1 variable', () => {
const var1 = new V.LayerVariable(tfc.mul(scalar(2.0), tfc.ones([2, 2])));
const gradients = V.gradients(() => tfc.mean(var1.read()), [var1]);
expect(gradients.length).toEqual(1);
expectTensorsClose(
tensor2d([[0.25, 0.25], [0.25, 0.25]], [2, 2]), gradients[0]);
});
it('Simple matmul and mean: 2 variables', () => {
const var1 = new V.LayerVariable(tensor2d([[1, 0], [0, 0]], [2, 2]));
const var2 = new V.LayerVariable(tensor2d([[1, 0], [0, 1]], [2, 2]));
const gradients = V.gradients(
() => tfc.mean(K.dot(var1.read(), var2.read())), [var1, var2]);
expect(gradients.length).toEqual(2);
// d(loss) / d(var1).
expectTensorsClose(
tensor2d([[0.25, 0.25], [0.25, 0.25]], [2, 2]), gradients[0]);
// d(loss) / d(var2).
expectTensorsClose(tensor2d([[0.25, 0.25], [0, 0]], [2, 2]), gradients[1]);
});
}); | the_stack |
import * as React from 'react';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { Label } from 'office-ui-fabric-react/lib/Label';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './add-update-template.module.scss';
import { modules, formats } from './editor-toolbar';
import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel';
import AddUpdateTemplatePanelState from './add-update-template-panel-state';
import AddUpdateTemplatePanelProps from './add-update-template-panel-props';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
import { IDragDropEvents } from 'office-ui-fabric-react/lib/utilities/dragdrop/interfaces';
import { DetailsList, IColumn, Selection, DetailsListLayoutMode, IDetailsRowProps, SelectionMode, DetailsRow } from 'office-ui-fabric-react/lib/DetailsList';
import { IColumnReorderOptions } from 'office-ui-fabric-react/lib/DetailsList';
import { MarqueeSelection } from 'office-ui-fabric-react/lib/MarqueeSelection';
import ListService from '../../services/list-service';
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { IconButton } from 'office-ui-fabric-react/lib/Button';
import { ColorPicker } from 'office-ui-fabric-react/lib/ColorPicker';
import { mergeStyles } from 'office-ui-fabric-react/lib/Styling';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
let _draggedItem: any = null;
let _draggedIndex = -1;
let _draggedType: string = "Fields";
export default class AddUpdateTemplate extends React.Component<AddUpdateTemplatePanelProps, AddUpdateTemplatePanelState> {
private listService: ListService;
private _fieldSelection: Selection;
private _itemSelection: Selection;
private _columns: IColumn[] = [
{
key: 'Title',
name: 'Field',
fieldName: 'Title',
minWidth: 120,
isResizable: true,
ariaLabel: 'Operations for Field'
}];
private _itemColumns: IColumn[] = [
{
key: 'Title',
name: 'Field',
fieldName: 'Title',
minWidth: 90,
isResizable: true,
ariaLabel: 'Operations for Field'
}, {
key: 'manage',
name: 'Manage',
fieldName: '',
minWidth: 50,
isResizable: false
}];
private _defautState: any;
private _sectionBackgroundColor: string;
private _sectionFontColor: string;
private _selectedColor: string;
constructor(props) {
super(props);
this.listService = new ListService();
this._sectionBackgroundColor = '#CECECE';
this._sectionFontColor = '#000';
this._selectedColor = '#000';
this._defautState = {
helperItems: [{
Title: 'Drag your fields here'
}],
listId: this.props.listId,
templateColumns: [],
section: {
Title: '',
Id: '',
BackgroundColor: this._sectionBackgroundColor,
FontColor: this._sectionFontColor,
Type: 'Section'
},
columns: this._columns,
itemColumns: this._itemColumns,
isColumnReorderEnabled: false,
frozenColumnCountFromStart: '1',
frozenColumnCountFromEnd: '0',
showColorPicker: false,
isFontColorPicker: false,
sectionErrorMessage: '',
titleErrorMessage: ''
};
this.state = {
...this._defautState,
fields: []
};
this._fieldSelection = new Selection();
this._itemSelection = new Selection();
}
public async componentDidMount() {
let fields: any[] = await this.listService.GetFieldsbyListId(this.props.listId);
this.setState({
fields
});
}
public render() {
const { fields, columns, itemColumns, helperItems } = this.state;
const { Title, Header, Footer, HeaderAdvancedMode, FooterAdvancedMode, SkipBlankColumns } = this.props.template;
const items = this.props.template.Columns;
return (
<div>
<Panel
isOpen={this.props.showTemplatePanel}
type={PanelType.largeFixed}
onDismiss={this._onClosePanel}
isFooterAtBottom={true}
headerText="Add/Update template"
closeButtonAriaLabel="Close"
onRenderFooterContent={this._onRenderFooterContent}
>
<div className={`${styles.AddUpdateTemplate} ms-Grid}`}>
<TextField value={Title} label="Name" errorMessage={this.state.titleErrorMessage} onChanged={(name) => { this.props.onTemplateChanged({ ...this.props.template, Title: name }); this.setState({ titleErrorMessage: '' }); }} />
<Label>Columns (Drag fields from the left table to the right one)</Label>
<div className="ms-Grid-row">
<div className={`ms-Grid-col ms-sm6 ms-md6 ms-lg6`}>
<MarqueeSelection selection={this._fieldSelection}>
<DetailsList
className={styles.detailsList}
isHeaderVisible={false}
layoutMode={DetailsListLayoutMode.fixedColumns}
setKey={'fields'}
items={fields}
columns={columns}
selection={this._fieldSelection}
selectionPreservedOnEmptyClick={true}
dragDropEvents={this._getFieldsDragEvents()}
ariaLabelForSelectionColumn="Toggle selection"
ariaLabelForSelectAllCheckbox="Toggle selection for all items"
/>
</MarqueeSelection>
</div>
<div className={`ms-Grid-col ms-sm6 ms-md6 ms-lg6`}>
{
items.length > 0 ?
<MarqueeSelection selection={this._itemSelection}>
<DetailsList
className={styles.detailsList}
isHeaderVisible={false}
layoutMode={DetailsListLayoutMode.justified}
setKey={'Id'}
items={items}
columns={itemColumns}
selection={this._itemSelection}
selectionPreservedOnEmptyClick={true}
onRenderItemColumn={this._renderItemColumn}
onRenderRow={this._renderRow}
dragDropEvents={this._getDragDropEvents()}
columnReorderOptions={this.state.isColumnReorderEnabled ? this._getColumnReorderOptions() : undefined}
ariaLabelForSelectionColumn="Toggle selection"
ariaLabelForSelectAllCheckbox="Toggle selection for all items"
/>
</MarqueeSelection>
:
<DetailsList
className={styles.detailsList}
isHeaderVisible={false}
items={helperItems}
columns={columns}
selectionMode={SelectionMode.none}
selectionPreservedOnEmptyClick={false}
dragDropEvents={this._getDragDropEvents()}
/>
}
</div>
</div>
<Label>Add section</Label>
<div className="ms-Grid-row">
<div className="ms-Grid-col ms-sm10 ms-md10 ms-lg10">
<TextField errorMessage={this.state.sectionErrorMessage} onChanged={(value) => this.setState({ section: { ...this.state.section, Title: value, Id: value }, sectionErrorMessage: '' })} value={this.state.section.Title} />
</div>
<div className="ms-Grid-col ms-sm1 ms-md2 ms-lg2">
<IconButton iconProps={{ iconName: 'Color' }} title="Background Color" style={{ color: this.state.section.BackgroundColor }} ariaLabel="Background Color" onClick={() => this._openColorPicker(false)} />
<IconButton iconProps={{ iconName: 'FontColor' }} title="Font Color" style={{ color: this.state.section.FontColor }} ariaLabel="Font Color" onClick={() => this._openColorPicker(true)} />
<IconButton iconProps={{ iconName: 'Accept' }} title="Accept" ariaLabel="Accept" onClick={this._addSection} />
</div>
</div>
<Toggle
defaultChecked={HeaderAdvancedMode}
label="Header"
onText="Advanced mode"
offText="Simple mode"
onChanged={this._headerAdvancedToggleChange}
/>
<div className={styles.editorContainer}>
<div hidden={HeaderAdvancedMode}>
<ReactQuill modules={modules} formats={formats} className={styles.quillEditor} value={HeaderAdvancedMode ? '' : Header} onChange={this._headerEditorChange} />
</div>
<div hidden={!HeaderAdvancedMode}>
<TextField multiline rows={11} placeholder="Put your HTML code here..." value={Header} onChanged={(value) => this.props.onTemplateChanged({ ...this.props.template, Header: value })} />
</div>
</div>
<Toggle
defaultChecked={FooterAdvancedMode}
label="Footer"
onText="Advanced mode"
offText="Simple mode"
onChanged={this._footerAdvancedToggleChange}
/>
<div className={styles.editorContainer}>
<div hidden={FooterAdvancedMode}>
<ReactQuill modules={modules} formats={formats} className={styles.quillEditor} value={FooterAdvancedMode ? '' : Footer} onChange={this._footerEditorChange} />
</div>
<div hidden={!FooterAdvancedMode}>
<TextField multiline rows={11} value={Footer} onChanged={(value) => this.props.onTemplateChanged({ ...this.props.template, Footer: value })} placeholder="Put your HTML code here..." />
</div>
</div>
<Toggle
defaultChecked={SkipBlankColumns}
label="Skip blank columns"
onText="On"
offText="Off"
onChanged={this._skipBlankColumnsToggleChange}
/>
</div>
<Dialog
onDismissed={this._closeColorPicker}
isClickableOutsideFocusTrap={true}
isOpen={this.state.showColorPicker}
ignoreExternalFocusing={true}
dialogContentProps={{
type: DialogType.normal,
title: 'Color picker',
showCloseButton: true
}}
modalProps={{
titleAriaId: 'myLabelId',
ignoreExternalFocusing: true,
subtitleAriaId: 'mySubTextId',
isBlocking: true,
containerClassName: 'ms-dialogMainOverride'
}}
>
<ColorPicker color={this._selectedColor} onColorChanged={this._onColorChange} />
<DialogFooter>
<PrimaryButton onClick={this._onColorSelected} text="OK" />
<DefaultButton onClick={this._closeColorPicker} text="Cancel" />
</DialogFooter>
</Dialog>
</Panel>
</div>
);
}
private _skipBlankColumnsToggleChange = (value) => {
this.props.onTemplateChanged({ ...this.props.template, SkipBlankColumns: value });
}
private _headerEditorChange = (value) => {
this.props.onTemplateChanged({ ...this.props.template, Header: value });
}
private _footerEditorChange = (value) => {
this.props.onTemplateChanged({ ...this.props.template, Footer: value });
}
private _headerAdvancedToggleChange = (checked: boolean) => {
this.props.onTemplateChanged({
...this.props.template,
HeaderAdvancedMode: checked
});
}
private _footerAdvancedToggleChange = (checked: boolean) => {
this.props.onTemplateChanged({
...this.props.template,
FooterAdvancedMode: checked
});
}
private _openColorPicker = (isFontColorPicker: boolean) => {
this.setState({
showColorPicker: true,
isFontColorPicker
});
}
private _onColorChange = (color: string): void => {
this._selectedColor = color;
}
private _closeColorPicker = () => {
this.setState({
showColorPicker: false
});
}
private _onColorSelected = () => {
const fontColorChanged = this.state.isFontColorPicker;
this.setState({
showColorPicker: false,
section: {
...this.state.section,
BackgroundColor: !fontColorChanged ? this._selectedColor : this.state.section.BackgroundColor,
FontColor: fontColorChanged ? this._selectedColor : this.state.section.FontColor
}
});
}
private _addSection = () => {
if (this.state.section.Title.length < 1) {
this.setState({
sectionErrorMessage: 'Please enter a name for your section'
});
}
else {
this.setState({
section: this._defautState.section,
sectionErrorMessage: ''
});
this.props.onTemplateChanged(
{
...this.props.template,
Columns: this.props.template.Columns.concat(this.state.section)
}
);
}
}
public _onClosePanel = () => {
this.setState({ ...this._defautState });
this.props.setShowTemplatePanel(false)();
}
private _onRenderFooterContent = (): JSX.Element => {
return (
<div>
<PrimaryButton onClick={this._saveTemplate} style={{ marginRight: '8px' }}>Save</PrimaryButton>
<DefaultButton onClick={() => this._onClosePanel()}>Cancel</DefaultButton>
</div>
);
}
private _saveTemplate = () => {
if (this.props.template.Title.length < 1)
this.setState({
titleErrorMessage: 'Please enter a name for your template'
});
else
this.props.onTemplateSaved();
}
private _renderRow = (props: IDetailsRowProps, defaultRender?: any) => {
if (props.item.Type === 'Section') {
const { BackgroundColor, FontColor } = props.item;
const className = mergeStyles({ backgroundColor: BackgroundColor, color: FontColor });
return <DetailsRow {...props} className={className} />;
}
return <DetailsRow {...props} />;
}
private _renderItemColumn = (item: any, index: number, column: IColumn) => {
const fieldContent = item[column.fieldName || ''];
switch (column.key) {
case 'manage':
return <IconButton className={styles.removeIconContainer} onClick={() => this._onRemoveItem(item)} iconProps={{ iconName: 'Delete' }} title="Delete" ariaLabel="Delete" />;
default:
return <span>{fieldContent}</span>;
}
}
private _onRemoveItem = (item: any) => {
this.props.onTemplateChanged({
...this.props.template,
Columns: this.props.template.Columns.filter(el => el != item)
});
}
// Details list methods
private _handleColumnReorder = (draggedIndex: number, targetIndex: number) => {
const draggedItems = this.state.columns[draggedIndex];
const newColumns: IColumn[] = [...this.state.columns];
// insert before the dropped item
newColumns.splice(draggedIndex, 1);
newColumns.splice(targetIndex, 0, draggedItems);
this.setState({ columns: newColumns });
}
private _getColumnReorderOptions = (): IColumnReorderOptions => {
return {
frozenColumnCountFromStart: parseInt(this.state.frozenColumnCountFromStart, 10),
frozenColumnCountFromEnd: parseInt(this.state.frozenColumnCountFromEnd, 10),
handleColumnReorder: this._handleColumnReorder
};
}
private _getFieldsDragEvents = (): IDragDropEvents => {
return {
canDrop: () => {
return false;
},
canDrag: () => {
return true;
},
onDragEnter: () => {
return 'dragEnter';
}, // return string is the css classes that will be added to the entering element.
onDragLeave: () => {
return;
},
onDragStart: (item?: any, itemIndex?: number, selectedItems?: any[], event?: MouseEvent) => {
_draggedItem = item;
_draggedIndex = itemIndex!;
_draggedType = "Fields";
},
onDragEnd: (item?: any, event?: DragEvent) => {
_draggedItem = null;
_draggedIndex = -1;
}
};
}
private _getDragDropEvents = (): IDragDropEvents => {
return {
canDrop: () => {
return true;
},
canDrag: () => {
return true;
},
onDragEnter: () => {
return 'dragEnter';
}, // return string is the css classes that will be added to the entering element.
onDragLeave: () => {
return;
},
onDrop: (item?: any, event?: DragEvent) => {
if (_draggedItem) {
this._insertAfterItem(item);
}
},
onDragStart: (item?: any, itemIndex?: number, selectedItems?: any[], event?: MouseEvent) => {
_draggedItem = item;
_draggedIndex = itemIndex!;
_draggedType = "Items";
},
onDragEnd: (item?: any, event?: DragEvent) => {
_draggedItem = null;
_draggedIndex = -1;
}
};
}
private _insertAfterItem = (item: any): void => {
const draggedItems = _draggedType === "Fields" ? this._fieldSelection.isIndexSelected(_draggedIndex) ? this._fieldSelection.getSelection() : [_draggedItem] : this._itemSelection.isIndexSelected(_draggedIndex) ? this._itemSelection.getSelection() : [_draggedItem];
const items: any[] = this.props.template.Columns.filter((i: number) => draggedItems.indexOf(i) === -1);
let insertIndex = items.indexOf(item);
// if dragging/dropping on itself, index will be 0.
if (insertIndex === -1) {
insertIndex = 0;
}
// Insert dragged items to the collection
items.splice(insertIndex + 1, 0, ...draggedItems);
// Clear the selection
this._fieldSelection.setAllSelected(false);
// Update the state
this.props.onTemplateChanged({
...this.props.template,
Columns: items
});
}
} | the_stack |
import type {
InitialState,
NavigationState,
PartialState,
} from '@react-navigation/routers';
import escape from 'escape-string-regexp';
import * as queryString from 'query-string';
import findFocusedRoute from './findFocusedRoute';
import type { PathConfigMap } from './types';
import validatePathConfig from './validatePathConfig';
type Options<ParamList extends {}> = {
initialRouteName?: string;
screens: PathConfigMap<ParamList>;
};
type ParseConfig = Record<string, (value: string) => any>;
type RouteConfig = {
screen: string;
regex?: RegExp;
path: string;
pattern: string;
routeNames: string[];
parse?: ParseConfig;
};
type InitialRouteConfig = {
initialRouteName: string;
parentScreens: string[];
};
type ResultState = PartialState<NavigationState> & {
state?: ResultState;
};
type ParsedRoute = {
name: string;
path?: string;
params?: Record<string, any> | undefined;
};
/**
* Utility to parse a path string to initial state object accepted by the container.
* This is useful for deep linking when we need to handle the incoming URL.
*
* @example
* ```js
* getStateFromPath(
* '/chat/jane/42',
* {
* screens: {
* Chat: {
* path: 'chat/:author/:id',
* parse: { id: Number }
* }
* }
* }
* )
* ```
* @param path Path string to parse and convert, e.g. /foo/bar?count=42.
* @param options Extra options to fine-tune how to parse the path.
*/
export default function getStateFromPath<ParamList extends {}>(
path: string,
options?: Options<ParamList>
): ResultState | undefined {
if (options) {
validatePathConfig(options);
}
let initialRoutes: InitialRouteConfig[] = [];
if (options?.initialRouteName) {
initialRoutes.push({
initialRouteName: options.initialRouteName,
parentScreens: [],
});
}
const screens = options?.screens;
let remaining = path
.replace(/\/+/g, '/') // Replace multiple slash (//) with single ones
.replace(/^\//, '') // Remove extra leading slash
.replace(/\?.*$/, ''); // Remove query params which we will handle later
// Make sure there is a trailing slash
remaining = remaining.endsWith('/') ? remaining : `${remaining}/`;
if (screens === undefined) {
// When no config is specified, use the path segments as route names
const routes = remaining
.split('/')
.filter(Boolean)
.map((segment) => {
const name = decodeURIComponent(segment);
return { name };
});
if (routes.length) {
return createNestedStateObject(path, routes, initialRoutes);
}
return undefined;
}
// Create a normalized configs array which will be easier to use
const configs = ([] as RouteConfig[])
.concat(
...Object.keys(screens).map((key) =>
createNormalizedConfigs(
key,
screens as PathConfigMap<object>,
[],
initialRoutes,
[]
)
)
)
.sort((a, b) => {
// Sort config so that:
// - the most exhaustive ones are always at the beginning
// - patterns with wildcard are always at the end
// If 2 patterns are same, move the one with less route names up
// This is an error state, so it's only useful for consistent error messages
if (a.pattern === b.pattern) {
return b.routeNames.join('>').localeCompare(a.routeNames.join('>'));
}
// If one of the patterns starts with the other, it's more exhaustive
// So move it up
if (a.pattern.startsWith(b.pattern)) {
return -1;
}
if (b.pattern.startsWith(a.pattern)) {
return 1;
}
const aParts = a.pattern.split('/');
const bParts = b.pattern.split('/');
for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
// if b is longer, b get higher priority
if (aParts[i] == null) {
return 1;
}
// if a is longer, a get higher priority
if (bParts[i] == null) {
return -1;
}
const aWildCard = aParts[i] === '*' || aParts[i].startsWith(':');
const bWildCard = bParts[i] === '*' || bParts[i].startsWith(':');
// if both are wildcard we compare next component
if (aWildCard && bWildCard) {
continue;
}
// if only a is wild card, b get higher priority
if (aWildCard) {
return 1;
}
// if only b is wild card, a get higher priority
if (bWildCard) {
return -1;
}
}
return bParts.length - aParts.length;
});
// Check for duplicate patterns in the config
configs.reduce<Record<string, RouteConfig>>((acc, config) => {
if (acc[config.pattern]) {
const a = acc[config.pattern].routeNames;
const b = config.routeNames;
// It's not a problem if the path string omitted from a inner most screen
// For example, it's ok if a path resolves to `A > B > C` or `A > B`
const intersects =
a.length > b.length
? b.every((it, i) => a[i] === it)
: a.every((it, i) => b[i] === it);
if (!intersects) {
throw new Error(
`Found conflicting screens with the same pattern. The pattern '${
config.pattern
}' resolves to both '${a.join(' > ')}' and '${b.join(
' > '
)}'. Patterns must be unique and cannot resolve to more than one screen.`
);
}
}
return Object.assign(acc, {
[config.pattern]: config,
});
}, {});
if (remaining === '/') {
// We need to add special handling of empty path so navigation to empty path also works
// When handling empty path, we should only look at the root level config
const match = configs.find(
(config) =>
config.path === '' &&
config.routeNames.every(
// Make sure that none of the parent configs have a non-empty path defined
(name) => !configs.find((c) => c.screen === name)?.path
)
);
if (match) {
return createNestedStateObject(
path,
match.routeNames.map((name) => ({ name })),
initialRoutes,
configs
);
}
return undefined;
}
let result: PartialState<NavigationState> | undefined;
let current: PartialState<NavigationState> | undefined;
// We match the whole path against the regex instead of segments
// This makes sure matches such as wildcard will catch any unmatched routes, even if nested
const { routes, remainingPath } = matchAgainstConfigs(
remaining,
configs.map((c) => ({
...c,
// Add `$` to the regex to make sure it matches till end of the path and not just beginning
regex: c.regex ? new RegExp(c.regex.source + '$') : undefined,
}))
);
if (routes !== undefined) {
// This will always be empty if full path matched
current = createNestedStateObject(path, routes, initialRoutes, configs);
remaining = remainingPath;
result = current;
}
if (current == null || result == null) {
return undefined;
}
return result;
}
const joinPaths = (...paths: string[]): string =>
([] as string[])
.concat(...paths.map((p) => p.split('/')))
.filter(Boolean)
.join('/');
const matchAgainstConfigs = (remaining: string, configs: RouteConfig[]) => {
let routes: ParsedRoute[] | undefined;
let remainingPath = remaining;
// Go through all configs, and see if the next path segment matches our regex
for (const config of configs) {
if (!config.regex) {
continue;
}
const match = remainingPath.match(config.regex);
// If our regex matches, we need to extract params from the path
if (match) {
const matchedParams = config.pattern
?.split('/')
.filter((p) => p.startsWith(':'))
.reduce<Record<string, any>>(
(acc, p, i) =>
Object.assign(acc, {
// The param segments appear every second item starting from 2 in the regex match result
[p]: match![(i + 1) * 2].replace(/\//, ''),
}),
{}
);
routes = config.routeNames.map((name) => {
const config = configs.find((c) => c.screen === name);
const params = config?.path
?.split('/')
.filter((p) => p.startsWith(':'))
.reduce<Record<string, any>>((acc, p) => {
const value = matchedParams[p];
if (value) {
const key = p.replace(/^:/, '').replace(/\?$/, '');
acc[key] = config.parse?.[key] ? config.parse[key](value) : value;
}
return acc;
}, {});
if (params && Object.keys(params).length) {
return { name, params };
}
return { name };
});
remainingPath = remainingPath.replace(match[1], '');
break;
}
}
return { routes, remainingPath };
};
const createNormalizedConfigs = (
screen: string,
routeConfig: PathConfigMap<object>,
routeNames: string[] = [],
initials: InitialRouteConfig[],
parentScreens: string[],
parentPattern?: string
): RouteConfig[] => {
const configs: RouteConfig[] = [];
routeNames.push(screen);
parentScreens.push(screen);
// @ts-expect-error: we can't strongly typecheck this for now
const config = routeConfig[screen];
if (typeof config === 'string') {
// If a string is specified as the value of the key(e.g. Foo: '/path'), use it as the pattern
const pattern = parentPattern ? joinPaths(parentPattern, config) : config;
configs.push(createConfigItem(screen, routeNames, pattern, config));
} else if (typeof config === 'object') {
let pattern: string | undefined;
// if an object is specified as the value (e.g. Foo: { ... }),
// it can have `path` property and
// it could have `screens` prop which has nested configs
if (typeof config.path === 'string') {
if (config.exact && config.path === undefined) {
throw new Error(
"A 'path' needs to be specified when specifying 'exact: true'. If you don't want this screen in the URL, specify it as empty string, e.g. `path: ''`."
);
}
pattern =
config.exact !== true
? joinPaths(parentPattern || '', config.path || '')
: config.path || '';
configs.push(
createConfigItem(
screen,
routeNames,
pattern!,
config.path,
config.parse
)
);
}
if (config.screens) {
// property `initialRouteName` without `screens` has no purpose
if (config.initialRouteName) {
initials.push({
initialRouteName: config.initialRouteName,
parentScreens,
});
}
Object.keys(config.screens).forEach((nestedConfig) => {
const result = createNormalizedConfigs(
nestedConfig,
config.screens as PathConfigMap<object>,
routeNames,
initials,
[...parentScreens],
pattern ?? parentPattern
);
configs.push(...result);
});
}
}
routeNames.pop();
return configs;
};
const createConfigItem = (
screen: string,
routeNames: string[],
pattern: string,
path: string,
parse?: ParseConfig
): RouteConfig => {
// Normalize pattern to remove any leading, trailing slashes, duplicate slashes etc.
pattern = pattern.split('/').filter(Boolean).join('/');
const regex = pattern
? new RegExp(
`^(${pattern
.split('/')
.map((it) => {
if (it.startsWith(':')) {
return `(([^/]+\\/)${it.endsWith('?') ? '?' : ''})`;
}
return `${it === '*' ? '.*' : escape(it)}\\/`;
})
.join('')})`
)
: undefined;
return {
screen,
regex,
pattern,
path,
// The routeNames array is mutated, so copy it to keep the current state
routeNames: [...routeNames],
parse,
};
};
const findParseConfigForRoute = (
routeName: string,
flatConfig: RouteConfig[]
): ParseConfig | undefined => {
for (const config of flatConfig) {
if (routeName === config.routeNames[config.routeNames.length - 1]) {
return config.parse;
}
}
return undefined;
};
// Try to find an initial route connected with the one passed
const findInitialRoute = (
routeName: string,
parentScreens: string[],
initialRoutes: InitialRouteConfig[]
): string | undefined => {
for (const config of initialRoutes) {
if (parentScreens.length === config.parentScreens.length) {
let sameParents = true;
for (let i = 0; i < parentScreens.length; i++) {
if (parentScreens[i].localeCompare(config.parentScreens[i]) !== 0) {
sameParents = false;
break;
}
}
if (sameParents) {
return routeName !== config.initialRouteName
? config.initialRouteName
: undefined;
}
}
}
return undefined;
};
// returns state object with values depending on whether
// it is the end of state and if there is initialRoute for this level
const createStateObject = (
initialRoute: string | undefined,
route: ParsedRoute,
isEmpty: boolean
): InitialState => {
if (isEmpty) {
if (initialRoute) {
return {
index: 1,
routes: [{ name: initialRoute }, route],
};
} else {
return {
routes: [route],
};
}
} else {
if (initialRoute) {
return {
index: 1,
routes: [{ name: initialRoute }, { ...route, state: { routes: [] } }],
};
} else {
return {
routes: [{ ...route, state: { routes: [] } }],
};
}
}
};
const createNestedStateObject = (
path: string,
routes: ParsedRoute[],
initialRoutes: InitialRouteConfig[],
flatConfig?: RouteConfig[]
) => {
let state: InitialState;
let route = routes.shift() as ParsedRoute;
const parentScreens: string[] = [];
let initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);
parentScreens.push(route.name);
state = createStateObject(initialRoute, route, routes.length === 0);
if (routes.length > 0) {
let nestedState = state;
while ((route = routes.shift() as ParsedRoute)) {
initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);
const nestedStateIndex =
nestedState.index || nestedState.routes.length - 1;
nestedState.routes[nestedStateIndex].state = createStateObject(
initialRoute,
route,
routes.length === 0
);
if (routes.length > 0) {
nestedState = nestedState.routes[nestedStateIndex]
.state as InitialState;
}
parentScreens.push(route.name);
}
}
route = findFocusedRoute(state) as ParsedRoute;
route.path = path;
const params = parseQueryParams(
path,
flatConfig ? findParseConfigForRoute(route.name, flatConfig) : undefined
);
if (params) {
route.params = { ...route.params, ...params };
}
return state;
};
const parseQueryParams = (
path: string,
parseConfig?: Record<string, (value: string) => any>
) => {
const query = path.split('?')[1];
const params = queryString.parse(query);
if (parseConfig) {
Object.keys(params).forEach((name) => {
if (parseConfig[name] && typeof params[name] === 'string') {
params[name] = parseConfig[name](params[name] as string);
}
});
}
return Object.keys(params).length ? params : undefined;
}; | the_stack |
import { Observable, fromEventPattern } from 'rxjs'
import { map, filter } from 'rxjs/operators'
import { Message, MessageResponse, MsgType } from '@/typings/message'
import { Mutable } from '@/typings/helpers'
/* --------------------------------------- *\
* #Types
\* --------------------------------------- */
export type StorageArea = 'all' | 'local' | 'sync'
export type StorageChange<T> = {
oldValue?: T
newValue?: T
}
export type StorageUpdate<T> = {
oldValue?: T
newValue: T
}
export type StorageListenerCb<T = any, K extends string = string> = (
changes: {
[field in K]: StorageChange<T>
},
areaName: string
) => void
type onMessageEvent<T extends Message = Message> = (
message: T & { __pageId__?: string },
sender: browser.runtime.MessageSender
) => Promise<any> | boolean | void
/* --------------------------------------- *\
* #Globals
\* --------------------------------------- */
const noop = () => {
/* do nothing */
}
/**
* key: {function} user's callback function
* values: {Map} listeners, key: message type, values: generated or user's callback functions
*/
const messageListeners: WeakMap<
Function,
Map<MsgType | '__DEFAULT_MSGTYPE__', Function>
> = new WeakMap()
/**
* For self page messaging
* key: {function} user's callback function
* values: {Map} listeners, key: message type, values: generated or user's callback functions
*/
const messageSelfListeners: WeakMap<
Function,
Map<MsgType | '__DEFAULT_MSGTYPE__', Function>
> = new WeakMap()
/**
* key: {function} user's callback function
* values: {Map} listeners, key: message type, values: generated or user's callback functions
*/
const storageListeners: WeakMap<
StorageListenerCb,
Map<string, StorageListenerCb>
> = new WeakMap()
/* --------------------------------------- *\
* #Exports
\* --------------------------------------- */
export const storage = {
sync: {
clear: storageClear,
remove: storageRemove,
get: storageGet,
set: storageSet,
/** Only for sync area */
addListener: storageAddListener,
/** Only for sync area */
removeListener: storageRemoveListener,
createStream: storageCreateStream,
get __storageArea__(): 'sync' {
return 'sync'
}
},
local: {
clear: storageClear,
remove: storageRemove,
get: storageGet,
set: storageSet,
/** Only for local area */
addListener: storageAddListener,
/** Only for local area */
removeListener: storageRemoveListener,
createStream: storageCreateStream,
get __storageArea__(): 'local' {
return 'local'
}
},
/** Clear all area */
clear: storageClear,
addListener: storageAddListener,
removeListener: storageRemoveListener,
createStream: storageCreateStream,
get __storageArea__(): 'all' {
return 'all'
}
} as const
/**
* Wraps in-app runtime.sendMessage and tabs.sendMessage
* Does not warp cross extension messaging!
*/
export const message = {
send: messageSend,
addListener: messageAddListener,
removeListener: messageRemoveListener,
createStream: messageCreateStream,
get __self__(): false {
return false
},
self: {
initClient,
initServer,
send: messageSendSelf,
addListener: messageAddListener,
removeListener: messageRemoveListener,
createStream: messageCreateStream,
get __self__(): true {
return true
}
}
} as const
export interface OpenUrlOptions {
url: string
/** use browser.runtime.getURL? */
self?: boolean
/** focus the new tab? default true */
active?: boolean
/** ignore existing url? default true */
unique?: boolean
}
/**
* Open a url on new tab or highlight a existing tab if already opened
*/
export async function openUrl(url: string, self?: boolean): Promise<void>
export async function openUrl(options: OpenUrlOptions): Promise<void>
export async function openUrl(
optionsOrUrl: string | OpenUrlOptions,
self?: boolean
): Promise<void> {
const options: OpenUrlOptions =
typeof optionsOrUrl === 'string'
? { url: optionsOrUrl, self }
: optionsOrUrl
const unique = options.unique !== false
const url = options.self ? browser.runtime.getURL(options.url) : options.url
if (unique) {
const tabs = await browser.tabs.query({ url }).catch(() => [])
if (tabs.length > 0) {
const { index, windowId } = tabs[0]
if (typeof browser.tabs['highlight'] === 'function') {
// Only Chrome supports tab.highlight for now
await browser.tabs['highlight']({ tabs: index, windowId })
}
await browser.windows.update(windowId!, { focused: true })
return
}
}
await browser.tabs.create({
url,
active: options.active !== false
})
}
/* --------------------------------------- *\
* #Storage
\* --------------------------------------- */
type StorageThisTwo = typeof storage.sync | typeof storage.local
type StorageThisThree = StorageThisTwo | typeof storage
function storageClear(): Promise<void>
function storageClear(this: StorageThisThree): Promise<void> {
return this.__storageArea__ === 'all'
? Promise.all([
browser.storage.local.clear(),
browser.storage.sync.clear()
]).then(noop)
: browser.storage[this.__storageArea__].clear()
}
function storageRemove(keys: string | string[]): Promise<void>
function storageRemove(
this: StorageThisTwo,
keys: string | string[]
): Promise<void> {
return browser.storage[this.__storageArea__].remove(keys)
}
function storageGet<T = any>(
key?: string | string[] | null
): Promise<Partial<T>>
function storageGet<T extends Object>(key: T | any): Promise<Partial<T>>
function storageGet<T = any>(this: StorageThisTwo, ...args) {
return browser.storage[this.__storageArea__].get(...args) as Promise<
Partial<T>
>
}
function storageSet(keys: any): Promise<void>
function storageSet(this: StorageThisTwo, keys: any): Promise<void> {
return browser.storage[this.__storageArea__].set(keys)
}
function storageAddListener<T = any>(cb: StorageListenerCb<T>): void
function storageAddListener<T = any, K extends string = string>(
key: K,
cb: StorageListenerCb<T, K>
): void
function storageAddListener(this: StorageThisThree, ...args): void {
let key: string
let cb: StorageListenerCb
if (typeof args[0] === 'function') {
key = ''
cb = args[0]
} else if (typeof args[0] === 'string' && typeof args[1] === 'function') {
key = args[0]
cb = args[1]
} else {
throw new Error('wrong arguments type')
}
let listeners = storageListeners.get(cb)
if (!listeners) {
listeners = new Map()
storageListeners.set(cb, listeners)
}
const listenerKey = this.__storageArea__ + key
let listener = listeners.get(listenerKey)
if (!listener) {
listener = (changes, areaName) => {
if (
(this.__storageArea__ === 'all' || areaName === this.__storageArea__) &&
(!key || key in changes)
) {
cb(changes, areaName)
}
}
listeners.set(listenerKey, listener)
}
return browser.storage.onChanged.addListener(listener)
}
function storageRemoveListener(key: string, cb: StorageListenerCb): void
function storageRemoveListener(cb: StorageListenerCb): void
function storageRemoveListener(this: StorageThisThree, ...args): void {
let key: string
let cb: StorageListenerCb
if (typeof args[0] === 'function') {
key = ''
cb = args[0]
} else if (typeof args[0] === 'string' && typeof args[1] === 'function') {
key = args[0]
cb = args[1]
} else {
throw new Error('wrong arguments type')
}
const listeners = storageListeners.get(cb)
if (listeners) {
if (key) {
// remove 'cb' listeners with 'key' under 'storageArea'
const listenerKey = this.__storageArea__ + key
const listener = listeners.get(listenerKey)
if (listener) {
browser.storage.onChanged.removeListener(listener)
listeners.delete(listenerKey)
if (listeners.size <= 0) {
storageListeners.delete(cb)
}
return
}
} else {
// remove all 'cb' listeners under 'storageArea'
listeners.forEach(listener => {
browser.storage.onChanged.removeListener(listener)
})
storageListeners.delete(cb)
return
}
}
browser.storage.onChanged.removeListener(cb)
}
function storageCreateStream<T = any>(key: string): Observable<StorageChange<T>>
function storageCreateStream<T = any>(
this: StorageThisThree,
key: string
): Observable<StorageChange<T>> {
if (!key) {
throw new Error('Missing key')
}
return fromEventPattern<StorageChange<T>>(
handler => this.addListener(key, handler as StorageListenerCb),
handler => this.removeListener(key, handler as StorageListenerCb)
).pipe(
filter(args =>
Object.prototype.hasOwnProperty.call(
Array.isArray(args) ? args[0] : args,
key
)
),
map(args => (Array.isArray(args) ? args[0][key] : args[key]))
)
}
/* --------------------------------------- *\
* #Message
\* --------------------------------------- */
type MessageThis = typeof message | typeof message.self
function messageSend<T extends MsgType, R = MessageResponse<T>>(
message: Message<T>
): Promise<R>
function messageSend<T extends MsgType, R = MessageResponse<T>>(
tabId: number,
message: Message<T>
): Promise<R>
function messageSend<T extends MsgType>(
...args: [Message<T>] | [number, Message<T>]
): Promise<any> {
let callContext: Error
if (process.env.DEBUG) {
callContext = new Error('Message Call Context')
}
return (args.length === 1
? browser.runtime.sendMessage(args[0])
: browser.tabs.sendMessage(args[0], args[1])
).catch(err => {
if (process.env.DEBUG) {
console.warn(err.message, ...args, callContext)
}
})
}
async function messageSendSelf<T extends MsgType, R = undefined>(
message: Message<T>
): Promise<R extends undefined ? MessageResponse<T> : R> {
let callContext: Error
if (process.env.DEBUG) {
callContext = new Error('Message Call Context')
}
if (window.pageId === undefined) {
await initClient()
}
return browser.runtime
.sendMessage(
Object.assign({}, message, {
__pageId__: window.pageId,
type: `[[${message.type}]]`
})
)
.catch(err => {
if (process.env.DEBUG) {
console.warn(err.message, message, callContext)
}
})
}
function messageAddListener<T extends MsgType>(
messageType: T,
cb: onMessageEvent<Message<T>>
): void
function messageAddListener<T extends MsgType>(
cb: onMessageEvent<Message>
): void
function messageAddListener<T extends MsgType>(
this: MessageThis,
...args: [T, onMessageEvent<Message<T>>] | [onMessageEvent<Message>]
): void {
if (window.pageId === undefined) {
initClient()
}
const allListeners = this.__self__ ? messageSelfListeners : messageListeners
const messageType = args.length === 1 ? undefined : args[0]
const cb = args.length === 1 ? args[0] : args[1]
let listeners = allListeners.get(cb)
if (!listeners) {
listeners = new Map()
allListeners.set(cb, listeners)
}
let listener = listeners.get(messageType || '__DEFAULT_MSGTYPE__')
if (!listener) {
listener = ((message, sender) => {
if (
message &&
(this.__self__
? window.pageId === message.__pageId__
: !message.__pageId__)
) {
if (messageType == null || message.type === messageType) {
return cb(message as Message<T> & { __pageId__?: string }, sender)
}
}
}) as onMessageEvent
listeners.set(messageType || '__DEFAULT_MSGTYPE__', listener)
}
// object is handled
return browser.runtime.onMessage.addListener(listener as any)
}
function messageRemoveListener(
messageType: Message['type'],
cb: onMessageEvent
): void
function messageRemoveListener(cb: onMessageEvent): void
function messageRemoveListener(
this: MessageThis,
...args: [Message['type'], onMessageEvent] | [onMessageEvent]
): void {
const allListeners = this.__self__ ? messageSelfListeners : messageListeners
const messageType = args.length === 1 ? undefined : args[0]
const cb = args.length === 1 ? args[0] : args[1]
const listeners = allListeners.get(cb)
if (listeners) {
if (messageType) {
const listener = listeners.get(messageType)
if (listener) {
// @ts-ignore
browser.runtime.onMessage.removeListener(listener)
listeners.delete(messageType)
if (listeners.size <= 0) {
allListeners.delete(cb)
}
return
}
} else {
// delete all cb related callbacks
listeners.forEach(listener =>
// @ts-ignore
browser.runtime.onMessage.removeListener(listener)
)
allListeners.delete(cb)
return
}
}
// @ts-ignore
browser.runtime.onMessage.removeListener(cb)
}
function messageCreateStream<T extends MsgType>(
messageType?: T
): Observable<Message<T>>
function messageCreateStream<T extends MsgType>(
this: MessageThis,
messageType?: T
): Observable<Message<T>> {
const pattern$ = messageType
? fromEventPattern<Message<T>>(
handler => this.addListener(messageType, handler),
handler => this.removeListener(messageType, handler)
)
: fromEventPattern<Message<T>>(
handler => this.addListener(handler),
handler => this.removeListener(handler)
)
// Arguments could be an array if there are multiple values emitted.
return pattern$.pipe(map(args => (Array.isArray(args) ? args[0] : args)))
}
/**
* Deploy page script for self-messaging
* This method is called on the first sendMessage
*/
function initClient(): Promise<typeof window.pageId> {
if (window.pageId === undefined) {
return message
.send<'PAGE_INFO'>({ type: 'PAGE_INFO' })
.then(({ pageId, faviconURL, pageTitle, pageURL }) => {
window.pageId = pageId
window.faviconURL = faviconURL
if (pageTitle) {
window.pageTitle = pageTitle
}
if (pageURL) {
window.pageURL = pageURL
}
return pageId
})
} else {
return Promise.resolve(window.pageId)
}
}
/**
* Deploy background proxy for self-messaging
* This method should be invoked in background script
*/
function initServer(): void {
window.pageId = 'background page'
const selfMsgTester = /^\[\[(.+)\]\]$/
browser.runtime.onMessage.addListener(
(message: object, sender: browser.runtime.MessageSender) => {
if (!message || !message['type']) {
return
}
if ((message as Message).type === 'PAGE_INFO') {
return Promise.resolve(_getPageInfo(sender))
}
const selfMsg = selfMsgTester.exec((message as Message).type)
if (selfMsg) {
;(message as Mutable<Message>).type = selfMsg[1] as MsgType
const tabId = sender.tab && sender.tab.id
if (tabId) {
return messageSend(tabId, message as Message)
} else {
return messageSend(message as Message)
}
}
}
)
}
function _getPageInfo(sender: browser.runtime.MessageSender) {
const result = {
pageId: '' as string | number,
faviconURL: '',
pageTitle: '',
pageURL: ''
}
const tab = sender.tab
if (tab) {
result.pageId = tab.id || ''
if (tab.favIconUrl) {
result.faviconURL = tab.favIconUrl
}
if (tab.url) {
result.pageURL = tab.url
}
if (tab.title) {
result.pageTitle = tab.title
}
} else {
// FRAGILE: Assume only browser action page is tabless
result.pageId = 'popup'
if (sender.url && !sender.url.startsWith('http')) {
result.faviconURL = 'https://saladict.crimx.com/favicon.ico'
}
}
return result
} | the_stack |
import ClipboardData from './ClipboardData';
import ContentChangedData from './ContentChangedData';
import EditorPlugin from './EditorPlugin';
import NodePosition from './NodePosition';
import TableSelection from './TableSelection';
import { ChangeSource } from '../enum/ChangeSource';
import { ColorTransformDirection } from '../enum/ColorTransformDirection';
import { ContentMetadata } from './ContentMetadata';
import { DOMEventHandler } from '../type/domEventHandler';
import { GetContentMode } from '../enum/GetContentMode';
import { InsertOption } from './InsertOption';
import { PendableFormatState, StyleBasedFormatState } from './FormatState';
import { PluginEvent } from '../event/PluginEvent';
import { PluginState } from './CorePlugins';
import { SelectionRangeEx } from './SelectionRangeEx';
import { SizeTransformer } from '../type/SizeTransformer';
import { TableSelectionRange } from './SelectionRangeEx';
import { TrustedHTMLHandler } from '../type/TrustedHTMLHandler';
import type { CompatibleChangeSource } from '../compatibleEnum/ChangeSource';
import type { CompatibleColorTransformDirection } from '../compatibleEnum/ColorTransformDirection';
import type { CompatibleGetContentMode } from '../compatibleEnum/GetContentMode';
/**
* Represents the core data structure of an editor
*/
export default interface EditorCore extends PluginState {
/**
* The content DIV element of this editor
*/
readonly contentDiv: HTMLDivElement;
/**
* An array of editor plugins.
*/
readonly plugins: EditorPlugin[];
/**
* Core API map of this editor
*/
readonly api: CoreApiMap;
/**
* Original API map of this editor. Overridden core API can use API from this map to call the original version of core API.
*/
readonly originalApi: CoreApiMap;
/**
* A handler to convert HTML string to a trust HTML string.
* By default it will just return the original HTML string directly.
* To override, pass your own trusted HTML handler to EditorOptions.trustedHTMLHandler
*/
readonly trustedHTMLHandler: TrustedHTMLHandler;
/*
* Current zoom scale, default value is 1
* When editor is put under a zoomed container, need to pass the zoom scale number using this property
* to let editor behave correctly especially for those mouse drag/drop behaviors
*/
zoomScale: number;
/**
* @deprecated Use zoomScale instead
*/
sizeTransformer: SizeTransformer;
}
/**
* Call an editing callback with adding undo snapshots around, and trigger a ContentChanged event if change source is specified.
* Undo snapshot will not be added if this call is nested inside another addUndoSnapshot() call.
* @param core The EditorCore object
* @param callback The editing callback, accepting current selection start and end position, returns an optional object used as the data field of ContentChangedEvent.
* @param changeSource The ChangeSource string of ContentChangedEvent. @default ChangeSource.Format. Set to null to avoid triggering ContentChangedEvent
* @param canUndoByBackspace True if this action can be undone when user press Backspace key (aka Auto Complete).
* @param additionalData Optional parameter to provide additional data related to the ContentChanged Event.
*/
export type AddUndoSnapshot = (
core: EditorCore,
callback: (start: NodePosition, end: NodePosition) => any,
changeSource: ChangeSource | CompatibleChangeSource | string,
canUndoByBackspace: boolean,
additionalData?: ContentChangedData
) => void;
/**
* Attach a DOM event to the editor content DIV
* @param core The EditorCore object
* @param eventMap A map from event name to its handler
*/
export type AttachDomEvent = (
core: EditorCore,
eventMap: Record<string, DOMEventHandler>
) => () => void;
/**
* Create a DocumentFragment for paste from a ClipboardData
* @param core The EditorCore object.
* @param clipboardData Clipboard data retrieved from clipboard
* @param position The position to paste to
* @param pasteAsText True to force use plain text as the content to paste, false to choose HTML or Image if any
* @param applyCurrentStyle True if apply format of current selection to the pasted content,
* false to keep original format
*/
export type CreatePasteFragment = (
core: EditorCore,
clipboardData: ClipboardData,
position: NodePosition,
pasteAsText: boolean,
applyCurrentStyle: boolean
) => DocumentFragment;
/**
* Ensure user will type into a container element rather than into the editor content DIV directly
* @param core The EditorCore object.
* @param position The position that user is about to type to
* @param keyboardEvent Optional keyboard event object
*/
export type EnsureTypeInContainer = (
core: EditorCore,
position: NodePosition,
keyboardEvent?: KeyboardEvent
) => void;
/**
* Focus to editor. If there is a cached selection range, use it as current selection
* @param core The EditorCore object
*/
export type Focus = (core: EditorCore) => void;
/**
* Get current editor content as HTML string
* @param core The EditorCore object
* @param mode specify what kind of HTML content to retrieve
* @returns HTML string representing current editor content
*/
export type GetContent = (
core: EditorCore,
mode: GetContentMode | CompatibleGetContentMode
) => string;
/**
* Get current or cached selection range
* @param core The EditorCore object
* @param tryGetFromCache Set to true to retrieve the selection range from cache if editor doesn't own the focus now
* @returns A Range object of the selection range
*/
export type GetSelectionRange = (core: EditorCore, tryGetFromCache: boolean) => Range;
/**
* Get current selection range
* @param core The EditorCore object
* @returns A Range object of the selection range
*/
export type GetSelectionRangeEx = (core: EditorCore) => SelectionRangeEx;
/**
* Get style based format state from current selection, including font name/size and colors
* @param core The EditorCore objects
* @param node The node to get style from
*/
export type GetStyleBasedFormatState = (core: EditorCore, node: Node) => StyleBasedFormatState;
/**
* Get the pendable format such as underline and bold
* @param core The EditorCore object
* @param forceGetStateFromDOM If set to true, will force get the format state from DOM tree.
* @return The pending format state of editor.
*/
export type GetPendableFormatState = (
core: EditorCore,
forceGetStateFromDOM: boolean
) => PendableFormatState;
/**
* Check if the editor has focus now
* @param core The EditorCore object
* @returns True if the editor has focus, otherwise false
*/
export type HasFocus = (core: EditorCore) => boolean;
/**
* Insert a DOM node into editor content
* @param core The EditorCore object. No op if null.
* @param option An insert option object to specify how to insert the node
*/
export type InsertNode = (core: EditorCore, node: Node, option: InsertOption) => boolean;
/**
* Restore an undo snapshot into editor
* @param core The editor core object
* @param step Steps to move, can be 0, positive or negative
*/
export type RestoreUndoSnapshot = (core: EditorCore, step: number) => void;
/**
* Change the editor selection to the given range
* @param core The EditorCore object
* @param range The range to select
* @param skipSameRange When set to true, do nothing if the given range is the same with current selection
* in editor, otherwise it will always remove current selection range and set to the given one.
* This parameter is always treated as true in Edge to avoid some weird runtime exception.
*/
export type SelectRange = (core: EditorCore, range: Range, skipSameRange?: boolean) => boolean;
/**
* Set HTML content to this editor. All existing content will be replaced. A ContentChanged event will be triggered
* if triggerContentChangedEvent is set to true
* @param core The EditorCore object
* @param content HTML content to set in
* @param triggerContentChangedEvent True to trigger a ContentChanged event. Default value is true
*/
export type SetContent = (
core: EditorCore,
content: string,
triggerContentChangedEvent: boolean,
metadata?: ContentMetadata
) => void;
/**
* Switch the Shadow Edit mode of editor On/Off
* @param core The EditorCore object
* @param isOn True to switch On, False to switch Off
*/
export type SwitchShadowEdit = (core: EditorCore, isOn: boolean) => void;
/**
* Edit and transform color of elements between light mode and dark mode
* @param core The EditorCore object
* @param rootNode The root HTML node to transform
* @param includeSelf True to transform the root node as well, otherwise false
* @param callback The callback function to invoke before do color transformation
* @param direction To specify the transform direction, light to dark, or dark to light
* @param forceTransform By default this function will only work when editor core is in dark mode.
* Pass true to this value to force do color transformation even editor core is in light mode
*/
export type TransformColor = (
core: EditorCore,
rootNode: Node,
includeSelf: boolean,
callback: () => void,
direction: ColorTransformDirection | CompatibleColorTransformDirection,
forceTransform?: boolean
) => void;
/**
* Trigger a plugin event
* @param core The EditorCore object
* @param pluginEvent The event object to trigger
* @param broadcast Set to true to skip the shouldHandleEventExclusively check
*/
export type TriggerEvent = (core: EditorCore, pluginEvent: PluginEvent, broadcast: boolean) => void;
/**
* Select a table and save data of the selected range
* @param core The EditorCore object
* @param table table to select
* @param coordinates first and last cell of the selection, if this parameter is null, instead of
* selecting, will unselect the table.
* @returns true if successful
*/
export type SelectTable = (
core: EditorCore,
table: HTMLTableElement,
coordinates?: TableSelection
) => TableSelectionRange;
/**
* The interface for the map of core API.
* Editor can call call API from this map under EditorCore object
*/
export interface CoreApiMap {
/**
* Call an editing callback with adding undo snapshots around, and trigger a ContentChanged event if change source is specified.
* Undo snapshot will not be added if this call is nested inside another addUndoSnapshot() call.
* @param core The EditorCore object
* @param callback The editing callback, accepting current selection start and end position, returns an optional object used as the data field of ContentChangedEvent.
* @param changeSource The ChangeSource string of ContentChangedEvent. @default ChangeSource.Format. Set to null to avoid triggering ContentChangedEvent
* @param canUndoByBackspace True if this action can be undone when user presses Backspace key (aka Auto Complete).
*/
addUndoSnapshot: AddUndoSnapshot;
/**
* Attach a DOM event to the editor content DIV
* @param core The EditorCore object
* @param eventName The DOM event name
* @param pluginEventType Optional event type. When specified, editor will trigger a plugin event with this name when the DOM event is triggered
* @param beforeDispatch Optional callback function to be invoked when the DOM event is triggered before trigger plugin event
*/
attachDomEvent: AttachDomEvent;
/**
* Create a DocumentFragment for paste from a ClipboardData
* @param core The EditorCore object.
* @param clipboardData Clipboard data retrieved from clipboard
* @param position The position to paste to
* @param pasteAsText True to force use plain text as the content to paste, false to choose HTML or Image if any
* @param applyCurrentStyle True if apply format of current selection to the pasted content,
* false to keep original format
*/
createPasteFragment: CreatePasteFragment;
/**
* Ensure user will type into a container element rather than into the editor content DIV directly
* @param core The EditorCore object.
* @param position The position that user is about to type to
* @param keyboardEvent Optional keyboard event object
*/
ensureTypeInContainer: EnsureTypeInContainer;
/**
* Focus to editor. If there is a cached selection range, use it as current selection
* @param core The EditorCore object
*/
focus: Focus;
/**
* Get current editor content as HTML string
* @param core The EditorCore object
* @param mode specify what kind of HTML content to retrieve
* @returns HTML string representing current editor content
*/
getContent: GetContent;
/**
* Get current or cached selection range
* @param core The EditorCore object
* @param tryGetFromCache Set to true to retrieve the selection range from cache if editor doesn't own the focus now
* @returns A Range object of the selection range
*/
getSelectionRange: GetSelectionRange;
/**
* Get current or cached selection range
* @param core The EditorCore object
* @param tryGetFromCache Set to true to retrieve the selection range from cache if editor doesn't own the focus now
* @returns A Range object of the selection range
*/
getSelectionRangeEx: GetSelectionRangeEx;
/**
* Get style based format state from current selection, including font name/size and colors
* @param core The EditorCore objects
* @param node The node to get style from
*/
getStyleBasedFormatState: GetStyleBasedFormatState;
/**
* Get the pendable format such as underline and bold
* @param core The EditorCore object
*@param forceGetStateFromDOM If set to true, will force get the format state from DOM tree.
* @return The pending format state of editor.
*/
getPendableFormatState: GetPendableFormatState;
/**
* Check if the editor has focus now
* @param core The EditorCore object
* @returns True if the editor has focus, otherwise false
*/
hasFocus: HasFocus;
/**
* Insert a DOM node into editor content
* @param core The EditorCore object. No op if null.
* @param option An insert option object to specify how to insert the node
*/
insertNode: InsertNode;
/**
* Restore an undo snapshot into editor
* @param core The editor core object
* @param step Steps to move, can be 0, positive or negative
*/
restoreUndoSnapshot: RestoreUndoSnapshot;
/**
* Change the editor selection to the given range
* @param core The EditorCore object
* @param range The range to select
* @param skipSameRange When set to true, do nothing if the given range is the same with current selection
* in editor, otherwise it will always remove current selection range and set to the given one.
* This parameter is always treated as true in Edge to avoid some weird runtime exception.
*/
selectRange: SelectRange;
/**
* Set HTML content to this editor. All existing content will be replaced. A ContentChanged event will be triggered
* if triggerContentChangedEvent is set to true
* @param core The EditorCore object
* @param content HTML content to set in
* @param triggerContentChangedEvent True to trigger a ContentChanged event. Default value is true
*/
setContent: SetContent;
/**
* Switch the Shadow Edit mode of editor On/Off
* @param core The EditorCore object
* @param isOn True to switch On, False to switch Off
*/
switchShadowEdit: SwitchShadowEdit;
/**
* Edit and transform color of elements between light mode and dark mode
* @param core The EditorCore object
* @param rootNode The root HTML element to transform
* @param includeSelf True to transform the root node as well, otherwise false
* @param callback The callback function to invoke before do color transformation
* @param direction To specify the transform direction, light to dark, or dark to light
* @param forceTransform By default this function will only work when editor core is in dark mode.
* Pass true to this value to force do color transformation even editor core is in light mode
*/
transformColor: TransformColor;
/**
* Trigger a plugin event
* @param core The EditorCore object
* @param pluginEvent The event object to trigger
* @param broadcast Set to true to skip the shouldHandleEventExclusively check
*/
triggerEvent: TriggerEvent;
/**
* Select a table and save data of the selected range
* @param core The EditorCore object
* @param table table to select
* @param coordinates first and last cell of the selection, if this parameter is null, instead of
* selecting, will unselect the table.
* @param shouldAddStyles Whether need to update the style elements
* @returns true if successful
*/
selectTable: SelectTable;
} | the_stack |
import { should } from 'chai';
import { tokenize, Input, Token } from './utils/tokenize';
describe("Verbatim identifier", () => {
before(() => { should() });
describe("Verbatim identifier", () => {
it("in extern alias directive", async () => {
const input = `
extern alias @foo;
extern alias @class;
extern alias @namespace;
`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Extern,
Token.Keywords.Alias,
Token.Variables.Alias("@foo"),
Token.Punctuation.Semicolon,
Token.Keywords.Extern,
Token.Keywords.Alias,
Token.Variables.Alias("@class"),
Token.Punctuation.Semicolon,
Token.Keywords.Extern,
Token.Keywords.Alias,
Token.Variables.Alias("@namespace"),
Token.Punctuation.Semicolon]);
});
it("in using directive", async () => {
const input = `
using @if;
using @class;
using @Foo.Bar;
using@Foo.Baz;
`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Using,
Token.Identifiers.NamespaceName("@if"),
Token.Punctuation.Semicolon,
Token.Keywords.Using,
Token.Identifiers.NamespaceName("@class"),
Token.Punctuation.Semicolon,
Token.Keywords.Using,
Token.Identifiers.NamespaceName("@Foo"),
Token.Identifiers.NamespaceName("Bar"),
Token.Punctuation.Semicolon,
Token.Keywords.Using,
Token.Identifiers.NamespaceName("@Foo"),
Token.Identifiers.NamespaceName("Baz"),
Token.Punctuation.Semicolon]);
});
it("in attribute's named argument", async () => {
const input = `[Foo(@class = 1)]`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Punctuation.OpenBracket,
Token.Type("Foo"),
Token.Punctuation.OpenParen,
Token.Identifiers.PropertyName("@class"),
Token.Operators.Assignment,
Token.Literals.Numeric.Decimal("1"),
Token.Punctuation.CloseParen,
Token.Punctuation.CloseBracket]);
});
it("in namespace directive", async () => {
const input = `
namespace @class
{
}
`;
let tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Namespace,
Token.Identifiers.NamespaceName("@class"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in class declaration", async () => {
const input = `
public class @class { }
public class @ClassName { }
`;
let tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Class,
Token.Identifiers.ClassName("@class"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Class,
Token.Identifiers.ClassName("@ClassName"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in delegate declaration", async () => {
const input = `delegate void @class();`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Delegate,
Token.PrimitiveType.Void,
Token.Identifiers.DelegateName("@class"),
Token.Punctuation.OpenParen,
Token.Punctuation.CloseParen,
Token.Punctuation.Semicolon]);
});
it("in enum declaration", async () => {
const input = `enum @class { }`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Enum,
Token.Identifiers.EnumName("@class"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in enum member", async () => {
const input = `
enum E
{
@class = 1,
@sufix,
other
}
`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Enum,
Token.Identifiers.EnumName("E"),
Token.Punctuation.OpenBrace,
Token.Identifiers.EnumMemberName("@class"),
Token.Operators.Assignment,
Token.Literals.Numeric.Decimal("1"),
Token.Punctuation.Comma,
Token.Identifiers.EnumMemberName("@sufix"),
Token.Punctuation.Comma,
Token.Identifiers.EnumMemberName("other"),
Token.Punctuation.CloseBrace]);
});
it("in interface declaration", async () => {
const input = `
public interface @interface { }
public interface @IClassName { }
`;
let tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Interface,
Token.Identifiers.InterfaceName("@interface"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Interface,
Token.Identifiers.InterfaceName("@IClassName"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in struct declaration", async () => {
const input = `
public struct @class { }
public struct @StructName { }
`;
let tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Struct,
Token.Identifiers.StructName("@class"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Struct,
Token.Identifiers.StructName("@StructName"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in type parameter list", async () => {
const input = `
public class Foo<@class, Bar> { }
public class Baz<@Bar, T> { }
`;
let tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Class,
Token.Identifiers.ClassName("Foo"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("@class"),
Token.Punctuation.Comma,
Token.Identifiers.TypeParameterName("Bar"),
Token.Punctuation.TypeParameters.End,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Modifiers.Public,
Token.Keywords.Class,
Token.Identifiers.ClassName("Baz"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("@Bar"),
Token.Punctuation.Comma,
Token.Identifiers.TypeParameterName("T"),
Token.Punctuation.TypeParameters.End,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in generic constraints", async () => {
const input = `class S<T1, T2> where T1 : @class { }`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Class,
Token.Identifiers.ClassName("S"),
Token.Punctuation.TypeParameters.Begin,
Token.Identifiers.TypeParameterName("T1"),
Token.Punctuation.Comma,
Token.Identifiers.TypeParameterName("T2"),
Token.Punctuation.TypeParameters.End,
Token.Keywords.Where,
Token.Type("T1"),
Token.Punctuation.Colon,
Token.Type("@class"),
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in field declaration", async () => {
const input = Input.InClass(`private String @class;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Private,
Token.Type("String"),
Token.Identifiers.FieldName("@class"),
Token.Punctuation.Semicolon]);
});
it("in property declaration", async () => {
const input = Input.InClass(`public Boolean @public { get; set; }`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Type("Boolean"),
Token.Identifiers.PropertyName("@public"),
Token.Punctuation.OpenBrace,
Token.Keywords.Get,
Token.Punctuation.Semicolon,
Token.Keywords.Set,
Token.Punctuation.Semicolon,
Token.Punctuation.CloseBrace]);
});
it("in indexer declaration", async () => {
const input = Input.InInterface(`string this[string @class] { get; set; }`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.PrimitiveType.String,
Token.Keywords.This,
Token.Punctuation.OpenBracket,
Token.PrimitiveType.String,
Token.Identifiers.ParameterName("@class"),
Token.Punctuation.CloseBracket,
Token.Punctuation.OpenBrace,
Token.Keywords.Get,
Token.Punctuation.Semicolon,
Token.Keywords.Set,
Token.Punctuation.Semicolon,
Token.Punctuation.CloseBrace]);
});
it("in event declaration", async () => {
const input = Input.InClass(`public event Type @class;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Event,
Token.Type("Type"),
Token.Identifiers.EventName("@class"),
Token.Punctuation.Semicolon]);
});
it("in method declaration", async () => {
const input = Input.InClass(`public void @void() { }`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.PrimitiveType.Void,
Token.Identifiers.MethodName("@void"),
Token.Punctuation.OpenParen,
Token.Punctuation.CloseParen,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace
]);
});
it("in constructor declaration", async () => {
const input = `
public class @class
{
public @class() { }
}
`;
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Class,
Token.Identifiers.ClassName("@class"),
Token.Punctuation.OpenBrace,
Token.Keywords.Modifiers.Public,
Token.Identifiers.MethodName("@class"),
Token.Punctuation.OpenParen,
Token.Punctuation.CloseParen,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Punctuation.CloseBrace]);
});
it("in destructor declaration", async () => {
const input = Input.InClass(`~@class() { }`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Punctuation.Tilde,
Token.Identifiers.MethodName("@class"),
Token.Punctuation.OpenParen,
Token.Punctuation.CloseParen,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace]);
});
it("in operator declaration", async () => {
const input = Input.InClass(`public static @class operator +(int value) { return null; }`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Modifiers.Static,
Token.Type("@class"),
Token.Keywords.Operator,
Token.Identifiers.MethodName("+"),
Token.Punctuation.OpenParen,
Token.PrimitiveType.Int,
Token.Identifiers.ParameterName("value"),
Token.Punctuation.CloseParen,
Token.Punctuation.OpenBrace,
Token.Keywords.Control.Return,
Token.Literals.Null,
Token.Punctuation.Semicolon,
Token.Punctuation.CloseBrace]);
});
it("in conversion operator declaration", async () => {
const input = Input.InClass(`public static implicit operator @class(int x) { return null; }`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Public,
Token.Keywords.Modifiers.Static,
Token.Keywords.Implicit,
Token.Keywords.Operator,
Token.Type("@class"),
Token.Punctuation.OpenParen,
Token.PrimitiveType.Int,
Token.Identifiers.ParameterName("x"),
Token.Punctuation.CloseParen,
Token.Punctuation.OpenBrace,
Token.Keywords.Control.Return,
Token.Literals.Null,
Token.Punctuation.Semicolon,
Token.Punctuation.CloseBrace]);
});
it("in goto statement", async () => {
const input = Input.InMethod(`
@Make:
var a = 1;
goto @Make;
`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Identifiers.LabelName("@Make"),
Token.Punctuation.Colon,
Token.Keywords.Var,
Token.Identifiers.LocalName("a"),
Token.Operators.Assignment,
Token.Literals.Numeric.Decimal("1"),
Token.Punctuation.Semicolon,
Token.Keywords.Control.Goto,
Token.Identifiers.LabelName("@Make"),
Token.Punctuation.Semicolon]);
});
it("in foreach statement", async () => {
const input = Input.InMethod(`foreach (int @class in @classes) { }`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Control.ForEach,
Token.Punctuation.OpenParen,
Token.PrimitiveType.Int,
Token.Identifiers.LocalName("@class"),
Token.Keywords.Control.In,
Token.Variables.ReadWrite("@classes"),
Token.Punctuation.CloseParen,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
]);
});
it("in catch clause", async () => {
const input = Input.InMethod(`
try
{
}
catch (@class @ex)
{
}`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Control.Try,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Keywords.Control.Catch,
Token.Punctuation.OpenParen,
Token.Type("@class"),
Token.Identifiers.LocalName("@ex"),
Token.Punctuation.CloseParen,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace
]);
});
it("in local variable declaration", async () => {
const input = Input.InMethod(`
var @class = @event.x;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("@class"),
Token.Operators.Assignment,
Token.Variables.Object("@event"),
Token.Punctuation.Accessor,
Token.Variables.Property("x"),
Token.Punctuation.Semicolon
]);
});
it("in local constant declaration", async () => {
const input = Input.InMethod(`
const string @class = obj.@class;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Modifiers.Const,
Token.PrimitiveType.String,
Token.Identifiers.LocalName("@class"),
Token.Operators.Assignment,
Token.Variables.Object("obj"),
Token.Punctuation.Accessor,
Token.Variables.Property("@class"),
Token.Punctuation.Semicolon
]);
});
it("in tuple deconstruction", async () => {
const input = Input.InMethod(`(int x, string @class) = (@count, "test");`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Punctuation.OpenParen,
Token.PrimitiveType.Int,
Token.Identifiers.TupleElementName("x"),
Token.Punctuation.Comma,
Token.PrimitiveType.String,
Token.Identifiers.TupleElementName("@class"),
Token.Punctuation.CloseParen,
Token.Operators.Assignment,
Token.Punctuation.OpenParen,
Token.Variables.ReadWrite("@count"),
Token.Punctuation.Comma,
Token.Punctuation.String.Begin,
Token.Literals.String("test"),
Token.Punctuation.String.End,
Token.Punctuation.CloseParen,
Token.Punctuation.Semicolon
]);
});
it("in declaration expression local", async () => {
const input = Input.InMethod(`M(out int @x, out var @y);`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Identifiers.MethodName("M"),
Token.Punctuation.OpenParen,
Token.Keywords.Modifiers.Out,
Token.PrimitiveType.Int,
Token.Identifiers.LocalName("@x"),
Token.Punctuation.Comma,
Token.Keywords.Modifiers.Out,
Token.Keywords.Var,
Token.Identifiers.LocalName("@y"),
Token.Punctuation.CloseParen,
Token.Punctuation.Semicolon
]);
});
it("in cast expression", async () => {
const input = Input.InMethod(`var x = (@class)@variable;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("x"),
Token.Operators.Assignment,
Token.Punctuation.OpenParen,
Token.Type("@class"),
Token.Punctuation.CloseParen,
Token.Variables.ReadWrite("@variable"),
Token.Punctuation.Semicolon
]);
});
it("in as expression", async () => {
const input = Input.InMethod(`var x = @variable as @class;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("x"),
Token.Operators.Assignment,
Token.Variables.ReadWrite("@variable"),
Token.Keywords.As,
Token.Type("@class"),
Token.Punctuation.Semicolon
]);
});
it("in is expression", async () => {
const input = Input.InMethod(`var x = @variable is @class;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("x"),
Token.Operators.Assignment,
Token.Variables.ReadWrite("@variable"),
Token.Keywords.Is,
Token.Type("@class"),
Token.Punctuation.Semicolon
]);
});
it("in object creation with parameters", async () => {
const input = Input.InMethod(`var x = new @class(@event, y);`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("x"),
Token.Operators.Assignment,
Token.Keywords.New,
Token.Type("@class"),
Token.Punctuation.OpenParen,
Token.Variables.ReadWrite("@event"),
Token.Punctuation.Comma,
Token.Variables.ReadWrite("y"),
Token.Punctuation.CloseParen,
Token.Punctuation.Semicolon
]);
});
it("in array creation", async () => {
const input = Input.InMethod(`@class[] x = new @class[0];`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Type("@class"),
Token.Punctuation.OpenBracket,
Token.Punctuation.CloseBracket,
Token.Identifiers.LocalName("x"),
Token.Operators.Assignment,
Token.Keywords.New,
Token.Type("@class"),
Token.Punctuation.OpenBracket,
Token.Literals.Numeric.Decimal("0"),
Token.Punctuation.CloseBracket,
Token.Punctuation.Semicolon
]);
});
it("in named arguments", async () => {
const input = Input.InMethod(`var x = Test(@default = 1);`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("x"),
Token.Operators.Assignment,
Token.Identifiers.MethodName("Test"),
Token.Punctuation.OpenParen,
Token.Variables.ReadWrite("@default"),
Token.Operators.Assignment,
Token.Literals.Numeric.Decimal("1"),
Token.Punctuation.CloseParen,
Token.Punctuation.Semicolon
]);
});
it("in query expression", async () => {
const input = Input.InMethod(`var query = from @class in numbers`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("query"),
Token.Operators.Assignment,
Token.Keywords.Queries.From,
Token.Identifiers.RangeVariableName("@class"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("numbers")
]);
});
it("in let clause", async () => {
const input = Input.InMethod(`
var earlyBirdQuery =
from sentence in strings
let @words = sentence.Split(' ')
from word in @words
select word;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("earlyBirdQuery"),
Token.Operators.Assignment,
Token.Keywords.Queries.From,
Token.Identifiers.RangeVariableName("sentence"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("strings"),
Token.Keywords.Queries.Let,
Token.Identifiers.RangeVariableName("@words"),
Token.Operators.Assignment,
Token.Variables.Object("sentence"),
Token.Punctuation.Accessor,
Token.Identifiers.MethodName("Split"),
Token.Punctuation.OpenParen,
Token.Punctuation.Char.Begin,
Token.Literals.Char(" "),
Token.Punctuation.Char.End,
Token.Punctuation.CloseParen,
Token.Keywords.Queries.From,
Token.Identifiers.RangeVariableName("word"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("@words"),
Token.Keywords.Queries.Select,
Token.Variables.ReadWrite("word"),
Token.Punctuation.Semicolon
]);
});
it("in join clause", async () => {
const input = Input.InMethod(`
var query =
from category in categories
join @prod in products on category.ID equals @prod.CategoryID into prodGroup
select new { CategoryName = category.Name, Products = prodGroup };`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("query"),
Token.Operators.Assignment,
Token.Keywords.Queries.From,
Token.Identifiers.RangeVariableName("category"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("categories"),
Token.Keywords.Queries.Join,
Token.Identifiers.RangeVariableName("@prod"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("products"),
Token.Keywords.Queries.On,
Token.Variables.Object("category"),
Token.Punctuation.Accessor,
Token.Variables.Property("ID"),
Token.Keywords.Queries.Equals,
Token.Variables.Object("@prod"),
Token.Punctuation.Accessor,
Token.Variables.Property("CategoryID"),
Token.Keywords.Queries.Into,
Token.Identifiers.RangeVariableName("prodGroup"),
Token.Keywords.Queries.Select,
Token.Keywords.New,
Token.Punctuation.OpenBrace,
Token.Variables.ReadWrite("CategoryName"),
Token.Operators.Assignment,
Token.Variables.Object("category"),
Token.Punctuation.Accessor,
Token.Variables.Property("Name"),
Token.Punctuation.Comma,
Token.Variables.ReadWrite("Products"),
Token.Operators.Assignment,
Token.Variables.ReadWrite("prodGroup"),
Token.Punctuation.CloseBrace,
Token.Punctuation.Semicolon
]);
});
it("in join into", async () => {
const input = Input.InMethod(`
var query =
from category in categories
join prod in products on category.ID equals prod.CategoryID into @prodGroup
select new { CategoryName = category.Name, Products = @prodGroup };`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("query"),
Token.Operators.Assignment,
Token.Keywords.Queries.From,
Token.Identifiers.RangeVariableName("category"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("categories"),
Token.Keywords.Queries.Join,
Token.Identifiers.RangeVariableName("prod"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("products"),
Token.Keywords.Queries.On,
Token.Variables.Object("category"),
Token.Punctuation.Accessor,
Token.Variables.Property("ID"),
Token.Keywords.Queries.Equals,
Token.Variables.Object("prod"),
Token.Punctuation.Accessor,
Token.Variables.Property("CategoryID"),
Token.Keywords.Queries.Into,
Token.Identifiers.RangeVariableName("@prodGroup"),
Token.Keywords.Queries.Select,
Token.Keywords.New,
Token.Punctuation.OpenBrace,
Token.Variables.ReadWrite("CategoryName"),
Token.Operators.Assignment,
Token.Variables.Object("category"),
Token.Punctuation.Accessor,
Token.Variables.Property("Name"),
Token.Punctuation.Comma,
Token.Variables.ReadWrite("Products"),
Token.Operators.Assignment,
Token.Variables.ReadWrite("@prodGroup"),
Token.Punctuation.CloseBrace,
Token.Punctuation.Semicolon
]);
});
it("in group into", async () => {
const input = Input.InMethod(`
var results =
from p in people
group p.Car by p.PersonId into @group
select new { PersonId = @group.Key, Cars = @group };`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Keywords.Var,
Token.Identifiers.LocalName("results"),
Token.Operators.Assignment,
Token.Keywords.Queries.From,
Token.Identifiers.RangeVariableName("p"),
Token.Keywords.Queries.In,
Token.Variables.ReadWrite("people"),
Token.Keywords.Queries.Group,
Token.Variables.Object("p"),
Token.Punctuation.Accessor,
Token.Variables.Property("Car"),
Token.Keywords.Queries.By,
Token.Variables.Object("p"),
Token.Punctuation.Accessor,
Token.Variables.Property("PersonId"),
Token.Keywords.Queries.Into,
Token.Identifiers.RangeVariableName("@group"),
Token.Keywords.Queries.Select,
Token.Keywords.New,
Token.Punctuation.OpenBrace,
Token.Variables.ReadWrite("PersonId"),
Token.Operators.Assignment,
Token.Variables.Object("@group"),
Token.Punctuation.Accessor,
Token.Variables.Property("Key"),
Token.Punctuation.Comma,
Token.Variables.ReadWrite("Cars"),
Token.Operators.Assignment,
Token.Variables.ReadWrite("@group"),
Token.Punctuation.CloseBrace,
Token.Punctuation.Semicolon
]);
});
it("in lambda parameters", async () => {
const input = Input.InMethod(`Action<int, int> a = (@x, y) => { };`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Type("Action"),
Token.Punctuation.TypeParameters.Begin,
Token.PrimitiveType.Int,
Token.Punctuation.Comma,
Token.PrimitiveType.Int,
Token.Punctuation.TypeParameters.End,
Token.Identifiers.LocalName("a"),
Token.Operators.Assignment,
Token.Punctuation.OpenParen,
Token.Identifiers.ParameterName("@x"),
Token.Punctuation.Comma,
Token.Identifiers.ParameterName("y"),
Token.Punctuation.CloseParen,
Token.Operators.Arrow,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Punctuation.Semicolon
]);
});
it("in tuple element", async () => {
const input = Input.InMethod(`(int @x, int y) p = point;`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Punctuation.OpenParen,
Token.PrimitiveType.Int,
Token.Identifiers.TupleElementName("@x"),
Token.Punctuation.Comma,
Token.PrimitiveType.Int,
Token.Identifiers.TupleElementName("y"),
Token.Punctuation.CloseParen,
Token.Identifiers.LocalName("p"),
Token.Operators.Assignment,
Token.Variables.ReadWrite("point"),
Token.Punctuation.Semicolon
]);
});
it("in anonymous method expression", async () => {
const input = Input.InMethod(`Action<int> a = @x => { };`);
const tokens = await tokenize(input);
tokens.should.deep.equal([
Token.Type("Action"),
Token.Punctuation.TypeParameters.Begin,
Token.PrimitiveType.Int,
Token.Punctuation.TypeParameters.End,
Token.Identifiers.LocalName("a"),
Token.Operators.Assignment,
Token.Identifiers.ParameterName("@x"),
Token.Operators.Arrow,
Token.Punctuation.OpenBrace,
Token.Punctuation.CloseBrace,
Token.Punctuation.Semicolon
]);
});
});
}); | the_stack |
export default function makeDashboard(integrationId: string) {
return {
annotations: {
list: [
{
builtIn: 1,
datasource: "-- Grafana --",
enable: true,
hide: true,
iconColor: "rgba(0, 211, 255, 1)",
name: "Annotations & Alerts",
type: "dashboard"
}
]
},
editable: true,
gnetId: null,
graphTooltip: 0,
iteration: 1623784884657,
links: [],
panels: [
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 0
},
hiddenSeries: false,
id: 2,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(changefeed_max_behind_nanos{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Max Changefeed Latency",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Max Changefeed Latency",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:162",
format: "ns",
label: "time",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:163",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 8
},
hiddenSeries: false,
id: 10,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(changefeed_emitted_bytes{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
intervalFactor: 2,
legendFormat: "Emitted Bytes",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Sink Byte Traffic",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:215",
format: "short",
label: "bytes",
logBase: 1,
max: "1",
min: "0",
show: true
},
{
$$hashKey: "object:216",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 16
},
hiddenSeries: false,
id: 4,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(changefeed_emitted_messages{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Messages",
refId: "B"
},
{
exemplar: true,
expr: `sum(rate(changefeed_flushes{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Flushes",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Sink Counts",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:319",
format: "short",
label: "actions",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:320",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 24
},
hiddenSeries: false,
id: 6,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(changefeed_emitted_messages{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Message Emit Time",
refId: "B"
},
{
exemplar: true,
expr: `sum(rate(changefeed_flush_nanos{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Flush Time",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Sink Timings",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:372",
format: "ns",
label: "time",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:373",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 8,
w: 24,
x: 0,
y: 32
},
hiddenSeries: false,
id: 8,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(rate(jobs_changefeed_resume_retry_error{integration_id="${integrationId}",instance=~"$node"}[5m]))`,
interval: "",
legendFormat: "Retryable Errors",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Changefeed Restarts",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:476",
format: "short",
label: "actions",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:477",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
}
],
schemaVersion: 27,
style: "dark",
tags: [],
templating: {
list: [
{
allValue: "",
current: {
selected: false,
text: "All",
value: "$__all"
},
datasource: "metrics",
definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`,
description: null,
error: null,
hide: 0,
includeAll: true,
label: "Node",
multi: false,
name: "node",
options: [],
query: {
query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`,
refId: "Prometheus-node-Variable-Query"
},
refresh: 1,
regex: "",
skipUrlSync: false,
sort: 1,
tagValuesQuery: "",
tags: [],
tagsQuery: "",
type: "query",
useTags: false
}
]
},
time: {
from: "now-1h",
to: "now"
},
timepicker: {},
timezone: "browser",
title: "CRDB Console: Changefeeds",
uid: `cha-${integrationId}`,
version: 3
};
}
export type Dashboard = ReturnType<typeof makeDashboard>; | the_stack |
import React, { useEffect, useState } from 'react';
import { DomainDetails, Subnav } from 'components';
import { ResultCard } from './ResultCard';
import {
makeStyles,
Paper,
FormControl,
Select,
MenuItem,
Typography,
Checkbox,
FormControlLabel,
FormGroup,
TextareaAutosize,
Button
} from '@material-ui/core';
import { Pagination } from '@material-ui/lab';
import { withSearch } from '@elastic/react-search-ui';
import { FilterDrawer } from './FilterDrawer';
import { ContextType } from '../../context/SearchProvider';
import { SortBar } from './SortBar';
import {
Button as USWDSButton,
Overlay,
Modal,
ModalContainer,
TextInput,
Label,
Dropdown
} from '@trussworks/react-uswds';
import { useAuthContext } from 'context';
import { FilterTags } from './FilterTags';
import { SavedSearch, Vulnerability } from 'types';
import { useBeforeunload } from 'react-beforeunload';
import { NoResults } from 'components/NoResults';
import { exportCSV } from 'components/ImportExport';
export const DashboardUI: React.FC<ContextType & { location: any }> = (
props
) => {
const {
current,
setCurrent,
resultsPerPage,
setResultsPerPage,
filters,
addFilter,
removeFilter,
results,
facets,
clearFilters,
sortDirection,
sortField,
setSort,
totalPages,
totalResults,
setSearchTerm,
searchTerm,
noResults
} = props;
const classes = useStyles();
const [selectedDomain, setSelectedDomain] = useState('');
const [resultsScrolled, setResultsScrolled] = useState(false);
const {
apiPost,
apiPut,
setLoading,
showAllOrganizations,
currentOrganization
} = useAuthContext();
const search:
| (SavedSearch & {
editing?: boolean;
})
| undefined = localStorage.getItem('savedSearch')
? JSON.parse(localStorage.getItem('savedSearch')!)
: undefined;
const [showSaveSearch, setShowSaveSearch] = useState<Boolean>(
search && search.editing ? true : false
);
const [savedSearchValues, setSavedSearchValues] = useState<
Partial<SavedSearch> & {
name: string;
vulnerabilityTemplate: Partial<Vulnerability>;
}
>(
search
? search
: {
name: '',
vulnerabilityTemplate: {},
createVulnerabilities: false
}
);
const onTextChange: React.ChangeEventHandler<
HTMLInputElement | HTMLSelectElement
> = (e) => onChange(e.target.name, e.target.value);
const onChange = (name: string, value: any) => {
setSavedSearchValues((values) => ({
...values,
[name]: value
}));
};
const onVulnerabilityTemplateChange = (e: any) => {
(savedSearchValues.vulnerabilityTemplate as any)[e.target.name] =
e.target.value;
setSavedSearchValues(savedSearchValues);
};
const handleResultScroll = (e: React.UIEvent<HTMLElement>) => {
if (e.currentTarget.scrollTop > 0) {
setResultsScrolled(true);
} else {
setResultsScrolled(false);
}
};
useEffect(() => {
if (props.location.search === '') {
// Search on initial load
setSearchTerm('');
}
return () => {
localStorage.removeItem('savedSearch');
};
}, [setSearchTerm, props.location.search]);
useBeforeunload((event) => {
localStorage.removeItem('savedSearch');
});
const fetchDomainsExport = async (): Promise<string> => {
try {
const body: any = {
current,
filters,
resultsPerPage,
searchTerm,
sortDirection,
sortField
};
if (!showAllOrganizations && currentOrganization) {
if ('rootDomains' in currentOrganization)
body.organizationId = currentOrganization.id;
else body.tagId = currentOrganization.id;
}
const { url } = await apiPost('/search/export', {
body
});
return url!;
} catch (e) {
console.error(e);
return '';
}
};
return (
<div className={classes.root}>
<FilterDrawer
addFilter={addFilter}
removeFilter={removeFilter}
filters={filters}
facets={facets}
clearFilters={filters.length > 0 ? () => clearFilters([]) : undefined}
/>
<div className={classes.contentWrapper}>
<Subnav
items={[
{ title: 'Search Results', path: '/inventory', exact: true },
{ title: 'All Domains', path: '/inventory/domains' },
{ title: 'All Vulnerabilities', path: '/inventory/vulnerabilities' }
]}
styles={{
paddingLeft: '0%'
}}
>
<FilterTags filters={filters} removeFilter={removeFilter} />
</Subnav>
<SortBar
sortField={sortField}
sortDirection={sortDirection}
setSort={setSort}
isFixed={resultsScrolled}
saveSearch={
filters.length > 0 || searchTerm
? () => setShowSaveSearch(true)
: undefined
}
existingSavedSearch={search}
/>
{noResults && (
<NoResults
message={"We don't see any results that match your criteria."}
></NoResults>
)}
<div className={classes.content}>
<div className={classes.panel} onScroll={handleResultScroll}>
{results.map((result) => (
<ResultCard
key={result.id.raw}
{...result}
onDomainSelected={(id) => setSelectedDomain(id)}
selected={result.id.raw === selectedDomain}
/>
))}
</div>
<div className={classes.panel}>
{selectedDomain && <DomainDetails domainId={selectedDomain} />}
</div>
</div>
<Paper classes={{ root: classes.pagination }}>
<span>
<strong>
{(totalResults === 0
? 0
: (current - 1) * resultsPerPage + 1
).toLocaleString()}{' '}
-{' '}
{Math.min(
(current - 1) * resultsPerPage + resultsPerPage,
totalResults
).toLocaleString()}
</strong>{' '}
of <strong>{totalResults.toLocaleString()}</strong>
</span>
<Pagination
count={totalPages}
page={current}
onChange={(_, page) => setCurrent(page)}
color="primary"
size="small"
/>
<FormControl
variant="outlined"
className={classes.pageSize}
size="small"
>
<Typography id="results-per-page-label">
Results per page:
</Typography>
<Select
id="teststa"
labelId="results-per-page-label"
value={resultsPerPage}
onChange={(e) => setResultsPerPage(e.target.value as number)}
>
{[15, 45, 90].map((perPage) => (
<MenuItem key={perPage} value={perPage}>
{perPage}
</MenuItem>
))}
</Select>
</FormControl>
<Button
className={classes.exportButton}
onClick={() =>
exportCSV(
{
name: 'domains',
getDataToExport: fetchDomainsExport
},
setLoading
)
}
>
Export Results
</Button>
</Paper>
</div>
{showSaveSearch && (
<div>
<Overlay />
<ModalContainer>
<Modal
className={classes.saveSearchModal}
actions={
<>
<USWDSButton
outline
type="button"
onClick={() => {
setShowSaveSearch(false);
}}
>
Cancel
</USWDSButton>
<USWDSButton
type="button"
onClick={async () => {
const body = {
body: {
...savedSearchValues,
searchTerm,
filters,
count: totalResults,
searchPath: window.location.search,
sortField,
sortDirection
}
};
if (search) {
await apiPut('/saved-searches/' + search.id, body);
} else {
await apiPost('/saved-searches/', body);
}
setShowSaveSearch(false);
}}
>
Save
</USWDSButton>
</>
}
title={search ? <h2>Update Search</h2> : <h2>Save Search</h2>}
>
<FormGroup>
<Label htmlFor="name">Name Your Search</Label>
<TextInput
required
id="name"
name="name"
type="text"
value={savedSearchValues.name}
onChange={onTextChange}
/>
<p>When a new result is found:</p>
{/* <FormControlLabel
control={
<Checkbox
// checked={gilad}
// onChange={handleChange}
name="email"
/>
}
label="Email me"
/> */}
<FormControlLabel
control={
<Checkbox
checked={savedSearchValues.createVulnerabilities}
onChange={(e) =>
onChange(e.target.name, e.target.checked)
}
id="createVulnerabilities"
name="createVulnerabilities"
/>
}
label="Create a vulnerability"
/>
{savedSearchValues.createVulnerabilities && (
<>
<Label htmlFor="title">Title</Label>
<TextInput
required
id="title"
name="title"
type="text"
value={savedSearchValues.vulnerabilityTemplate.title}
onChange={onVulnerabilityTemplateChange}
/>
<Label htmlFor="description">Description</Label>
<TextareaAutosize
required
id="description"
name="description"
style={{ padding: 10 }}
rowsMin={2}
value={
savedSearchValues.vulnerabilityTemplate.description
}
onChange={onVulnerabilityTemplateChange}
/>
<Label htmlFor="description">Severity</Label>
<Dropdown
id="severity"
name="severity"
onChange={onVulnerabilityTemplateChange}
value={
savedSearchValues.vulnerabilityTemplate
.severity as string
}
style={{ display: 'inline-block', width: '150px' }}
>
<option value="None">None</option>
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
<option value="Critical">Critical</option>
</Dropdown>
</>
)}
{/* <h3>Collaborators</h3>
<p>
Collaborators can view vulnerabilities, and domains within
this search. Adding a team will make all members
collaborators.
</p>
<button className={classes.addButton} >
<AddCircleOutline></AddCircleOutline> ADD
</button> */}
</FormGroup>
</Modal>
</ModalContainer>
</div>
)}
</div>
);
};
export const Dashboard = withSearch(
({
addFilter,
removeFilter,
results,
totalResults,
filters,
facets,
searchTerm,
setSearchTerm,
autocompletedResults,
clearFilters,
saveSearch,
sortDirection,
sortField,
setSort,
resultsPerPage,
setResultsPerPage,
current,
setCurrent,
totalPages,
noResults
}: ContextType) => ({
addFilter,
removeFilter,
results,
totalResults,
filters,
facets,
searchTerm,
setSearchTerm,
autocompletedResults,
clearFilters,
saveSearch,
sortDirection,
sortField,
setSort,
resultsPerPage,
setResultsPerPage,
current,
setCurrent,
totalPages,
noResults
})
)(DashboardUI);
const useStyles = makeStyles(() => ({
tableRoot: {
marginTop: '0'
},
root: {
position: 'relative',
flex: '1',
width: '100%',
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'stretch',
margin: '0',
overflowY: 'hidden'
},
contentWrapper: {
position: 'relative',
flex: '1 1 auto',
height: '100%',
display: 'flex',
flexFlow: 'column nowrap',
overflowY: 'hidden'
},
status: {
display: 'flex',
margin: '1rem 0 1rem 1rem',
fontSize: '1.2rem',
justifyContent: 'flex-start',
alignItems: 'center'
},
content: {
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'stretch',
flex: '1',
overflowY: 'hidden'
},
panel: {
position: 'relative',
height: '100%',
overflowY: 'auto',
padding: '0 1rem 2rem 1rem',
flex: '0 0 50%'
},
pagination: {
height: 'auto',
flex: 0,
display: 'flex',
flexFlow: 'row nowrap',
justifyContent: 'flex-start',
alignItems: 'center',
boxShadow: '0px -1px 2px rgba(0, 0, 0, 0.15)',
padding: '1rem 2rem',
'& > span': {
marginRight: '2rem'
},
'& *:focus': {
outline: 'none !important'
},
borderRadius: 0,
zIndex: 9
},
exportButton: {
justifyContent: 'flex-end',
marginLeft: 'auto'
},
pageSize: {
'& > p': {
margin: '0 1rem 0 2rem'
},
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'center'
},
saveSearchModal: {},
addButton: {
outline: 'none',
border: 'none',
color: '#71767A',
background: 'none',
cursor: 'pointer'
}
})); | the_stack |
import { BncClient } from '@binance-chain/javascript-sdk/lib/client'
import * as crypto from '@binance-chain/javascript-sdk/lib/crypto'
import { SignedSend } from '@binance-chain/javascript-sdk/lib/types'
import {
Address,
Balance,
BaseXChainClient,
FeeType,
Fees,
Network,
Tx,
TxHash,
TxHistoryParams,
TxParams,
TxsPage,
XChainClient,
XChainClientParams,
singleFee,
} from '@xchainjs/xchain-client'
import {
Asset,
AssetBNB,
BaseAmount,
Chain,
assetAmount,
assetFromString,
assetToBase,
assetToString,
baseAmount,
baseToAsset,
} from '@xchainjs/xchain-util'
import axios from 'axios'
import {
Account,
Balance as BinanceBalance,
Fees as BinanceFees,
TransactionResult,
TransferFee,
TxPage as BinanceTxPage,
} from './types/binance'
import { getPrefix, isAccount, isTransferFee, parseTx } from './util'
type PrivKey = string
export type Coin = {
asset: Asset
amount: BaseAmount
}
export type MultiTransfer = {
to: Address
coins: Coin[]
}
export type MultiSendParams = {
walletIndex?: number
transactions: MultiTransfer[]
memo?: string
}
/**
* Interface for custom Binance client
*/
export interface BinanceClient {
purgeClient(): void
getBncClient(): BncClient
getAccount(address?: Address, index?: number): Promise<Account>
getMultiSendFees(): Promise<Fees>
getSingleAndMultiFees(): Promise<{ single: Fees; multi: Fees }>
multiSend(params: MultiSendParams): Promise<TxHash>
}
/**
* Custom Binance client
*/
class Client extends BaseXChainClient implements BinanceClient, XChainClient {
private bncClient: BncClient
/**
* Constructor
*
* Client has to be initialised with network type and phrase.
* It will throw an error if an invalid phrase has been passed.
*
* @param {XChainClientParams} params
*
* @throws {"Invalid phrase"} Thrown if the given phase is invalid.
*/
constructor(params: XChainClientParams) {
super(Chain.Binance, params)
this.bncClient = new BncClient(this.getClientUrl())
this.bncClient.chooseNetwork(this.getNetwork())
}
/**
* Get the BncClient interface.
*
* @returns {BncClient} The BncClient from `@binance-chain/javascript-sdk`.
*/
getBncClient(): BncClient {
return this.bncClient
}
/**
* Set/update the current network.
*
* @param {Network} network
* @returns {void}
*
* @throws {"Network must be provided"}
* Thrown if network has not been set before.
*/
setNetwork(network: Network): void {
super.setNetwork(network)
this.bncClient = new BncClient(this.getClientUrl())
this.bncClient.chooseNetwork(network)
}
/**
* Get the client url.
*
* @returns {string} The client url for binance chain based on the network.
*/
private getClientUrl(): string {
switch (this.network) {
case Network.Mainnet:
return 'https://dex.binance.org'
case Network.Testnet:
return 'https://testnet-dex.binance.org'
}
}
/**
* Get the explorer url.
*
* @returns {string} The explorer url based on the network.
*/
getExplorerUrl(): string {
switch (this.network) {
case Network.Mainnet:
return 'https://explorer.binance.org'
case Network.Testnet:
return 'https://testnet-explorer.binance.org'
}
}
/**
* Get the explorer url for the given address.
*
* @param {Address} address
* @returns {string} The explorer url for the given address based on the network.
*/
getExplorerAddressUrl(address: Address): string {
return `${this.getExplorerUrl()}/address/${address}`
}
/**
* Get the explorer url for the given transaction id.
*
* @param {string} txID
* @returns {string} The explorer url for the given transaction id based on the network.
*/
getExplorerTxUrl(txID: string): string {
return `${this.getExplorerUrl()}/tx/${txID}`
}
/**
* @private
* Get private key.
*
* @param {number} index account index for the derivation path
* @returns {PrivKey} The privkey generated from the given phrase
*
* @throws {"Phrase not set"}
* Throws an error if phrase has not been set before
* */
private getPrivateKey(index: number): PrivKey {
if (!this.phrase) throw new Error('Phrase not set')
return crypto.getPrivateKeyFromMnemonic(this.phrase, true, index)
}
/**
* Get the current address.
*
* @param {number} index (optional) Account index for the derivation path
* @returns {Address} The current address.
*
* @throws {Error} Thrown if phrase has not been set before. A phrase is needed to create a wallet and to derive an address from it.
*/
getAddress(index = 0): string {
return crypto.getAddressFromPrivateKey(this.getPrivateKey(index), getPrefix(this.network))
}
/**
* Validate the given address.
*
* @param {Address} address
* @returns {boolean} `true` or `false`
*/
validateAddress(address: Address): boolean {
return this.bncClient.checkAddress(address, getPrefix(this.network))
}
/**
* Get account data of wallets or by given address.
*
* @param {Address} address (optional) By default, it will return account data of current wallet.
* @param {number} index (optional) Account index for the derivation path
*
* @returns {Account} account details of given address.
*/
async getAccount(address?: Address, index = 0): Promise<Account> {
const accountAddress = address || this.getAddress(index)
const response = await this.bncClient.getAccount(accountAddress)
if (!response || !response.result || !isAccount(response.result))
return Promise.reject(Error(`Could not get account data for address ${accountAddress}`))
return response.result
}
/**
* Get the balance of a given address.
*
* @param {Address} address By default, it will return the balance of the current wallet. (optional)
* @param {Asset} asset If not set, it will return all assets available. (optional)
* @returns {Balance[]} The balance of the address.
*/
async getBalance(address: Address, assets?: Asset[]): Promise<Balance[]> {
const balances: BinanceBalance[] = await this.bncClient.getBalance(address)
return balances
.map((balance) => {
return {
asset: assetFromString(`${Chain.Binance}.${balance.symbol}`) || AssetBNB,
amount: assetToBase(assetAmount(balance.free, 8)),
}
})
.filter(
(balance) => !assets || assets.filter((asset) => assetToString(balance.asset) === assetToString(asset)).length,
)
}
/**
* @private
* Search transactions with parameters.
*
* @returns {Params} The parameters to be used for transaction search.
* */
private async searchTransactions(params?: { [x: string]: string | undefined }): Promise<TxsPage> {
const clientUrl = `${this.getClientUrl()}/api/v1/transactions`
const url = new URL(clientUrl)
const endTime = Date.now()
const diffTime = 90 * 24 * 60 * 60 * 1000
url.searchParams.set('endTime', endTime.toString())
url.searchParams.set('startTime', (endTime - diffTime).toString())
for (const key in params) {
const value = params[key]
if (value) {
url.searchParams.set(key, value)
if (key === 'startTime' && !params['endTime']) {
url.searchParams.set('endTime', (parseInt(value) + diffTime).toString())
}
if (key === 'endTime' && !params['startTime']) {
url.searchParams.set('startTime', (parseInt(value) - diffTime).toString())
}
}
}
const txHistory = (await axios.get<BinanceTxPage>(url.toString())).data
return {
total: txHistory.total,
txs: txHistory.tx.map(parseTx).filter(Boolean) as Tx[],
}
}
/**
* Get transaction history of a given address with pagination options.
* By default it will return the transaction history of the current wallet.
*
* @param {TxHistoryParams} params The options to get transaction history. (optional)
* @returns {TxsPage} The transaction history.
*/
async getTransactions(params?: TxHistoryParams): Promise<TxsPage> {
return await this.searchTransactions({
address: params && params.address,
limit: params && params.limit?.toString(),
offset: params && params.offset?.toString(),
startTime: params && params.startTime && params.startTime.getTime().toString(),
txAsset: params && params.asset,
})
}
/**
* Get the transaction details of a given transaction id.
*
* @param {string} txId The transaction id.
* @returns {Tx} The transaction details of the given transaction id.
*/
async getTransactionData(txId: string): Promise<Tx> {
const txResult: TransactionResult = (await axios.get(`${this.getClientUrl()}/api/v1/tx/${txId}?format=json`)).data
const blockHeight = txResult.height
let address = ''
const msgs = txResult.tx.value.msg
if (msgs.length) {
const msg = msgs[0].value as SignedSend
if (msg.inputs && msg.inputs.length) {
address = msg.inputs[0].address
} else if (msg.outputs && msg.outputs.length) {
address = msg.outputs[0].address
}
}
const txHistory = await this.searchTransactions({ address, blockHeight })
const [transaction] = txHistory.txs.filter((tx) => tx.hash === txId)
if (!transaction) {
throw new Error('transaction not found')
}
return transaction
}
/**
* Broadcast multi-send transaction.
*
* @param {MultiSendParams} params The multi-send transfer options.
* @returns {TxHash} The transaction hash.
*/
async multiSend({ walletIndex = 0, transactions, memo = '' }: MultiSendParams): Promise<TxHash> {
const derivedAddress = this.getAddress(walletIndex)
await this.bncClient.initChain()
await this.bncClient.setPrivateKey(this.getPrivateKey(walletIndex))
const transferResult = await this.bncClient.multiSend(
derivedAddress,
transactions.map((transaction) => {
return {
to: transaction.to,
coins: transaction.coins.map((coin) => {
return {
denom: coin.asset.symbol,
amount: baseToAsset(coin.amount).amount().toString(),
}
}),
}
}),
memo,
)
return transferResult.result.map((txResult: { hash?: TxHash }) => txResult?.hash ?? '')[0]
}
/**
* Transfer balances.
*
* @param {TxParams} params The transfer options.
* @returns {TxHash} The transaction hash.
*/
async transfer({ walletIndex, asset, amount, recipient, memo }: TxParams): Promise<TxHash> {
await this.bncClient.initChain()
await this.bncClient.setPrivateKey(this.getPrivateKey(walletIndex || 0))
const transferResult = await this.bncClient.transfer(
this.getAddress(walletIndex),
recipient,
baseToAsset(amount).amount().toString(),
asset ? asset.symbol : AssetBNB.symbol,
memo,
)
return transferResult.result.map((txResult: { hash?: TxHash }) => txResult?.hash ?? '')[0]
}
/**
* Get the current transfer fee.
*
* @returns {TransferFee} The current transfer fee.
*/
private async getTransferFee(): Promise<TransferFee> {
const feesArray = (await axios.get<BinanceFees>(`${this.getClientUrl()}/api/v1/fees`)).data
const [transferFee] = feesArray.filter(isTransferFee)
if (!transferFee) throw new Error('failed to get transfer fees')
return transferFee
}
/**
* Get the current fee.
*
* @returns {Fees} The current fee.
*/
async getFees(): Promise<Fees> {
let singleTxFee: BaseAmount | undefined = undefined
try {
singleTxFee = baseAmount(await this.getFeeRateFromThorchain())
} catch (error) {
console.log(error)
console.warn(`Error pulling rates from thorchain, will try alternate`)
}
if (!singleTxFee) {
const transferFee = await this.getTransferFee()
singleTxFee = baseAmount(transferFee.fixed_fee_params.fee)
}
return singleFee(FeeType.FlatFee, singleTxFee)
}
/**
* Get the current fee for multi-send transaction.
*
* @returns {Fees} The current fee for multi-send transaction.
*/
async getMultiSendFees(): Promise<Fees> {
const transferFee = await this.getTransferFee()
const multiTxFee = baseAmount(transferFee.multi_transfer_fee)
return {
type: 'base' as FeeType,
average: multiTxFee,
fast: multiTxFee,
fastest: multiTxFee,
} as Fees
}
/**
* Get the current fee for both single and multi-send transaction.
*
* @returns {SingleAndMultiFees} The current fee for both single and multi-send transaction.
*/
async getSingleAndMultiFees(): Promise<{ single: Fees; multi: Fees }> {
const transferFee = await this.getTransferFee()
const singleTxFee = baseAmount(transferFee.fixed_fee_params.fee)
const multiTxFee = baseAmount(transferFee.multi_transfer_fee)
return {
single: {
type: 'base' as FeeType,
fast: singleTxFee,
fastest: singleTxFee,
average: singleTxFee,
} as Fees,
multi: {
type: 'base' as FeeType,
average: multiTxFee,
fast: multiTxFee,
fastest: multiTxFee,
} as Fees,
}
}
}
export { Client } | the_stack |
import {Router} from 'express';
import * as solc from 'solc';
import {AbiCoder} from 'web3-eth-abi';
const abiCoder = new AbiCoder();
import * as Web3 from 'web3';
import BigNumber from "bignumber.js";
import {ModelInfo} from './definitions';
import {parseModel} from './models.parsers';
import {repoSchema} from '../repo/procModelData';
import {registrySchema} from '../repo/procModelData';
import {policySchema} from '../repo/procModelData';
import {roleTaskSchema} from '../repo/procModelData';
import {generatePolicy} from './dynamic_binding/validation_code_gen/BindingPolicyGenerator';
import {generateRoleTaskContract} from './dynamic_binding/validation_code_gen/ProcessRoleGenerator';
import {SubProcessInfo, IFlowInfo, IDataInfo, ElementIFlow, ParamInfo} from './interpreter/ParsingInfo';
import {parseBpmnModel} from './interpreter/BPMNParser';
// import * as mongoose from 'mongoose';
// let app = require('express')();
// let http = require('http').Server(app);
// let io = require('socket.io')(http);
// let ObjectId = mongoose.Types.ObjectId;
/* http.listen(8090, () => {
// console.log('started on port 8090');
}); */
import fs = require('fs');
////// ANTLR Runtime Requirements //////////////////////////
////////////////////////////////////////////////////////////
const models: Router = Router();
let web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
// var web3 = new Web3(new Web3.providers.HttpProvider("http://193.40.11.64:80"));
const WebSocket = require('ws');
let mws;
const wss = new WebSocket.Server({port: 8090});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
// console.log('received: %s', message);
});
ws.on('error', () => {});
mws = ws;
});
let executionAccount = 0
web3.eth.filter("latest", function (error, result) {
if (!error) {
try {
let info = web3.eth.getBlock(result);
if (info.transactions.length > 0) {
// // console.log('----------------------------------------------------------------------------------------------');
// // console.log('NEW BLOCK MINED');
let toNotify = [];
info.transactions.forEach(transactionHash => {
// // console.log("TRANSACTION ", transRec);
//// console.log(web3.eth.estimateGas({from: web3.eth.accounts[0], to: transactionHash, amount: web3.toWei(1, "ether")}))
let transRec = web3.eth.getTransactionReceipt(transactionHash);
let tranInfo = { 'hash': transactionHash,
'blockNumber': transRec.blockNumber,
'gas': transRec.gasUsed,
'cumulGas': transRec.cumulativeGasUsed }
// if(toPrint.length > 0 && toPrint === transactionHash) {
// // console.log('Gas :' + tI + " " + transRec.gasUsed);
// toPrint = '';
// tI = 0;
// }
if(pendingTrans.has(tranInfo.hash)) {
toNotify.push(tranInfo);
/* if(transRec.logs && transRec.logs.length > 0) {
console.log(transRec.logs)
console.log('-----------------------------------------------------------------')
} */
}
/* if(!bindingOpTransactions.has(tranInfo.hash)) {
transRec.logs.forEach(logElem => {
if (workListInstances.has(logElem.address) && toNotify.indexOf(logElem.address) < 0) {
//// console.log("LOG ELEMENT ", logElem);
// console.log('WorkList', workListInstances);
toNotify.push(workListInstances.get(logElem.address));
}
})
} */
//// console.log('----------------------------------------------------------------------------------------------');
});
if (toNotify.length > 0) {
//// console.log("Message sent through socket running on port 8090");
toNotify.forEach(add => {
// console.log(add.hash)
if (mws)
mws.send(JSON.stringify(add), function ack(error) {
});
});
//io.emit('message', { type: 'new-message', text: "Updates in Server" });
} else {
//// console.log("Nothing to notify");
}
}
} catch(ex) { }
}
});
/////////////////////////////////////////////////////////
/// CATERPILLAR INTERPRETER OPERATIONS ///
/////////////////////////////////////////////////////////
let contractsInfo: any;
let processInfo: SubProcessInfo;
let deployedContracts: Map<string, any> = new Map();
let pendingTrans: Map<string, string> = new Map();
models.post('/interpreter', (req, res) => {
instantiateContract('BPMNInterpreter:BPMNInterpreter')
.then((result) => {
deployedContracts.set('interpreter', result.contract);
res.status(200).send({'contract': result.contract.address, 'gas': result.gas});
})
.catch(error => {
res.status(400).send(error);
})
});
models.post('/interpreter/models', (req, res) => {
console.log('Parsig BPMN Model and Generating IData Smart Contracts ...');
parseBpmnModel(req.body.bpmn)
.then((procInfo: SubProcessInfo) => {
console.log('IFlow information collected ...')
compileContracts(procInfo)
.then((result) => {
console.log(result);
// Deploying Interpreter
instantiateContract('BPMNInterpreter:BPMNInterpreter')
.then(interpreter => {
deployedContracts.set('interpreter', interpreter.contract);
// Deploying IFlow Node
instantiateContract('IFlow:IFlowImpl')
.then(iFlow => {
deployedContracts.set('iFlow', iFlow.contract);
// Deploying Factory
instantiateContract(procInfo.procId+ 'Factory:'+ procInfo.procId + 'Factory')
.then(iFactory => {
deployedContracts.set('iFactory', iFactory.contract);
addFactory()
.then(factoryRes => {
console.log('FactoryTrans: ' + factoryRes);
addInterpreter()
.then(interpreterRes => {
// printIFlow();
res.status(200).send(
{
iFlow: {address: iFlow.contract.address, gas: iFlow.gas},
interpreter: {address: interpreter.contract.address, gas: interpreter.gas},
iFactory: {address: iFactory.contract.address, gas: iFactory.gas},
toRegister: elementsToRegister(),
elementNames: elementNames()
}
);
})
.catch((error) => {
res.status(400).send(error);
})
})
.catch((error) => {
res.status(400).send(error);
})
})
.catch((error) => {
res.status(400).send(error);
})
})
.catch((error) => {
res.status(400).send(error);
})
})
.catch((error) => {
res.status(400).send(error);
})
})
.catch((error) => {
res.status(400).send(error);
})
})
.catch(error => {
res.status(400).send(error);
});
});
models.get('/interpreter/models', (req, res) => {
// Retrieves the {hashes, names} of the models registered in Process Repository
});
models.get('/interpreter/models/:mHash', (req, res) => {
// Retrieves all the metadata of a given model (hash)
});
models.post('/i-flow', (req, res) => {
instantiateContract('IFlow:IFlowImpl')
.then((result) => {
deployedContracts.set('i-flow', result.contract);
res.status(200).send({'contract': result.contract.address, 'gas': result.gas});
})
.catch(error => {
res.status(400).send(error);
})
});
models.get('/i-flow/:cfAddress', (req, res) => {
// Updating sub-processes into an iflow node
});
models.patch('/i-flow/element/:cfAddress', (req, res) => {
// Updating elements into an iflow node
});
models.patch('/i-flow/child/:cfAddress', (req, res) => {
// Updating sub-processes into an iflow node
});
models.patch('/i-flow/factory/:cfAddress', (req, res) => {
// Updating sub-processes into an iflow node
});
// Creation of a new Process Case
models.post('/i-flow/p-cases/:cfAddress', (req, res) => {
let cfAddress = abiCoder.encodeParameter('address', req.params.cfAddress);
let interpreter = deployedContracts.get('interpreter');
interpreter.createInstance(cfAddress, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error, result) => {
if (result) {
pendingTrans.set(result.toString(), 'pCase: ' + cfAddress);
console.log(result.toString());
let myEvent = interpreter.NewCaseCreated({
fromBlock: 0,
toBlock: 'latest'
});
myEvent.watch((errEvt, resEvt) => {
if (!errEvt) {
if (resEvt && resEvt.transactionHash === result && resEvt.event === 'NewCaseCreated') {
myEvent.stopWatching();
let pCase = resEvt.args.pCase.toString();
console.log('pCase: ', pCase);
console.log('Gas: ', web3.eth.getTransactionReceipt(resEvt.transactionHash).gasUsed);
console.log('....................................................................');
res.status(200).send({pCase: pCase, gas: web3.eth.getTransactionReceipt(resEvt.transactionHash).gasUsed });
}
} else {
console.log('ERROR ', errEvt);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send(errEvt);
}
});
}
else {
// console.log(error)
res.status(400).send(error);
}
})
});
models.get('/i-flow/p-cases/:cfAddress', (req, res) => {
// Retrieves the process cases created for a given iFlow node
});
// Retrives the state of a process case (started activities)
models.get('/i-data/:pcAddress', (req, res) => {
res.status(200).send({enabled: getProcessState(req.params.pcAddress)});
});
// Checks-out a task in a given process case
models.get('/i-data/:pcAddress/i-flow/:eIndex', (req, res) => {
//
});
// Checks-in a task in a given process case
models.patch('/i-data/:pcAddress/i-flow/:eIndex', (req, res) => {
let pCase = req.params.pcAddress;
let cName = processInfo.procId + 'Data:' + processInfo.procId + 'Data';
let contract = web3.eth.contract(JSON.parse(contractsInfo[cName].interface)).at(pCase);
let reqId = req.params.eIndex;
let inputParams = req.body.inputParameters;
let realParameters = [];
realParameters = inputParams.length > 0 ? [reqId].concat(inputParams) : [reqId];
contract['checkIn'][joinTypes(+reqId)].apply(this, realParameters.concat({
from:web3.eth.accounts[0],
gas: 4700000
}, (error, result) => {
if (error) {
console.log('ERROR: ' + error);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send('Error');
} else {
pendingTrans.set(result.toString(), 'checkIn: ' + reqId);
//console.log(`TRANSACTION: ${result}, PENDING !!!`);
//console.log('----------------------------------------------------------------------------------------------');
res.status(200).send({transactionHash: result});
}
}));
});
let printIFlow = () => {
processInfo.iflow.nodeIndexMap.forEach((eInd, eId) => {
console.log('eInd: ', eInd);
console.log('eName: ', processInfo.iflow.elementInfo.get(eInd).eName);
console.log('typeInfo: ', processInfo.iflow.elementInfo.get(eInd).typeInfo);
console.log('preC: ', processInfo.iflow.elementInfo.get(eInd).preC);
console.log('postC: ', processInfo.iflow.elementInfo.get(eInd).postC);
console.log('next: ', processInfo.iflow.elementInfo.get(eInd).next);
console.log('----------------------------------------------')
});
}
// Registers an element into IFlow node
models.post('/i-flow/element/:eInd', (req, res) => {
// FOR EXPERIMENTS ONLY
// Extend method to receive the input parameters as JSON in the body.
// Actual uri: /i-flow/element/:cfAddress
let eInd: number = +req.params.eInd
let eInfo: ElementIFlow = processInfo.iflow.elementInfo.get(eInd);
let preC = abiCoder.encodeParameter('uint256', eInfo.preC);
let postC= abiCoder.encodeParameter('uint256', eInfo.postC);
let typeInfo = abiCoder.encodeParameter('uint256', eInfo.typeInfo);
registerElement(eInd, preC, postC, typeInfo, 'elem', eInfo.next)
.then((result) => {
pendingTrans.set(result.toString(), 'Register: ' + eInd);
res.status(200).send({ transactionHash: result });
})
.catch((error) => {
res.status(400).send(error);
})
})
let getProcessState = (pCase: string) => {
let cName = processInfo.procId + 'Data:' + processInfo.procId + 'Data';
let iData = web3.eth.contract(JSON.parse(contractsInfo[cName].interface)).at(pCase);
let iFlow = deployedContracts.get('iFlow');
let startedActivities = iData.getStartedActivities.call().toString(2).split('').reverse();
let tokensonEdges = iData.getMarking.call().toString(2).split('').reverse();
let eCandidates = processInfo.iflow.nodeIndexMap.size;
let enabledTasks = new Array();
for (let eInd = 1; eInd <= eCandidates; eInd++) {
let preC = iFlow.getPreCond.call(eInd).toString(2).split('').reverse();
let postC = iFlow.getPostCond.call(eInd).toString(2).split('').reverse();
let typeInfo = iFlow.getTypeInfo.call(eInd).toString(2).split('').reverse();
if(typeInfo[0] === '1' && typeInfo[3] === '1' && (typeInfo[11] === '1' || typeInfo[14] === '1')) {
for(let i = 0; i < preC.length; i++) {
if(preC[i] === '1' && i < tokensonEdges.length && tokensonEdges[i] === '1') {
enabledTasks.push(eInd);
break;
}
}
}
}
return enabledTasks;
}
let joinTypes = (eInd: number) => {
let params: Array<ParamInfo> = processInfo.iData.inParams.get(eInd);
let res: string = 'uint256';
params.forEach(param => {
res += param.type === 'uint' ? ',uint256' : `,${param.type}`;
});
return res;
}
let registerElement = (eInd, preC, postC, typeInfo, eId, nextElem) => {
return new Promise<any>((resolve, reject) => {
let iFlow = deployedContracts.get('iFlow');
iFlow.setElement(eInd, preC, postC, typeInfo, eId, nextElem, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error, result) => {
if (result) {
resolve(result)
}
else {
reject(error);
}
})
});
}
let elementsToRegister = () => {
let res = [];
processInfo.iflow.nodeIndexMap.forEach((eInd, eId) => {
res[eInd] = eId;
});
return res;
}
let elementNames = () => {
let res = [];
processInfo.iflow.nodeIndexMap.forEach((eInd, eId) => {
res[eInd] = processInfo.iflow.elementInfo.get(eInd).eName;
});
return res;
}
let addFactory = () => {
return new Promise((resolve, reject) => {
let iFlow = deployedContracts.get('iFlow');
let iFactoryAddr = deployedContracts.get('iFactory').address;
iFlow.setFactoryInst(iFactoryAddr, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error, result) => {
if (result) {
resolve(result)
}
else {
console.log('ERROR ', error);
reject(error);
}
})
})
}
let addInterpreter = () => {
return new Promise((resolve, reject) => {
let iFlow = deployedContracts.get('iFlow');
let interpreterAddr = deployedContracts.get('interpreter').address;
iFlow.setInterpreterInst(interpreterAddr, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error, result) => {
if (result) {
resolve(result)
}
else {
console.log('ERROR ', error);
reject(error);
}
})
})
}
let compileContracts = (procInfo: SubProcessInfo) => {
return new Promise((resolve, reject) => {
let input = {
'IFlow': fs.readFileSync('./src/models/interpreter/smart_contracts/IFlow.sol', 'utf8'),
'IData': fs.readFileSync('./src/models/interpreter/smart_contracts/IData.sol', 'utf8'),
'IFactory': fs.readFileSync('./src/models/interpreter/smart_contracts/IFactory.sol', 'utf8'),
'BPMNInterpreter': fs.readFileSync('./src/models/interpreter/smart_contracts/BPMNInterpreter.sol', 'utf8'),
// 'BindingAccessControl' : fs.readFileSync('./src/models/dynamic_binding/runtime_solidity/BindingAccessControl.sol', 'utf8')
};
let queue: Array<SubProcessInfo> = new Array();
queue.push(procInfo);
while(queue.length > 0) {
let topProc: SubProcessInfo = queue.pop();
console.log(topProc.iData.iDataSolidity)
console.log('---------------------------------')
input[topProc.procId + 'Data'] = topProc.iData.iDataSolidity;
input[topProc.procId + 'Factory'] = topProc.iData.factorySolidity;
for(let i = 0; i < topProc.children.length; i++)
queue.push(topProc.children[i]);
}
console.log('Compiling IData Contracts ...');
let output = solc.compile({sources: input}, 1);
if (Object.keys(output.contracts).length === 0) {
console.log('Compilation Errors In IData Ssmart Contracts');
console.log(output.errors);
console.log('----------------------------------------------------------------------------------------------');
reject('Compilation Errors In IData Ssmart Contracts');
} else {
contractsInfo = output.contracts;
processInfo = procInfo;
resolve('IData Contracts Generated And Compiled Successfully. ');
}
})
}
let instantiateContract = (key: string) => {
return new Promise<any>((resolve, reject) => {
let contract = web3.eth.contract(JSON.parse(contractsInfo[key].interface));
let bytecode = contractsInfo[key].bytecode;
let gasEstimate = web3.eth.estimateGas({data: bytecode});
contract.new(
{from: web3.eth.accounts[0], data: "0x" + bytecode, gas: gasEstimate + 50000},
(errF, contractF) => {
if (errF) {
console.log(`${key} instance creation failed`);
console.log('ERROR ', errF);
reject(errF);
} else if (contractF.address) {
let gasUsed = web3.eth.getTransactionReceipt(contractF.transactionHash).gasUsed;
console.log(`${key} CONTRACT DEPLOYED and RUNNING at ` + contractF.address.toString());
console.log('GAS USED: ', gasUsed);
console.log('............................................')
resolve({'contract': contractF, 'gas': gasUsed});
}
});
});
}
let workListInstances: Map<string, string> = new Map();
let bindingOpTransactions: Map<string, number> = new Map();
let processRegistryContract: any = undefined;
// Querying for every contract all the created instances
models.get('/processes', (req, res) => {
console.log('QUERYING ALL ACTIVE CONTRACTS');
let actives = [];
if(processRegistryContract) {
let registeredInstances = processRegistryContract.allInstances.call();
registeredInstances.forEach(instance => {
let repoID = web3.toAscii(processRegistryContract.bundleFor.call(instance)).toString().substr(0, 24);
repoSchema.find({_id: repoID},
(err, repoData) => {
if (err) {
res.status(404).send([]);
return;
} else {
if(repoData.length > 0) {
console.log({id: repoID, name: repoData[0].rootProcessName, address: instance});
actives.push({id: repoID, name: repoData[0].rootProcessName, address: instance});
if (actives.length === registeredInstances.length) {
res.status(200).send(actives);
return;
}
}
}
})
})
} else {
res.status(404).send([]);
}
});
// Querying all registered (root) process in the repository
models.get('/models', (req, res) => {
console.log('QUERYING REGISTERED MODELS');
let actives = [];
if(processRegistryContract) {
repoSchema.find({'bpmnModel': {$ne: 'empty'}},
(err, repoData) => {
if (err)
res.send([]);
else {
repoData.forEach(data => {
if(web3.toAscii(processRegistryContract.childrenFor(data._id.toString(), 0)).toString().substr(0, 24) === data._id.toString()) {
console.log({id: data._id, name: data.rootProcessName});
actives.push({
id: data._id,
name: data.rootProcessName,
bpmn: data.bpmnModel,
solidity: data.solidityCode
})
}
});
console.log('----------------------------------------------------------------------------------------------');
res.send(actives);
}
});
} else {
res.send([]);
console.log('----------------------------------------------------------------------------------------------');
}
});
//////////////////////////////////////////////////////////////////////
/// CONFIGURATION (ProcessRegistry) REGISTRATION operations ///
//////////////////////////////////////////////////////////////////////
models.post('/registry', (req, res) => {
console.log('DEPLOYING PROCESS RUNTIME REGISTRY ...');
try {
let input = {
'AbstractFactory': fs.readFileSync('./src/models/abstract/AbstractFactory.sol', 'utf8'),
'ProcessRegistry': fs.readFileSync('./src/models/abstract/ProcessRegistry.sol', 'utf8')
};
console.log('=============================================');
console.log("SOLIDITY CODE");
console.log('=============================================');
console.log(input['ProcessRegistry']);
console.log('....................................................................');
let output = solc.compile({sources: input}, 1);
if (Object.keys(output.contracts).length === 0) {
res.status(400).send('COMPILATION ERROR IN RUNTIME REGISTRY SMART CONTRACTS');
console.log('COMPILATION ERROR IN SMART CONTRACTS');
console.log(output.errors);
console.log('----------------------------------------------------------------------------------------------');
return;
}
console.log('PROCESS RUNTIME REGISTRY COMPILED SUCCESSFULLY');
console.log('CREATING RUNTIME REGISTRY INSTANCE ... ');
let ProcContract = web3.eth.contract(JSON.parse(output.contracts['ProcessRegistry:ProcessRegistry'].interface));
ProcContract.new(
{
from: web3.eth.accounts[executionAccount],
data: "0x" + output.contracts['ProcessRegistry:ProcessRegistry'].bytecode,
gas: 4700000
},
(err, contract) => {
if (err) {
console.log(`ERROR: ProcessRegistry instance creation failed`);
console.log('RESULT ', err);
res.status(403).send(err);
} else if (contract.address) {
registrySchema.create(
{
address: contract.address,
solidityCode: input['ProcessRegistry'],
abi: output.contracts['ProcessRegistry:ProcessRegistry'].interface,
bytecode: output.contracts['ProcessRegistry:ProcessRegistry'].bytecode,
},
(err, repoData) => {
if (err) {
console.log('Error ', err);
console.log('----------------------------------------------------------------------------------------------');
// registerModels(currentIndex, sortedElements, createdElementMap, modelInfo, contracts, res);
}
else {
processRegistryContract = contract;
let registryGas = web3.eth.getTransactionReceipt(contract.transactionHash).gasUsed;
let idAsString = repoData._id.toString();
console.log("Process Registry DEPLOYED and RUNNING at " + processRegistryContract.address.toString());
console.log('GAS USED: ', registryGas);
console.log('REPO ID: ', idAsString);
res.status(200).send({ 'address': processRegistryContract.address.toString(), gas: registryGas, repoId: idAsString});
console.log('----------------------------------------------------------------------------------------------');
}
})
}
});
} catch (e) {
console.log("Error: ", e);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send(e);
}
});
models.post('/registry/load', (req, res) => {
console.log('LOADING PROCESS RUNTIME REGISTRY ...');
if(web3.isAddress(req.body.from)) {
registrySchema.find({address: req.body.from},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
processRegistryContract = web3.eth.contract(JSON.parse(repoData[0].abi)).at(req.body.from);
console.log('Registry Loaded Successfully');
res.status(200).send('Registry Loaded Successfully');
console.log('----------------------------------------------------------------------------------------------');
} else {
console.log("Error: Registry NOT Found");
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send('Registry NOT Found');
return;
}
})
} else {
registrySchema.find({_id: req.body.from},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
processRegistryContract = web3.eth.contract(JSON.parse(repoData[0].abi)).at(repoData[0].address);
console.log('Registry Loaded Successfully');
res.status(200).send('Registry Loaded Successfully');
console.log('----------------------------------------------------------------------------------------------');
} else {
console.log("Error: Registry NOT Found");
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send('Registry NOT Found');
return;
}
})
}
});
//////////////////////////////////////////////////////////////////////
/// ROLE DYNAMIC BINDING operations ///
//////////////////////////////////////////////////////////////////////
models.post('/resources/policy', (req, res) => {
console.log('GENERATING AND DEPLOYING BINDING POLICY CONTRACTS ...');
if (processRegistryContract === undefined) {
console.log('ERROR: No Runtime Registry Available');
console.log('----------------------------------------------------------------------------------------------');
res.status(404).send('Error: Runtime Registry Not Found');
} else {
console.log('GENERATING SMART CONTRACTS FROM BINDING POLICY ...');
let resourceModel = req.body.model;
let parsingResult = generatePolicy(resourceModel, 'BindingPolicy');
parsingResult
.then((policy) => {
let input = {
'BindingAccessControl': fs.readFileSync('./src/models/dynamic_binding/runtime_solidity/BindingAccessControl.sol', 'utf8')
};
input['BindingPolicy'] = policy.solidity;
console.log('=============================================');
console.log("SOLIDITY CODE");
console.log('=============================================');
Object.keys(input).forEach(key => {
console.log(input[key]);
});
console.log('....................................................................');
let output = solc.compile({sources: input}, 1);
if (Object.keys(output.contracts).length === 0) {
res.status(400).send('COMPILATION ERROR IN POLICY CONTRACTS');
console.log('COMPILATION ERROR IN POLICY CONTRACTS');
console.log(output.errors);
console.log('----------------------------------------------------------------------------------------------');
return;
}
console.log('POLICY CONTRACTS GENERATED AND COMPILED SUCCESSFULLY');
let ProcContract = web3.eth.contract(JSON.parse(output.contracts['BindingPolicy:BindingPolicy_Contract'].interface));
ProcContract.new(
{
from: web3.eth.accounts[executionAccount],
data: "0x" + output.contracts['BindingPolicy:BindingPolicy_Contract'].bytecode,
gas: 4700000
},
(err, contract) => {
if (err) {
console.log(`ERROR: PolicyContract instance creation failed`);
console.log('RESULT ', err);
res.status(403).send(err);
} else if (contract.address) {
let indexToRole = [];
for (let [role, index] of policy.roleIndexMap) {
indexToRole[index] = role;
}
policySchema.create(
{
address: contract.address,
model: req.body.model,
solidityCode: input['BindingPolicy'],
abi: output.contracts['BindingPolicy:BindingPolicy_Contract'].interface,
bytecode: output.contracts['BindingPolicy:BindingPolicy_Contract'].bytecode,
indexToRole: indexToRole,
accessControlAbi: output.contracts['BindingAccessControl:BindingAccessControl'].interface,
accessControlBytecode: output.contracts['BindingAccessControl:BindingAccessControl'].bytecode,
},
(err, repoData) => {
if (err) {
console.log('Error ', err);
console.log('----------------------------------------------------------------------------------------------');
// registerModels(currentIndex, sortedElements, createdElementMap, modelInfo, contracts, res);
}
else {
let idAsString = repoData._id.toString();
let policyGas = web3.eth.getTransactionReceipt(contract.transactionHash).gasUsed;
console.log("Policy CREATED and RUNNING at " + contract.address.toString());
console.log('GAS USED: ', policyGas);
console.log('Policy Id: ', idAsString);
console.log('Role\'s indexes: ', policy.roleIndexMap);
console.log(".............................................");
res.status(200).send({address: contract.address.toString(), gas: policyGas, repoId: idAsString });
console.log('----------------------------------------------------------------------------------------------');
}
})
}
});
})
.catch((err) => {
res.status(200).send({ 'Error': 'Error Parsing' });
console.log('----------------------------------------------------------------------------------------------');
})
}
});
models.post('/resources/task-role', (req, res) => {
if(processRegistryContract === undefined) {
console.log('ERROR: Runtime Registry NOT FOUND.');
res.status(404).send({ 'Error': 'Runtime Registry NOT FOUND. Please, Create/Load a Registry.' });
console.log('----------------------------------------------------------------------------------------------');
} else {
if(web3.isAddress(req.body.policyId)) {
policySchema.find({address: req.body.policyId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let processData: Map<string, Array<any>> = new Map();
searchRepository(0, [req.body.rootProc], processData, res, req.body.policyId, findRoleMap(repoData[0].indexToRole));
} else {
console.log("Error: Binding Policy NOT Found");
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send('Binding Policy NOT Found');
return;
}
})
} else {
policySchema.find({_id: req.body.policyId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let processData: Map<string, Array<any>> = new Map();
searchRepository(0, [req.body.rootProc], processData, res, req.body.policyId, findRoleMap(repoData[0].indexToRole));
} else {
console.log("Error: Binding Policy NOT Found");
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send('Binding Policy NOT Found');
return;
}
})
}
}
});
models.get('/resources/:role/:procAddress', (req, res) => {
if (!web3.isAddress(req.params.procAddress)) {
res.status(200).send({'state' : 'INVALID INPUT PROCESS ADDRESS'});
} else if(processRegistryContract === undefined) {
res.status(200).send({'state' : 'UNDEFINED PROCESS REGISTRY'});
} else {
let _policyId = web3.toAscii(processRegistryContract.bindingPolicyFor.call(req.params.procAddress)).toString().substr(0, 24);
policySchema.find({_id: _policyId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let roleIndexMap = findRoleMap(repoData[0].indexToRole);
if(!roleIndexMap.has(req.params.role)) {
console.log('UNDEFINED INPUT ROLE');
res.status(200).send({'state' : 'UNDEFINED INPUT ROLE'});
} else {
let accessControlAddr = processRegistryContract.findRuntimePolicy.call(req.params.procAddress);
if(accessControlAddr.toString() === '0x0000000000000000000000000000000000000000') {
console.log('UNDEFINED ACESS CONTROL CONTRACT');
res.status(200).send({'state' : 'UNDEFINED ACESS CONTROL CONTRACT'});
} else {
let _runtimePolicyContract = web3.eth.contract(JSON.parse(repoData[0].accessControlAbi)).at(accessControlAddr);
let result = _runtimePolicyContract.roleState.call(roleIndexMap.get(req.params.role), req.params.procAddress);
if(result.c[0] === 0) {
console.log(`${req.params.role} is UNBOUND`)
res.status(200).send({'state' : 'UNBOUND'});
} else if(result.c[0] === 1) {
console.log(`${req.params.role} is RELEASING`)
res.status(200).send({'state' : 'RELEASING'});
} else if(result.c[0] === 2) {
console.log(`${req.params.role} is NOMINATED`)
res.status(200).send({'state' : 'NOMINATED'});
} else if(result.c[0] === 3) {
console.log(`${req.params.role} is BOUND`)
res.status(200).send({'state' : 'BOUND'});
} else {
console.log('UNDEFINED STATE');
res.status(200).send({'state' : 'UNDEFINED'});
}
}
}
} else {
console.log('UNDEFINED POLICY CONTRACT');
res.status(200).send({'state' : 'UNDEFINED POLICY CONTRACT'});
return;
}
});
}
console.log('----------------------------------------------------------------------------------------------');
});
let validateInput = (rNominator: string, rNominee: string, roleIndexMap, res: any) => {
if(!roleIndexMap.has(rNominee)) {
console.log(`Error Nominee Role [${rNominee}] NOT FOUND`);
res.status(404).send({ 'Error': `Nominee Role [${rNominee}] NOT FOUND` });
console.log('----------------------------------------------------------------------------------------------');
return false;
} else if(!roleIndexMap.has(rNominator)) {
console.log(`Error Nominee Role [${rNominee}] NOT FOUND`);
res.status(404).send({ 'Error': `Nominee Role [${rNominee}] NOT FOUND` });
console.log('----------------------------------------------------------------------------------------------');
return false;
}
return true;
}
let findRoleMap = (repoArr) => {
let roleInedexMap: Map<string, number> = new Map();
for (let i = 1; i < repoArr.length; i++)
if(repoArr[i])
roleInedexMap.set(repoArr[i], i);
return roleInedexMap;
}
let verifyAddress = (address: string, actor: string, res: any) => {
if (!web3.isAddress(address)) {
console.log('Error: ', `Invalid ${actor} Address [${address}]`);
res.status(400).send(`Invalid Nominator Address [${address}]`);
console.log('----------------------------------------------------------------------------------------------');
return false;
}
return true;
}
models.post('/resources/nominate', (req, res) => {
if(processRegistryContract === undefined) {
res.status(404).send({'state' : 'UNDEFINED PROCESS REGISTRY'});
} else {
let _policyId = web3.toAscii(processRegistryContract.bindingPolicyFor.call(req.body.pCase)).toString().substr(0, 24);
policySchema.find({_id: _policyId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let roleIndexMap = findRoleMap(repoData[0].indexToRole);
if(validateInput(req.body.rNominator, req.body.rNominee, roleIndexMap, res)) {
if (verifyAddress(req.body.nominator, 'Nominator', res) &&
verifyAddress(req.body.nominee, 'Nominee', res) &&
verifyAddress(req.body.pCase, 'Process Case', res)) {
let accessControlAddr = processRegistryContract.findRuntimePolicy.call(req.body.pCase);
if(accessControlAddr.toString() !== '0x0000000000000000000000000000000000000000') {
console.log(`${req.body.rNominator}[${req.body.nominator}] is nominating ${req.body.rNominee}[${req.body.nominee}]`);
console.log(`Process Case: ${req.body.pCase}`);
let _runtimePolicyContract = web3.eth.contract(JSON.parse(repoData[0].accessControlAbi)).at(accessControlAddr);
_runtimePolicyContract.nominate(
roleIndexMap.get(req.body.rNominator),
roleIndexMap.get(req.body.rNominee),
req.body.nominator,
req.body.nominee,
req.body.pCase,
{
from: req.body.nominator,
gas: 4700000
},
(error, result) => {
if (result) {
console.log(`SUCCESS: ${req.body.nominator} nominated ${req.body.nominee}`);
console.log(`Transaction Hash: ${result}`)
console.log('----------------------------------------------------------------------------------------------');
bindingOpTransactions.set(result, 0);
res.status(200).send({'transactionHash': result});
}
else {
console.log('ERROR', 'Nomination REJECTED by the Binding Policy');
console.log('----------------------------------------------------------------------------------------------');
res.status(404).send({'ERROR': error});
}
})
} else {
console.log(`Process Instance NOT FOUND.`);
res.status(404).send({ 'Error': `Process Instance NOT FOUND. The nomination of an actor must occurr afterthe process deployment.` });
console.log('----------------------------------------------------------------------------------------------');
}
}
}
} else {
console.log('UNDEFINED POLICY CONTRACT');
res.status(400).send({'state' : 'UNDEFINED POLICY CONTRACT'});
return;
}
})
}
})
models.post('/resources/release', (req, res) => {
if(processRegistryContract === undefined) {
res.status(404).send({'state' : 'UNDEFINED PROCESS REGISTRY'});
} else {
let _policyId = web3.toAscii(processRegistryContract.bindingPolicyFor.call(req.body.pCase)).toString().substr(0, 24);
policySchema.find({_id: _policyId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let roleIndexMap = findRoleMap(repoData[0].indexToRole);
if(validateInput(req.body.rNominator, req.body.rNominee, roleIndexMap, res)) {
if (verifyAddress(req.body.nominator, 'Nominator', res) &&
verifyAddress(req.body.pCase, 'Process Case', res)) {
let accessControlAddr = processRegistryContract.findRuntimePolicy.call(req.body.pCase);
if(accessControlAddr.toString() !== '0x0000000000000000000000000000000000000000') {
console.log(`${req.body.rNominator}[${req.body.nominator}] is releasing ${req.body.rNominee}[${req.body.nominee}]`);
console.log(`Process Case: ${req.body.pCase}`);
let _runtimePolicyContract = web3.eth.contract(JSON.parse(repoData[0].accessControlAbi)).at(accessControlAddr);
_runtimePolicyContract.release(
roleIndexMap.get(req.body.rNominator),
roleIndexMap.get(req.body.rNominee),
req.body.nominator,
req.body.pCase,
{
from: req.body.nominator,
gas: 4700000
},
(error, result) => {
if (result) {
console.log(`SUCCESS: ${req.body.nominator} released ${req.body.nominee}`);
console.log(`Transaction Hash: ${result}`)
console.log('----------------------------------------------------------------------------------------------');
bindingOpTransactions.set(result, 0);
res.status(200).send({'transactionHash': result});
}
else {
console.log('ERROR', 'Release REJECTED by the Binding Policy');
res.status(400).send({'ERROR': error});
}
})
} else {
console.log(`Process Instance NOT FOUND.`);
res.status(404).send({ 'Error': `Process Instance NOT FOUND. The release of an actor must occurr afterthe process deployment.` });
console.log('----------------------------------------------------------------------------------------------');
}
}
}
} else {
console.log('UNDEFINED POLICY CONTRACT');
res.status(400).send({'state' : 'UNDEFINED POLICY CONTRACT'});
return;
}
})
}
})
let verifyEndorser = (rEndorser: string, endorser: string, roleIndexMap, res: any) => {
if(!roleIndexMap.has(rEndorser)) {
console.log(`Error Endorser Role [${rEndorser}] NOT FOUND`);
res.status(404).send({ 'Error': `Nominee Role [${rEndorser}] NOT FOUND` });
console.log('----------------------------------------------------------------------------------------------');
return false;
}
return verifyAddress(endorser, 'Endorser', res);
}
models.post('/resources/vote', (req, res) => {
if(processRegistryContract === undefined) {
res.status(404).send({'state' : 'UNDEFINED PROCESS REGISTRY'});
} else {
let _policyId = web3.toAscii(processRegistryContract.bindingPolicyFor.call(req.body.pCase)).toString().substr(0, 24);
policySchema.find({_id: _policyId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let roleIndexMap = findRoleMap(repoData[0].indexToRole);
if(validateInput(req.body.rNominator, req.body.rNominee, roleIndexMap, res)) {
if (verifyEndorser(req.body.rEndorser, req.body.endorser, roleIndexMap, res) &&
verifyAddress(req.body.pCase, 'Process Case', res)) {
let accessControlAddr = processRegistryContract.findRuntimePolicy.call(req.body.pCase);
if(accessControlAddr.toString() !== '0x0000000000000000000000000000000000000000') {
let _runtimePolicyContract = web3.eth.contract(JSON.parse(repoData[0].accessControlAbi)).at(accessControlAddr);
if(req.body.onNomination) {
let voteResult = req.body.isAccepted === "true" ? 'endorsing' : 'rejecting';
console.log(`${req.body.rEndorser}[${req.body.endorser}] is ${voteResult} nomination of ${req.body.rNominee} by ${req.body.rNominator}`)
console.log(`Process Case: ${req.body.pCase}`)
_runtimePolicyContract.voteN (
roleIndexMap.get(req.body.rNominator),
roleIndexMap.get(req.body.rNominee),
roleIndexMap.get(req.body.rEndorser),
req.body.endorser,
req.body.pCase,
req.body.isAccepted,
{
from: req.body.endorser,
gas: 4700000
},
(error, result) => {
if (result) {
let tp = req.body.isAccepted === 'true' ? 'endorsed' : 'rejected';
console.log(`SUCCESS: ${req.body.endorser} ${tp} the nomination of ${req.body.nominee}`);
console.log(`Transaction Hash: ${result}`)
console.log('----------------------------------------------------------------------------------------------');
bindingOpTransactions.set(result, 0);
res.status(200).send({'transactionHash': result});
}
else {
console.log('ERROR', 'Vote REJECTED by the Binding Policy');
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send({'ERROR': error});
}
})
} else {
let voteResult = req.body.isAccepted === "true" ? 'endorsing' : 'rejecting';
console.log(`${req.body.rEndorser}[${req.body.endorser}] is ${voteResult} release of ${req.body.rNominee} by ${req.body.rNominator}`)
console.log(`Process Case: ${req.body.pCase}`)
_runtimePolicyContract.voteR (
roleIndexMap.get(req.body.rNominator),
roleIndexMap.get(req.body.rNominee),
roleIndexMap.get(req.body.rEndorser),
req.body.endorser,
req.body.pCase,
req.body.isAccepted,
{
from: req.body.endorser,
gas: 4700000
},
(error, result) => {
if (result) {
let tp = req.body.isAccepted === 'true' ? 'endorsed' : 'rejected';
console.log(`VOTE ACCEPTED: ${req.body.endorser} ${tp} the release of ${req.body.nominee}`);
console.log(`Transaction Hash: ${result}`)
console.log('----------------------------------------------------------------------------------------------');
bindingOpTransactions.set(result, 0);
res.status(200).send({'transactionHash': result});
}
else {
console.log('ERROR', 'Vote REJECTED by the Binding Policy');
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send({'ERROR': error});
}
})
}
} else {
console.log(`Process Instance NOT FOUND.`);
res.status(404).send({ 'Error': `Process Instance NOT FOUND. The voting of an operation must occurr afterthe process deployment.` });
console.log('----------------------------------------------------------------------------------------------');
}
}
}
} else {
console.log('UNDEFINED POLICY CONTRACT');
res.status(400).send({'state' : 'UNDEFINED POLICY CONTRACT'});
return;
}
})
}
})
let searchRepository = (top: number, queue: Array<string>, processData: Map<string, Array<any>>, response, policyId, roleIndexMap) => {
processData.set(queue[top], new Array());
repoSchema.find({_id: queue[top]},
(err, repoData) => {
if (err) {
return;
} else {
if(repoData.length > 0) {
let dictionary = repoData[0].indexToElement;
for (let i = 1; i < dictionary.length; i++) {
if(dictionary[i].type === 'Workitem') {
processData.get(queue[top]).push({taskIndex: i, roleIndex: roleIndexMap.get(dictionary[i].role)});
} else if (dictionary[i].type === 'Separate-Instance') {
queue.push(web3.toAscii(processRegistryContract.childrenFor.call(queue[top], i)).toString().substr(0, 24));
}
}
if(top < queue.length - 1)
searchRepository(top + 1, queue, processData, response, policyId, roleIndexMap);
else {
let procesRoleContract = generateRoleTaskContract(processData, 'TaskRoleContract', true);
procesRoleContract
.then((solidity) => {
let input = {}
input['TaskRoleContract'] = solidity;
console.log('=============================================');
console.log("SOLIDITY CODE");
console.log('=============================================');
console.log(solidity)
let output = solc.compile({sources: input}, 1);
if (Object.keys(output.contracts).length === 0) {
response.status(400).send('COMPILATION ERROR IN TASK-ROLE CONTRACT');
console.log('COMPILATION ERROR IN TASK-ROLE CONTRACT');
console.log(output.errors);
console.log('----------------------------------------------------------------------------------------------');
return;
}
let ProcContract = web3.eth.contract(JSON.parse(output.contracts['TaskRoleContract:TaskRoleContract_Contract'].interface));
ProcContract.new(
{
from: web3.eth.accounts[executionAccount],
data: "0x" + output.contracts['TaskRoleContract:TaskRoleContract_Contract'].bytecode,
gas: 4700000
},
(err, contract) => {
if (err) {
console.log(`ERROR: TASK-ROLE-MAP instance creation failed`);
console.log('RESULT ', err);
response.status(403).send(err);
} else if (contract.address) {
roleTaskSchema.create(
{
address: contract.address,
solidityCode: input['TaskRoleContract'],
abi: output.contracts['TaskRoleContract:TaskRoleContract_Contract'].interface,
bytecode: output.contracts['TaskRoleContract:TaskRoleContract_Contract'].bytecode,
},
(err, repoData) => {
if (err) {
console.log('Error ', err);
console.log('----------------------------------------------------------------------------------------------');
}
else {
let idAsString = repoData._id.toString();
processRegistryContract.relateProcessToPolicy(queue[0], policyId, idAsString, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error, result) => {
if (result) {
let gas = web3.eth.getTransactionReceipt(contract.transactionHash).gasUsed;
console.log("TaskRoleMap CREATED and RUNNING at " + contract.address.toString());
console.log('GAS USED: ', gas);
console.log('Repo Id: ', idAsString);
response.status(200).send({ address: contract.address.toString(), gas: gas, repoId: idAsString });
console.log('----------------------------------------------------------------------------------------------');
}
else {
console.log('ERROR ', error);
response.status(400).send(error);
}
})
}
})
}
});
})
.catch((err) => {
console.log('Error: process ID ' + queue[top] + ' not found');
response.status(404).send({ 'Error': 'Process ID not found' });
console.log('----------------------------------------------------------------------------------------------');
})
}
}
}
})
}
//////////////////////////////////////////////////////////////////////
/// PROCESS MODEL CONTROL FLOW + WORKLIST operations ///
//////////////////////////////////////////////////////////////////////
models.post('/models', (req, res) => {
if (processRegistryContract === undefined) {
console.log('ERROR: Runtime Registry NOT FOUND');
res.status(404).send({'Error': 'Runtime Registry NOT FOUND'});
console.log('----------------------------------------------------------------------------------------------');
} else {
console.log('GENERATING SMART CONTRACTS FROM PROCESS MODEL ...');
let modelInfo: ModelInfo = req.body as ModelInfo;
try {
let cont = parseModel(modelInfo);
cont.then(() => {
let input = {
'AbstractFactory': fs.readFileSync('./src/models/abstract/AbstractFactory.sol', 'utf8'),
'AbstractRegistry': fs.readFileSync('./src/models/abstract/AbstractRegistry.sol', 'utf8'),
'AbstractWorklist': fs.readFileSync('./src/models/abstract/AbstractWorklist.sol', 'utf8'),
'ProcessRegistry': fs.readFileSync('./src/models/abstract/ProcessRegistry.sol', 'utf8'),
'AbstractProcess': fs.readFileSync('./src/models/abstract/AbstractProcess.sol', 'utf8'),
'BindingAccessControl' : fs.readFileSync('./src/models/dynamic_binding/runtime_solidity/BindingAccessControl.sol', 'utf8')
};
input[modelInfo.id] = modelInfo.solidity;
console.log('=============================================');
console.log("SOLIDITY CODE");
console.log('=============================================');
console.log(modelInfo.solidity);
console.log('....................................................................');
let output = solc.compile({sources: input}, 1);
if (Object.keys(output.contracts).length === 0) {
res.status(400).send('COMPILATION ERROR IN SMART CONTRACTS');
console.log('COMPILATION ERROR IN SMART CONTRACTS');
console.log(output.errors);
console.log('----------------------------------------------------------------------------------------------');
return;
}
console.log('CONTRACTS GENERATED AND COMPILED SUCCESSFULLY');
Object.keys(output.contracts).forEach(key => {
let bytecode = '0x' + output.contracts[key].bytecode;
var gasEstimate = web3.eth.estimateGas({data: bytecode});
// console.log(".............................................");
// console.log("Contract Name: " + key.split(':')[1]);
// console.log("Gas Estimation: " + gasEstimate);
});
console.log('....................................................................');
console.log('STARTING PROCESS MODEL REGISTRATION ...');
registerModel(modelInfo, output.contracts, res);
})
} catch (e) {
console.log("ERROR: ", e);
res.status(400).send(e);
console.log('----------------------------------------------------------------------------------------------');
}
}
});
// Creating a new instance of a registered (root) process
let caseCreatorMap: Map<string, string> = new Map();
models.post('/models/:bundleId', (req, res) => {
if (verifyAddress(req.body.caseCreator, 'Case Creator', res) && processRegistryContract !== undefined) {
let _taskRoleId = web3.toAscii(processRegistryContract.taskRoleMapFromId.call(req.params.bundleId)).toString().substr(0, 24);
roleTaskSchema.find({_id: _taskRoleId},
(err, repoDataTaskRole) => {
if (!err && repoDataTaskRole && repoDataTaskRole.length > 0) {
let _policyId = web3.toAscii(processRegistryContract.bindingPolicyFromId.call(req.params.bundleId)).toString().substr(0, 24);
policySchema.find({_id: _policyId},
(err, repoDataPolicy) => {
if (!err && repoDataPolicy && repoDataPolicy.length > 0) {
let roleIndexMap = findRoleMap(repoDataPolicy[0].indexToRole);
if (!roleIndexMap.has(req.body.creatorRole)) {
console.log('Case Creator Role NOT found');
res.status(404).send('Case Creator Role NOT found');
console.log('----------------------------------------------------------------------------------------------');
} else {
repoSchema.find({_id: req.params.bundleId},
(err, repoData) => {
if (err)
res.status(404).send('Process model not found');
else {
console.log("TRYING TO CREATE INSTANCE OF CONTRACT: ", repoData[0].rootProcessID);
let AccessControlContract = web3.eth.contract(JSON.parse(repoDataPolicy[0].accessControlAbi));
AccessControlContract.new(processRegistryContract.address, repoDataPolicy[0].address, repoDataTaskRole[0].address,
{
from: req.body.caseCreator,
data: "0x" + repoDataPolicy[0].accessControlBytecode,
gas: 4700000
},
(err, contract) => {
if (err) {
console.log(`ERROR: BindingAccessControl instance creation failed`);
console.log('RESULT ', err);
res.status(403).send(err);
} else if (contract.address) {
let policyGas = web3.eth.getTransactionReceipt(contract.transactionHash).gasUsed;
console.log("BindingAccessControl Contract DEPLOYED and RUNNING at " + contract.address.toString());
console.log('Gas Used: ', policyGas);
console.log('....................................................................');
processRegistryContract.newBundleInstanceFor(repoData[0]._id.toString(), 0, contract.address, {
from: web3.eth.accounts[executionAccount],
gas: 4500000
},
(errNew, resNew) => {
if (!errNew) {
let myEvent = processRegistryContract.NewInstanceCreatedFor({
fromBlock: 0,
toBlock: 'latest'
});
myEvent.watch((errEvt, resEvt) => {
if (!errEvt) {
if (resEvt && resEvt.transactionHash === resNew && resEvt.event === 'NewInstanceCreatedFor' && parseInt(resEvt.args.parent.toString(), 16) === 0) {
myEvent.stopWatching();
let processAddress = resEvt.args.processAddress.toString();
console.log('Root Process Contract DEPLOYED and RUNNING !!! AT ADDRESS: ', processAddress);
console.log('GAS USED: ', web3.eth.getTransactionReceipt(resEvt.transactionHash).gasUsed);
console.log('....................................................................');
contract.nominateCaseCreator(roleIndexMap.get(req.body.creatorRole), req.body.caseCreator, processAddress, {
from: req.body.caseCreator,
gas: 4700000
},
(error1, result1) => {
if (result1) {
console.log("Case-creator nominated ");
caseCreatorMap.set(result1, processAddress);
console.log('----------------------------------------------------------------------------------------------');
res.status(200).send({
address: processAddress,
gas: web3.eth.getTransactionReceipt(resEvt.transactionHash).gasUsed,
runtimeAddress: contract.address.toString(),
runtimeGas: policyGas,
transactionHash: result1,
});
}
else {
console.log('ERROR ', error1);
console.log('----------------------------------------------------------------------------------------------');
res.status(200).send({ERROR: error1});
}
})
}
} else {
console.log('ERROR ', errEvt);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send(errEvt);
}
});
} else {
console.log('ERROR ', errNew);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send(errNew);
}
});
}
});
}
});
}
} else {
console.log('UNDEFINED POLICY CONTRACT');
res.status(400).send({'state' : 'UNDEFINED POLICY CONTRACT'});
return;
}
})
} else {
console.log('Task-Role Contract NOT found');
res.status(404).send('Task-Role Contract NOT found');
console.log('----------------------------------------------------------------------------------------------');
}
})
} else
res.status(404).send('Process model not found');
});
// Querying activation for a given process (repository ID provided)
models.get('/processes/:procAddress', (req, res) => {
let contractAddress = req.params.procAddress;
console.log('QUERYING ACTIVATION FOR CONTRACT:', contractAddress);
if (processRegistryContract) {
let bundleId = web3.toAscii(processRegistryContract.bundleFor.call(contractAddress)).toString().substr(0, 24);
repoSchema.find({_id: bundleId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let workitems = [],
serviceTasks = [];
console.log("CHECKING STARTED ELEMENTS ");
instanceStateFor(0, [contractAddress], repoData[0].bpmnModel, workitems, serviceTasks, res);
} else {
console.log('Instance Not Found');
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send({});
}
})
} else {
console.log('Instance Not Found');
res.status(400).send({});
}
});
// Performing an operation on a started workitem: Execute, Allocate, Revoke.
models.post('/workitems/:worklistAddress/:reqId', (req, res) => {
let worklistAddress = req.params.worklistAddress;
let reqId = req.params.reqId;
if(! web3.isAddress(req.body.user)) {
console.log('Error: ', `Invalid Addres '${req.body.user}' of user trying to perform the operation.`);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send(`Invalid Addres '${req.body.user}' of user trying to perform the operation.`);
} else if (processRegistryContract) {
let bundleId = web3.toAscii(processRegistryContract.worklistBundleFor.call(worklistAddress)).toString().substr(0, 24);
repoSchema.find({_id: bundleId},
(err, repoData) => {
if (!err && repoData && repoData.length > 0) {
let worklistInstance = web3.eth.contract(JSON.parse(repoData[0].worklistAbi)).at(worklistAddress);
let nodeIndex = worklistInstance.elementIndexFor.call(reqId);
let node = repoData[0].indexToElement[nodeIndex];
let inputParams = req.body.inputParameters;
let realParameters = [];
let functionName = '';
realParameters = inputParams.length > 0 ? [reqId].concat(inputParams) : [reqId];
console.log(`WANT TO EXECUTE TASK: ${node.name}, ON WORKLIST: ${worklistAddress}`);
functionName = node.name;
worklistInstance[functionName].apply(this, realParameters.concat({
from: req.body.user,
gas: 4700000
}, (error, result) => {
if (error) {
console.log('ERROR: ' + error);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send('Error');
} else {
console.log(`TRANSACTION: ${result}, PENDING !!!`);
console.log('----------------------------------------------------------------------------------------------');
res.status(200).send({transactionHash: result});
}
}));
} else {
console.log('Error: ', err);
console.log('----------------------------------------------------------------------------------------------');
res.status(400).send('Error');
}
})
} else {
console.log('Error: ', 'Process Registry Undefined');
res.status(400).send('Process Registry Undefined');
}
});
/////////////// Methods for deploying model //////////////////////
// Step 1. Model Registration: Collects the compilation artifacts of the produced models,
// and saves all these metadata as an entry in the Process Repository.
let registerModel = (modelInfo, contracts, response) => {
// Sorting elements such that children are created first
let queue = [{nodeId: modelInfo.id, nodeName: modelInfo.name, bundleId: '', nodeIndex: 0, bundleParent: '', factoryContract: ''}];
for (let i = 0; i < queue.length; i++) {
if (modelInfo.controlFlowInfoMap.has(queue[i].nodeId)) {
let cfInfo = modelInfo.controlFlowInfoMap.get(queue[i].nodeId);
let candidates = [cfInfo.multiinstanceActivities, cfInfo.nonInterruptingEvents, cfInfo.callActivities];
candidates.forEach(children => {
if (children) {
children.forEach((value, key) => {
queue.push({nodeId: key, nodeName: value, bundleId: '', nodeIndex: 0, bundleParent: '', factoryContract: '' });
})
}
})
}
}
queue.reverse();
let nodeIndexes = new Map();
for (let i = 0; i < queue.length; i++)
nodeIndexes.set(queue[i].nodeId, i);
console.log('....................................................................');
console.log('UPDATING COMPILATION ARTIFACTS IN REPOSITORY ...');
registerModels(0, queue, nodeIndexes, modelInfo, contracts, response);
};
let registerModels = (currentIndex, sortedElements, nodeIndexes, modelInfo, contracts, res) => {
let nodeName = sortedElements[currentIndex].nodeName;
let gNodeId = sortedElements[currentIndex].nodeId;
let controlFlowInfo = modelInfo.controlFlowInfoMap.get(gNodeId);
if (modelInfo.globalNodeMap.get(gNodeId).$type === 'bpmn:StartEvent')
controlFlowInfo = modelInfo.controlFlowInfoMap.get(modelInfo.globalNodeMap.get(gNodeId).$parent.id);
if (controlFlowInfo) {
let indexToFunctionName = [];
let childrenSubproc = [];
controlFlowInfo.nodeList.forEach(nodeId => {
let element = modelInfo.globalNodeMap.get(nodeId);
if (controlFlowInfo.nodeList.indexOf(nodeId) >= 0) {
let type = "None";
let role = "None";
let indexRole = 0;
if (controlFlowInfo.callActivities.has(nodeId) || controlFlowInfo.multiinstanceActivities.has(nodeId) || controlFlowInfo.nonInterruptingEvents.has(nodeId))
type = "Separate-Instance";
else if (element.$type === 'bpmn:ServiceTask')
type = "Service";
else if (element.$type === 'bpmn:UserTask' || element.$type === 'bpmn:ReceiveTask' || controlFlowInfo.catchingMessages.indexOf(nodeId) >= 0) {
type = "Workitem";
if(!controlFlowInfo.taskRoleMap.has(nodeId))
throw 'No role related to User Task: ' + controlFlowInfo.nodeNameMap.get(nodeId);
role = controlFlowInfo.taskRoleMap.get(nodeId);
}
indexToFunctionName[controlFlowInfo.nodeIndexMap.get(nodeId)] = {
name: controlFlowInfo.nodeNameMap.get(nodeId),
id: nodeId,
type: type,
role: role
};
if (controlFlowInfo.callActivities.has(nodeId) || controlFlowInfo.multiinstanceActivities.has(nodeId) || controlFlowInfo.nonInterruptingEvents.has(nodeId)) {
childrenSubproc.push(nodeId);
sortedElements[nodeIndexes.get(nodeId)].nodeIndex = controlFlowInfo.nodeIndexMap.get(nodeId);
if (controlFlowInfo.externalBundles.has(nodeId))
sortedElements[nodeIndexes.get(nodeId)].bundleId = controlFlowInfo.externalBundles.get(nodeId);
}
}
});
let bpmnModel = currentIndex < sortedElements.length - 1 ? 'empty' : modelInfo.bpmn;
let worklistAbi = contracts[`${modelInfo.id}:${nodeName}_Worklist`] ? contracts[`${modelInfo.id}:${nodeName}_Worklist`].interface : 'undefined';
repoSchema.create(
{
rootProcessID: gNodeId,
rootProcessName: nodeName,
bpmnModel: bpmnModel,
solidityCode: modelInfo.solidity,
abi: contracts[`${modelInfo.id}:${nodeName}_Contract`].interface,
bytecode: contracts[`${modelInfo.id}:${nodeName}_Contract`].bytecode,
indexToElement: indexToFunctionName,
worklistAbi: worklistAbi
},
(err, repoData) => {
if (err) {
console.log('Error ', err);
// registerModels(currentIndex, sortedElements, createdElementMap, modelInfo, contracts, res);
}
else {
let idAsString = repoData._id.toString();
sortedElements[currentIndex].bundleId = idAsString;
sortedElements[currentIndex].bundleParent = idAsString;
childrenSubproc.forEach(childId => {
sortedElements[nodeIndexes.get(childId)].bundleParent = idAsString;
});
console.log(`Compilation artifacts of ${nodeName} updated in repository with id ${idAsString}`);
continueRegistration(currentIndex, sortedElements, nodeIndexes, modelInfo, contracts, res);
}
})
} else {
continueRegistration(currentIndex, sortedElements, nodeIndexes, modelInfo, contracts, res);
}
};
let continueRegistration = (currentIndex, sortedElements, nodeIndexes, modelInfo, contracts, res) => {
if (currentIndex + 1 >= sortedElements.length) {
console.log('....................................................................');
console.log('RELATING PARENT TO NESTED CHILDREN IN REGISTRY ...');
createParent2ChildRelation(0, sortedElements, contracts, modelInfo, res);
}
else
registerModels(currentIndex + 1, sortedElements, nodeIndexes, modelInfo, contracts, res);
};
let createParent2ChildRelation = (currentIndex, sortedElements, outputContracts, modelInfo, response) => {
processRegistryContract.addChildBundleId(sortedElements[currentIndex].bundleParent, sortedElements[currentIndex].bundleId, sortedElements[currentIndex].nodeIndex, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error, result) => {
if (result) {
console.log(`${sortedElements[currentIndex].nodeName} : ${sortedElements[currentIndex].bundleParent} => (${sortedElements[currentIndex].nodeIndex}), ${sortedElements[currentIndex].bundleId}`);
if (currentIndex + 1 < sortedElements.length) {
createParent2ChildRelation(currentIndex + 1, sortedElements, outputContracts, modelInfo, response);
} else {
console.log('....................................................................');
let removedCallActivities = [];
sortedElements.forEach(element => {
if (modelInfo.controlFlowInfoMap.has(element.nodeId) || modelInfo.globalNodeMap.get(element.nodeId).$type === 'bpmn:StartEvent') {
removedCallActivities.push(element);
}
});
if (removedCallActivities.length > 0) {
console.log('DEPLOYING FACTORIES AND UPDATING PROCESS-FACTORY RELATION IN REGISTRY ...');
registerFactory(0, removedCallActivities, outputContracts, modelInfo, response);
}
}
}
else {
console.log('ERROR ', error);
response.status(400).send(error);
}
})
};
let registerFactory = (currentIndex, sortedElements, outputContracts, modelInfo, response) => {
let entryFactoryName = `${modelInfo.id}:${sortedElements[currentIndex].nodeName}_Factory`;
let FactoryContract = web3.eth.contract(JSON.parse(outputContracts[entryFactoryName].interface));
FactoryContract.new(
{from: web3.eth.accounts[0], data: "0x" + outputContracts[entryFactoryName].bytecode, gas: 4700000},
(errF, contractF) => {
if (errF) {
console.log(`ERROR: ${sortedElements[currentIndex].nodeName}_Factory instance creation failed`);
console.log('RESULT ', errF);
response.status(400).send(errF);
} else if (contractF.address) {
console.log(`${sortedElements[currentIndex].nodeName}_Factory running at address ${contractF.address.toString()}`);
continueFactoryRegistration(currentIndex, sortedElements, outputContracts, contractF, modelInfo, response);
}
});
};
let continueFactoryRegistration = (currentIndex, sortedElements, outputContracts, contractF, modelInfo, response) => {
processRegistryContract.registerFactory(sortedElements[currentIndex].bundleId, contractF.address, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error1, result1) => {
if (result1) {
console.log(`${sortedElements[currentIndex].nodeName}_Factory registered SUCCESSFULLY in Process Registry`);
console.log('....................................................................');
if (currentIndex + 1 < sortedElements.length) {
registerFactory(currentIndex + 1, sortedElements, outputContracts, modelInfo, response);
} else {
console.log('....................................................................');
console.log('DEPLOYONG WORKLIST CONTRACTS AND UPDATING PROCESS REGISTRY ...');
createWorklistInstances(0, sortedElements, outputContracts, modelInfo, response);
}
}
else {
console.log('Error ', error1);
response.status(400).send(error1);
}
})
};
let createWorklistInstances = (currentIndex, sortedElements, outputContracts, modelInfo, response) => {
let entryWorklistName = `${modelInfo.id}:${sortedElements[currentIndex].nodeName}_Worklist`;
if (outputContracts[entryWorklistName]) {
let WorklistContract = web3.eth.contract(JSON.parse(outputContracts[entryWorklistName].interface));
WorklistContract.new(
{from: web3.eth.accounts[0], data: "0x" + outputContracts[entryWorklistName].bytecode, gas: 4700000},
(errW, contractW) => {
if (errW) {
console.log(`${sortedElements[currentIndex].nodeName}_Worklist instance creation failed`);
console.log('ERROR: ', errW);
response.status(400).send(errW);
}
else if (contractW.address) {
console.log(`${sortedElements[currentIndex].nodeName}_Worklist running at address ${contractW.address.toString()}`);
processRegistryContract.registerWorklist(sortedElements[currentIndex].bundleId, contractW.address, {
from: web3.eth.accounts[0],
gas: 4700000
},
(error1, result1) => {
if (result1) {
console.log(`${sortedElements[currentIndex].nodeName}_Worklist registered SUCCESSFULLY in Process Registry`);
console.log('....................................................................');
sortedElements[currentIndex] = {
nodeId: sortedElements[currentIndex].nodeId,
nodeName: sortedElements[currentIndex].nodeName,
bundleId: sortedElements[currentIndex].bundleId,
bundleParent: sortedElements[currentIndex].bundleParent,
worklist: contractW.address
};
continueWorklistCreation(currentIndex, sortedElements, outputContracts, modelInfo, response);
}
else {
console.log('ERROR ', error1);
response.status(400).send(error1);
}
})
}
}
)
} else {
continueWorklistCreation(currentIndex, sortedElements, outputContracts, modelInfo, response);
}
};
let continueWorklistCreation = (currentIndex, sortedElements, outputContracts, modelInfo, response) => {
if (currentIndex + 1 < sortedElements.length) {
createWorklistInstances(currentIndex + 1, sortedElements, outputContracts, modelInfo, response);
} else {
let bundleId = '';
for (let i = 0; i < sortedElements.length; i++) {
if (sortedElements[i].nodeName === modelInfo.name) {
bundleId = sortedElements[i].bundleId;
break;
}
}
console.log('----------------------------------------------------------------------------------------------');
response.status(200).send({
id: bundleId,
name: modelInfo.name,
bpmn: modelInfo.bpmn,
solidity: modelInfo.solidity
});
}
};
/////////////////////////////////////////////////////////////////////
let instanceStateFor = (currentIndex, nestedContracts, bpmnModel, workitems, serviceTasks, res) => {
let contractAddress = nestedContracts[currentIndex];
let bundleId = web3.toAscii(processRegistryContract.bundleFor.call(contractAddress)).toString().substr(0, 24);
repoSchema.find({_id: bundleId},
(err, repoData) => {
if (err) {
console.log('ERROR ', err);
return [];
} else {
let contractInstance = web3.eth.contract(JSON.parse(repoData[0].abi)).at(contractAddress);
let worklistAddress = contractInstance.getWorklistAddress.call();
let worklistInstance: any;
if (worklistAddress.toString() !== '0x0000000000000000000000000000000000000000')
worklistInstance = web3.eth.contract(JSON.parse(repoData[0].worklistAbi)).at(worklistAddress);
let dictionary = repoData[0].indexToElement;
let startedActivities = contractInstance.startedActivities.call().toString(2).split('').reverse();
for (let index = 0; index < startedActivities.length; index++) {
if (startedActivities[index] === '1') {
if (dictionary[index].type === 'Workitem') {
let reqInd = worklistInstance.workItemsFor.call(index, contractAddress).toString(2).split('').reverse();
for (let i = 0; i < reqInd.length; i++) {
if (reqInd[i] === '1') {
let notFound = true;
for (let j = 0; j < workitems.length; j++) {
if (workitems[j].elementId === dictionary[index].id && workitems[j].bundleId === bundleId) {
workitems[j].hrefs.push(`/workitems/${worklistAddress}/${i}`);
workitems[j].pCases.push(worklistInstance.processInstanceFor.call(i));
notFound = false;
break;
}
}
if (notFound) {
workitems.push({
elementId: dictionary[index].id,
elementName: dictionary[index].name,
input: findParameters(repoData[0].worklistAbi, dictionary[index].name),
bundleId: bundleId,
processAddress: contractAddress,
pCases: [contractAddress],
hrefs: [`/workitems/${worklistAddress}/${i}`]
});
}
}
}
} else if (dictionary[index].type === 'Service') {
// PENDING
} else if (dictionary[index].type === 'Separate-Instance') {
let startedInstances = contractInstance.startedInstanceIndexFor.call(index).toString(2).split('').reverse();
let allInstances = contractInstance.allInstanceAddresses.call();
for (let i = 0; i < startedInstances.length; i++)
if (startedInstances[i] === '1')
nestedContracts.push(allInstances[i]);
}
}
}
if (currentIndex + 1 < nestedContracts.length)
instanceStateFor(currentIndex + 1, nestedContracts, bpmnModel, workitems, serviceTasks, res);
else {
if (workitems.length == 0 && serviceTasks.length == 0)
console.log('No started elements ...');
else {
workitems.forEach(elem => {
console.log("Element ID: ", elem.elementId);
console.log("Element Name: ", elem.elementName);
console.log("Input Parameters: ", elem.input);
console.log("bundleId: ", elem.bundleId);
console.log("pCases: ", elem.pCases)
console.log("hrefs: ", elem.hrefs);
console.log("...............................................................");
})
}
console.log('----------------------------------------------------------------------------------------------');
res.status(200).send({bpmn: bpmnModel, workitems: workitems, serviceTasks: serviceTasks});
}
}
});
};
let findParameters = (contractAbi, functionName) => {
let jsonAbi = JSON.parse(contractAbi);
let candidates = [];
jsonAbi.forEach(element => {
if (element.name === functionName) {
candidates = element.inputs;
}
});
let res = [];
candidates.forEach(element => {
if (element.name && element.name !== 'workitemId')
res.push(element);
});
return res;
};
export default models; | the_stack |
import 'jest';
import * as DevicesService from './devicesService';
import * as DataplaneService from './dataplaneServiceHelper';
import { HTTP_OPERATION_TYPES, HUB_DATA_PLANE_API_VERSION } from '../../constants/apiConstants';
import { Twin } from '../models/device';
import { DeviceIdentity } from './../models/deviceIdentity';
import { buildQueryString, getConnectionInfoFromConnectionString } from '../shared/utils';
import { MonitorEventsParameters } from '../parameters/deviceParameters';
import * as interfaceUtils from '../shared/interfaceUtils';
const deviceId = 'deviceId';
const connectionString = 'HostName=test-string.azure-devices.net;SharedAccessKeyName=owner;SharedAccessKey=fakeKey=';
const connectionInfo = getConnectionInfoFromConnectionString(connectionString);
const headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
// tslint:disable
const emptyPromise = new Promise(() => {});
const twin: Twin = {
deviceId,
deviceEtag: '',
etag: 'AAAAAAAAAAE=',
status: 'enabled',
statusUpdateTime: '0001-01-01T00:00:00Z',
connectionState: 'Disconnected',
lastActivityTime: '0001-01-01T00:00:00Z',
cloudToDeviceMessageCount: 0,
authenticationType: 'sas',
x509Thumbprint: {primaryThumbprint: null, secondaryThumbprint: null},
properties: {},
capabilities: {iotEdge: false},
version: 1
};
const deviceIdentity: DeviceIdentity = {
authentication: {symmetricKey: {primaryKey: null, secondaryKey: null}, type: 'sas', x509Thumbprint: null},
capabilities: {iotEdge: false},
cloudToDeviceMessageCount: null,
deviceId,
etag: null,
lastActivityTime: null,
status: 'enabled',
statusReason: null,
statusUpdatedTime: null
};
// tslint:enable
const sasToken = 'testSasToken';
const mockDataPlaneConnectionHelper = () => {
if (!(connectionInfo && connectionInfo.hostName)) {
return;
}
return {
connectionInfo,
sasToken,
};
};
describe('deviceTwinService', () => {
context('fetchDeviceTwin', () => {
it ('returns if deviceId is not specified', () => {
expect(DevicesService.fetchDeviceTwin({deviceId: undefined})).toEqual(emptyPromise);
});
it('calls fetch with specified parameters and returns deviceTwin when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo, connectionString, sasToken});
// tslint:disable
const response = {
json: () => {return {
body: twin,
headers:{}
}},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Get,
path: `twins/${deviceId}`,
sharedAccessSignature: connectionInformation.sasToken
};
const result = await DevicesService.fetchDeviceTwin({deviceId});
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual(twin);
});
it('throws Error when promise rejects', async done => {
window.fetch = jest.fn().mockRejectedValueOnce(new Error('Not found'));
await expect(DevicesService.fetchDeviceTwin({deviceId})).rejects.toThrowError('Not found');
done();
});
});
context('updateDeviceTwin', () => {
it('calls fetch with specified parameters and invokes updateDeviceTwin when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo, connectionString, sasToken});
// tslint:disable
const responseBody = twin;
const response = {
json: () => {
return {
body: responseBody,
headers:{}
}
},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
const result = await DevicesService.updateDeviceTwin(twin);
const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
body: JSON.stringify(twin),
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Patch,
path: `twins/${deviceId}`,
sharedAccessSignature: connectionInformation.sasToken
};
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual(responseBody);
});
it('throws Error when promise rejects', async () => {
window.fetch = jest.fn().mockRejectedValueOnce(new Error());
await expect(DevicesService.updateDeviceTwin(twin)).rejects.toThrow(new Error());
});
});
context('invokeDirectMethod', () => {
const parameters = {
connectTimeoutInSeconds: 10,
connectionString,
deviceId: undefined,
methodName: 'methodName',
payload: {foo: 'bar'},
responseTimeoutInSeconds : 10,
};
it ('returns if deviceId is not specified', () => {
expect(DevicesService.invokeDirectMethod(parameters)).toEqual(emptyPromise);
});
it('calls fetch with specified parameters and invokes invokeDirectMethod when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo: getConnectionInfoFromConnectionString(parameters.connectionString), connectionString, sasToken});
// tslint:disable
const responseBody = {description: 'invoked'};
const response = {
json: () => {
return {
body: responseBody,
headers:{}
}
},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
const result = await DevicesService.invokeDirectMethod({
...parameters,
deviceId
});
const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
body: JSON.stringify({
connectTimeoutInSeconds: parameters.connectTimeoutInSeconds,
methodName: parameters.methodName,
payload: parameters.payload,
responseTimeoutInSeconds: parameters.responseTimeoutInSeconds,
}),
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Post,
path: `twins/${deviceId}/methods`,
sharedAccessSignature: connectionInformation.sasToken
};
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual(responseBody);
});
it('throws Error when promise rejects', async () => {
window.fetch = jest.fn().mockRejectedValueOnce(new Error());
await expect(DevicesService.invokeDirectMethod({
...parameters,
deviceId
})).rejects.toThrow(new Error());
});
});
context('cloudToDeviceMessage', () => {
const parameters = {
body: 'body',
deviceId: 'deviceId',
properties: []
};
it('calls sendMessageToDevice with expected parameters', async () => {
const sendMessageToDevice = jest.fn();
jest.spyOn(interfaceUtils, 'getDeviceInterface').mockReturnValue({
sendMessageToDevice
});
await DevicesService.cloudToDeviceMessage(parameters);
expect(sendMessageToDevice).toBeCalledWith({
connectionString,
deviceId: 'deviceId',
messageBody: 'body',
messageProperties: []
});
});
});
context('addDevice', () => {
const parameters = {
connectionString,
deviceIdentity: undefined
};
it ('returns if deviceIdentity is not specified', () => {
expect(DevicesService.addDevice(parameters)).toEqual(emptyPromise);
});
it('calls fetch with specified parameters and invokes addDevice when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo: getConnectionInfoFromConnectionString(parameters.connectionString), connectionString, sasToken});
// tslint:disable
const responseBody = deviceIdentity;
const response = {
json: () => {
return {
body: responseBody,
headers:{}
}
},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
const result = await DevicesService.addDevice({
...parameters,
deviceIdentity
});
const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
body: JSON.stringify(deviceIdentity),
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Put,
path: `devices/${deviceId}`,
sharedAccessSignature: connectionInformation.sasToken
};
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual(responseBody);
});
it('throws Error when promise rejects', async () => {
window.fetch = jest.fn().mockRejectedValueOnce(new Error());
await expect(DevicesService.addDevice({
...parameters,
deviceIdentity
})).rejects.toThrow(new Error());
});
});
context('updateDevice', () => {
const parameters = {
connectionString,
deviceIdentity: undefined
};
it ('returns if deviceIdentity is not specified', () => {
expect(DevicesService.updateDevice(parameters)).toEqual(emptyPromise);
});
it('calls fetch with specified parameters and invokes updateDevice when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo: getConnectionInfoFromConnectionString(parameters.connectionString), connectionString, sasToken});
// tslint:disable
const responseBody = deviceIdentity;
const response = {
json: () => {
return {
body: responseBody,
headers:{}
}
},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
const result = await DevicesService.updateDevice({
...parameters,
deviceIdentity
});
const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
body: JSON.stringify(deviceIdentity),
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Put,
path: `devices/${deviceId}`,
sharedAccessSignature: connectionInformation.sasToken
};
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual(responseBody);
});
it('throws Error when promise rejects', async () => {
window.fetch = jest.fn().mockRejectedValueOnce(new Error());
await expect(DevicesService.updateDevice({
...parameters,
deviceIdentity
})).rejects.toThrow(new Error());
});
});
context('fetchDevice', () => {
const parameters = {
connectionString,
deviceId: undefined
};
it ('returns if deviceId is not specified', () => {
expect(DevicesService.fetchDevice(parameters)).toEqual(emptyPromise);
});
it('calls fetch with specified parameters and invokes fetchDevice when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo: getConnectionInfoFromConnectionString(parameters.connectionString), connectionString, sasToken});
// tslint:disable
const responseBody = deviceIdentity;
const response = {
json: () => {
return {
body: responseBody,
headers:{}
}
},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
const result = await DevicesService.fetchDevice({
...parameters,
deviceId
});
const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Get,
path: `devices/${deviceId}`,
sharedAccessSignature: connectionInformation.sasToken
};
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual(responseBody);
});
it('throws Error when promise rejects', async () => {
window.fetch = jest.fn().mockRejectedValueOnce(new Error());
await expect(DevicesService.fetchDevice({
...parameters,
deviceId
})).rejects.toThrowError();
});
});
context('fetchDevices', () => {
const parameters = {
connectionString,
query: {
clauses: [],
continuationTokens: ['', '123'],
currentPageIndex: 1,
deviceId
}
};
it('calls fetch with specified parameters and invokes fetchDevices when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo: getConnectionInfoFromConnectionString(parameters.connectionString), connectionString, sasToken});
// tslint:disable
const responseBody = deviceIdentity;
const response = {
json: () => {
return {
body: [responseBody],
headers:{foo: 'bar'}
}
},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
const result = await DevicesService.fetchDevices(parameters);
const connectionInformation = mockDataPlaneConnectionHelper();
const queryString = buildQueryString(parameters.query);
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
body: JSON.stringify({
query: queryString,
}),
headers: {'x-ms-max-item-count': 100, 'x-ms-continuation': '123'},
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Post,
path: 'devices/query',
sharedAccessSignature: connectionInformation.sasToken,
};
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual({body: [responseBody], headers: {foo: 'bar'}});
});
it('throws Error when promise rejects', async () => {
window.fetch = jest.fn().mockRejectedValueOnce(new Error());
await expect(DevicesService.fetchDevices(parameters)).rejects.toThrow(new Error()).catch();
});
});
context('deleteDevices', () => {
let parameters = {
connectionString,
deviceIds: undefined
};
it ('returns if deviceId is not specified', () => {
expect(DevicesService.deleteDevices(parameters)).toEqual(emptyPromise);
});
it('calls fetch with specified parameters and invokes deleteDevices when response is 200', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo: getConnectionInfoFromConnectionString(parameters.connectionString), connectionString, sasToken});
// tslint:disable
const responseBody = {isSuccessful:true, errors:[], warnings:[]};
const response = {
json: () => {
return {
body: responseBody,
headers:{}
}
},
status: 200
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
parameters = {
...parameters,
deviceIds: [deviceId]
};
const result = await DevicesService.deleteDevices(parameters);
const connectionInformation = mockDataPlaneConnectionHelper();
const deviceDeletionInstructions = parameters.deviceIds.map(id => {
return {
etag: '*',
id,
importMode: 'deleteIfMatchEtag'
};
});
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
body: JSON.stringify(deviceDeletionInstructions),
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Post,
path: `devices`,
sharedAccessSignature: connectionInformation.sasToken
};
const serviceRequestParams = {
body: JSON.stringify(dataPlaneRequest),
cache: 'no-cache',
credentials: 'include',
headers,
method: HTTP_OPERATION_TYPES.Post,
mode: 'cors',
};
expect(fetch).toBeCalledWith(DataplaneService.DATAPLANE_CONTROLLER_ENDPOINT, serviceRequestParams);
expect(result).toEqual(responseBody);
});
it('throws Error when response status is 500', async () => {
// tslint:disable
const response = {
json: () => {return {
body: {},
headers:{}
}},
status: 500
} as any;
// tslint:enable
jest.spyOn(window, 'fetch').mockResolvedValue(response);
await expect(DevicesService.deleteDevices({
...parameters,
deviceIds: [deviceId]
})).rejects.toThrow(new Error('500')).catch();
});
});
context('monitorEvents', () => {
const parameters: MonitorEventsParameters = {
consumerGroup: '$Default',
customEventHubConnectionString: undefined,
deviceId,
hubConnectionString: undefined,
moduleId: undefined,
startTime: undefined
};
it('calls startEventHubMonitoring with expected parameters', async () => {
jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo: getConnectionInfoFromConnectionString(connectionString), connectionString, sasToken});
const startEventHubMonitoring = jest.fn();
jest.spyOn(interfaceUtils, 'getEventHubInterface').mockReturnValue({
startEventHubMonitoring
});
await DevicesService.monitorEvents(parameters);
expect(startEventHubMonitoring).toBeCalledWith({
...parameters,
hubConnectionString: connectionString,
startTime: parameters.startTime && parameters.startTime.toISOString()
});
});
});
}); | the_stack |
import * as DomUtil from '../common/dom_util';
import {SemanticFont, SemanticRole, SemanticType} from './semantic_attr';
import {SemanticNode} from './semantic_node';
import {SemanticAbstractParser} from './semantic_parser';
import * as SemanticPred from './semantic_pred';
import SemanticProcessor from './semantic_processor';
import * as SemanticUtil from './semantic_util';
export class SemanticMathml extends SemanticAbstractParser<Element> {
private parseMap_: {[key: string]:
(p1: Element, p2: Element[]) => SemanticNode};
/**
* Get an attribute from a node and provide a default if it does not exist. It
* returns null if attribute is empty string or whitespace only.
* @param node The node from which to retrieve the attribute.
* @param attr The attribute.
* @param def The default return value.
* @return The value of the attribute or null.
*/
private static getAttribute_(node: Element, attr: string, def: string): string
|null {
if (!node.hasAttribute(attr)) {
return def;
}
let value = node.getAttribute(attr);
if (value.match(/^\s*$/)) {
return null;
}
return value;
}
/**
* The semantic parser for MathML elements.
*/
constructor() {
super('MathML');
this.parseMap_ = {
'SEMANTICS': this.semantics_.bind(this),
'MATH': this.rows_.bind(this),
'MROW': this.rows_.bind(this),
'MPADDED': this.rows_.bind(this),
'MSTYLE': this.rows_.bind(this),
'MFRAC': this.fraction_.bind(this),
'MSUB': this.limits_.bind(this),
'MSUP': this.limits_.bind(this),
'MSUBSUP': this.limits_.bind(this),
'MOVER': this.limits_.bind(this),
'MUNDER': this.limits_.bind(this),
'MUNDEROVER': this.limits_.bind(this),
'MROOT': this.root_.bind(this),
'MSQRT': this.sqrt_.bind(this),
'MTABLE': this.table_.bind(this),
'MLABELEDTR': this.tableLabeledRow_.bind(this),
'MTR': this.tableRow_.bind(this),
'MTD': this.tableCell_.bind(this),
'MS': this.text_.bind(this),
'MTEXT': this.text_.bind(this),
'MSPACE': this.space_.bind(this),
'ANNOTATION-XML': this.text_.bind(this),
'MI': this.identifier_.bind(this),
'MN': this.number_.bind(this),
'MO': this.operator_.bind(this),
'MFENCED': this.fenced_.bind(this),
'MENCLOSE': this.enclosed_.bind(this),
'MMULTISCRIPTS': this.multiscripts_.bind(this),
'ANNOTATION': this.empty_.bind(this),
'NONE': this.empty_.bind(this),
'MACTION': this.action_.bind(this)
};
let meaning = {
type: SemanticType.IDENTIFIER,
role: SemanticRole.NUMBERSET,
font: SemanticFont.DOUBLESTRUCK
};
['C', 'H', 'N', 'P', 'Q', 'R', 'Z', 'ℂ', 'ℍ', 'ℕ', 'ℙ', 'ℚ', 'ℝ', 'ℤ']
.forEach(((x: string) =>
this.getFactory().defaultMap.add(x, meaning)).bind(this));
}
/**
* @override
*/
public parse(mml: Element) {
SemanticProcessor.getInstance().setNodeFactory(this.getFactory());
let children = DomUtil.toArray(mml.childNodes);
let tag = DomUtil.tagName(mml);
let func = this.parseMap_[tag];
let newNode = (func ? func : this.dummy_.bind(this))(mml, children);
SemanticUtil.addAttributes(newNode, mml);
if (['MATH', 'MROW', 'MPADDED', 'MSTYLE', 'SEMANTICS'].indexOf(tag) !==
-1) {
return newNode;
}
newNode.mathml.unshift(mml);
newNode.mathmlTree = mml;
return newNode;
}
/**
* Parses semantics elements.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private semantics_(_node: Element, children: Element[]): SemanticNode {
return children.length ? this.parse(children[0]) :
this.getFactory().makeEmptyNode();
}
/**
* Parses inferred row elements.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private rows_(node: Element, children: Element[]): SemanticNode {
// Special cases:
let semantics = node.getAttribute('semantics');
if (semantics && semantics.match('bspr_')) {
return SemanticProcessor.proof(
node, semantics, this.parseList.bind(this));
}
// End special cases.
children = SemanticUtil.purgeNodes(children);
// Single child node, i.e. the row is meaningless.
let newNode;
if (children.length === 1) {
// TODO: Collate external attributes!
newNode = this.parse(children[0]);
if (newNode.type === SemanticType.EMPTY && !newNode.mathmlTree) {
newNode.mathmlTree = node;
}
} else {
// Case of a 'meaningful' row, even if they are empty.
newNode = SemanticProcessor.getInstance().row(this.parseList(children));
}
newNode.mathml.unshift(node);
return newNode;
}
/**
* Parses fraction like elements.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private fraction_(node: Element, children: Element[]): SemanticNode {
if (!children.length) {
return this.getFactory().makeEmptyNode();
}
let upper = this.parse(children[0]);
let lower = children[1] ? this.parse(children[1]) :
this.getFactory().makeEmptyNode();
let sem = SemanticProcessor.getInstance().fractionLikeNode(
upper, lower, node.getAttribute('linethickness'),
node.getAttribute('bevelled') === 'true');
return sem;
}
/**
* Parses an expression with bounds.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private limits_(node: Element, children: Element[]): SemanticNode {
return SemanticProcessor.getInstance().limitNode(
DomUtil.tagName(node), this.parseList(children));
}
/**
* Parses a general root element.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private root_(node: Element, children: Element[]): SemanticNode {
if (!children[1]) {
return this.sqrt_(node, children);
}
return this.getFactory().makeBranchNode(
SemanticType.ROOT,
[this.parse(children[1]), this.parse(children[0])], []);
}
/**
* Parses a square root element.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private sqrt_(_node: Element, children: Element[]): SemanticNode {
let semNodes = this.parseList(SemanticUtil.purgeNodes(children));
return this.getFactory().makeBranchNode(
SemanticType.SQRT,
[SemanticProcessor.getInstance().row(semNodes)], []);
}
/**
* Parses a table structure.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private table_(node: Element, children: Element[]): SemanticNode {
let semantics = node.getAttribute('semantics');
if (semantics && semantics.match('bspr_')) {
return SemanticProcessor.proof(
node, semantics, this.parseList.bind(this));
}
let newNode = this.getFactory().makeBranchNode(
SemanticType.TABLE, this.parseList(children), []);
newNode.mathmlTree = node;
SemanticProcessor.tableToMultiline(newNode);
return newNode;
}
/**
* Parses a row of a table.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private tableRow_(_node: Element, children: Element[]): SemanticNode {
let newNode = this.getFactory().makeBranchNode(
SemanticType.ROW, this.parseList(children), []);
newNode.role = SemanticRole.TABLE;
return newNode;
}
/**
* Parses a row of a table.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private tableLabeledRow_(node: Element, children: Element[]): SemanticNode {
if (!children.length) {
return this.tableRow_(node, children);
}
let label = this.parse(children[0]);
label.role = SemanticRole.LABEL;
let newNode = this.getFactory().makeBranchNode(
SemanticType.ROW, this.parseList(children.slice(1)), [label]);
newNode.role = SemanticRole.TABLE;
return newNode;
}
/**
* Parses a table cell.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private tableCell_(_node: Element, children: Element[]): SemanticNode {
let semNodes = this.parseList(SemanticUtil.purgeNodes(children));
let childNodes: SemanticNode[];
if (!semNodes.length) {
childNodes = [];
} else if (
semNodes.length === 1 &&
SemanticPred.isType(semNodes[0], SemanticType.EMPTY)) {
// In case we have an explicit empty node, we do not want to process it
// again. However, we know there will be a mathml node to embed the
// semantic information into if necessary.
childNodes = semNodes;
} else {
childNodes = [SemanticProcessor.getInstance().row(semNodes)];
}
let newNode = this.getFactory().makeBranchNode(
SemanticType.CELL, childNodes, []);
newNode.role = SemanticRole.TABLE;
return newNode;
}
/**
* Parse a space element. If sufficiently wide, create an empty text element.
* alpha only: ignore, em pc >= .5, cm >= .4, ex >= 1, in >= .15, pt mm >= 5.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private space_(node: Element, children: Element[]): SemanticNode {
let width = node.getAttribute('width');
let match = width && width.match(/[a-z]*$/);
if (!match) {
return this.empty_(node, children);
}
let sizes: {[key: string]: number} = {
'cm': .4, 'pc': .5, 'em': .5, 'ex': 1, 'in': .15, 'pt': 5, 'mm': 5
};
let unit = match[0];
let measure = parseFloat(width.slice(0, match.index));
let size = sizes[unit];
if (!size || isNaN(measure) || measure < size) {
return this.empty_(node, children);
}
let newNode = this.getFactory().makeUnprocessed(node);
return SemanticProcessor.getInstance().text(newNode, DomUtil.tagName(node));
}
/**
* Parses a text element.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private text_(node: Element, children: Element[]): SemanticNode {
let newNode = this.leaf_(node, children);
if (!node.textContent) {
return newNode;
}
newNode.updateContent(node.textContent, true);
return SemanticProcessor.getInstance().text(newNode, DomUtil.tagName(node));
}
/**
* Create an identifier node, with particular emphasis on font disambiguation.
* @param node A MathML node.
* @param children The children of the node.
* @return The new semantic identifier node.
*/
private identifier_(node: Element, children: Element[]): SemanticNode {
let newNode = this.leaf_(node, children);
return SemanticProcessor.getInstance().identifierNode(
newNode,
SemanticProcessor.getInstance().font(node.getAttribute('mathvariant')),
node.getAttribute('class'));
}
/**
* Parses a number.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private number_(node: Element, children: Element[]): SemanticNode {
let newNode = this.leaf_(node, children);
SemanticProcessor.number(newNode);
return newNode;
}
/**
* Parses an operator.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private operator_(node: Element, children: Element[]): SemanticNode {
let newNode = this.leaf_(node, children);
SemanticProcessor.getInstance().operatorNode(newNode);
return newNode;
}
/**
* Parses a fenced element.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private fenced_(node: Element, children: Element[]): SemanticNode {
let semNodes = this.parseList(SemanticUtil.purgeNodes(children));
let sepValue = SemanticMathml.getAttribute_(node, 'separators', ',');
let open = SemanticMathml.getAttribute_(node, 'open', '(');
let close = SemanticMathml.getAttribute_(node, 'close', ')');
let newNode = SemanticProcessor.getInstance().mfenced(
open, close, sepValue, semNodes);
let nodes = SemanticProcessor.getInstance().tablesInRow([newNode]);
return nodes[0];
}
/**
* Parses an enclosed element.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private enclosed_(node: Element, children: Element[]): SemanticNode {
let semNodes = this.parseList(SemanticUtil.purgeNodes(children));
let newNode = this.getFactory().makeBranchNode(
SemanticType.ENCLOSE,
[SemanticProcessor.getInstance().row(semNodes)], []);
newNode.role = (node.getAttribute('notation') as SemanticRole) ||
SemanticRole.UNKNOWN;
return newNode;
}
/**
* Parses a mmultiscript node into a tensor representation.
* @param node A MathML node.
* @param children The nodes children.
* @return The semantic tensor node.
*/
private multiscripts_(_node: Element, children: Element[]): SemanticNode {
// Empty node. Illegal MathML markup, but valid in MathJax.
if (!children.length) {
return this.getFactory().makeEmptyNode();
}
let base = this.parse((children.shift() as Element));
if (!children.length) {
return base;
}
let lsup = [];
let lsub = [];
let rsup = [];
let rsub = [];
let prescripts = false;
let scriptcount = 0;
for (let i = 0, child; child = children[i]; i++) {
if (DomUtil.tagName(child) === 'MPRESCRIPTS') {
prescripts = true;
scriptcount = 0;
continue;
}
prescripts ?
(scriptcount & 1 ? lsup.push(child) : lsub.push(child)) :
(scriptcount & 1 ? rsup.push(child) : rsub.push(child));
scriptcount++;
}
// This is the pathological msubsup case.
// We retain NONE nodes if necessary, i.e., in a non-empty sub- or
// superscript.
if (!SemanticUtil.purgeNodes(lsup).length &&
!SemanticUtil.purgeNodes(lsub).length) {
return SemanticProcessor.getInstance().pseudoTensor(
base, this.parseList(rsub), this.parseList(rsup));
}
// We really deal with a multiscript tensor.
return SemanticProcessor.getInstance().tensor(
base, this.parseList(lsub), this.parseList(lsup), this.parseList(rsub),
this.parseList(rsup));
}
/**
* Parses an empty element.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private empty_(_node: Element, _children: Element[]): SemanticNode {
return this.getFactory().makeEmptyNode();
}
/**
* Parses an actionable element.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private action_(node: Element, children: Element[]): SemanticNode {
// This here is currently geared towards our collapse actions!
return children.length > 1 ? this.parse(children[1]) :
this.getFactory().makeUnprocessed(node);
}
/**
* Parses a dummy element for which no other case is known.
* @param node A MathML node.
* @param children The children of the node.
* @return The newly created semantic node.
*/
private dummy_(node: Element, _children: Element[]): SemanticNode {
let unknown = this.getFactory().makeUnprocessed(node);
unknown.role = (node.tagName as SemanticRole);
unknown.textContent = node.textContent;
return unknown;
}
/**
* Creates a leaf node from MathML node.
* @param mml The MathML node.
* @param children Its child nodes.
* @return The new node.
*/
private leaf_(mml: Element, children: Element[]): SemanticNode {
if (children.length === 1 &&
children[0].nodeType !== DomUtil.NodeType.TEXT_NODE) {
let node = this.getFactory().makeUnprocessed(mml);
node.role = (children[0].tagName as SemanticRole);
SemanticUtil.addAttributes(node, children[0]);
return node;
}
return this.getFactory().makeLeafNode(
mml.textContent,
SemanticProcessor.getInstance().font(mml.getAttribute('mathvariant')));
}
}
// TODO (sorge) Role and font of multi-character and digits unicode strings.
// TODO (sorge) Reclassify wrongly tagged numbers or identifiers more
// systematically.
// TODO (sorge) Put this all in a single clean reclassification method.
// TODO (sorge) Do something useful with error and phantom symbols. | the_stack |
import Dimensions = Utils.Measurements.Dimensions;
import DisplayObject = etch.drawing.DisplayObject;
import {Device} from '../Device';
import IDisplayContext = etch.drawing.IDisplayContext;
import Size = minerva.Size;
import {IApp} from '../IApp';
declare var App: IApp;
export class SoundcloudPanel extends DisplayObject{
public Open: boolean;
public OffsetX: number;
public OffsetY: number;
private _CopyJson;
public SearchString: string;
private _RollOvers: boolean[];
private _Page:number = 1;
private _ItemNo:number = 5;
private _Blink:number = 0;
private _SelectedBlock: any;
private _RandomWords: string[];
public SearchInputContainer: HTMLElement;
public SearchInput: HTMLInputElement;
Init(drawTo: IDisplayContext): void {
super.Init(drawTo);
this.Open = false;
this.OffsetX = 0;
this.OffsetY = -this.DrawTo.Height;
this._RollOvers = [];
this.SearchString = "Hello";
// DOM ELEMENTS //
this.SearchInputContainer = <HTMLElement>document.getElementById("soundCloudSearch");
this.SearchInput = <HTMLInputElement>document.getElementById("soundCloudSearchInput");
this.SearchInput.addEventListener(
'input',
(event):void => {
this.TestString(this.SearchInput);
this.UpdateString(this.SearchInput);
}
);
this.SearchInput.addEventListener(
'keydown',
(event):void => {
this.EnterCheck(event);
}
);
this._CopyJson = {
titleLine: "Title",
searchLine: "Search SoundCloud",
randomLine: "Randomise",
saving: "saving...",
noResults: "No results found"
};
var colors = ['black','grey','white','red','yellow','pink','green','orange','purple','blue','cream'];
var animals = ['cat','dog','horse','rat','deer','snake','bat','mouse','wolf','hound','fox','bird'];
var places = ['home','house','work','country','county','land','mountain','lake','sea','valley','desert','plains','ocean','space','sky','temple','church','shrine'];
var objects = ['train','car','plane','jet','rocket','satellite','hand','head','back','eyes','legs','mouth','paper','crystal','skull','bones','flag','dust','rock','metal','plant','flower','sun','moon','day','night','gun','blood','gang','sample','drum','clap','echo','sound','song'];
var descriptions = ['wet','dry','hot','cold','good','bad','evil','soft','hard','light','dark','heavy','clean','dirty','short','long','royal','magic','holy'];
this._RandomWords = colors.concat(animals,places,objects,descriptions);
}
//-------------------------------------------------------------------------------------------
// INPUT
//-------------------------------------------------------------------------------------------
// DOES INPUT STRING NEED CHARS REMOVED //
TestString(element: HTMLInputElement) {
var caretPos = element.selectionStart;
if (caretPos > 0) {
caretPos -= 1;
}
// [^A-Za-z0-9_] alpha-numeric
// [][!"#$%&'()*+,./:;<=>?@\^_`{|}~-] punctuation
// [.,\/#!$%\^&\*;:{}=\-_`~()] punctuation 2
if (/[.,\/#\?\"\'$£%\^&\*;:{|}<=>\\@\`\+~()]/.test(element.value)) {
element.value = element.value.replace(/[.,\/#\?\"\'$£%\^&\*;:{|}<=>\\@\`\+~()]/g, '');
element.selectionStart = caretPos;
element.selectionEnd = caretPos;
}
}
// TITLE INPUT HAS CHANGED, USE UPDATED INPUT VALUE //
UpdateString(element: HTMLInputElement) {
var string: string = element.value;
this.SearchString = string;
}
// SET A PROVIDED DOM ELEMENT'S STRING //
UpdateFormText(element: HTMLInputElement, str: string) {
element.value = str;
}
// ENTER PRESSED ON INPUT //
EnterCheck(e: any) {
var key = e.which || e.keyCode;
if (key === 13) {
this.Submit();
}
}
Submit() {
this.SearchInput.blur();
this._SelectedBlock.SearchString = this.SearchString;
this._SelectedBlock.Search(this.SearchString);
this._Page = 1;
this.OffsetX = 0;
this.ClearScroll();
}
/*GetString() {
return this.SearchString;
}
UpdateString(string) {
this.SearchString = string;
}
StringReturn() {
this._SelectedBlock.SearchString = this.SearchString;
this._SelectedBlock.Search(this.SearchString);
this._Page = 1;
this.OffsetX = 0;
}*/
//-------------------------------------------------------------------------------------------
// DRAW
//-------------------------------------------------------------------------------------------
Draw() {
var ctx = this.Ctx;
var midType = App.Metrics.TxtMid;
var headType = App.Metrics.TxtHeader;
var units = App.Unit;
var centerY = this.OffsetY + (App.Height * 0.5);
var appWidth = App.Width;
var appHeight = App.Height;
var margin = (appWidth*0.5) - (210*units);
var pageW = (420*units);
if (this.Open) {
// BG //
App.FillColor(ctx,App.Palette[2]);
ctx.globalAlpha = 0.95;
ctx.fillRect(0,this.OffsetY,appWidth,appHeight);
ctx.globalAlpha = 1;
// RESULTS //
App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]);
App.StrokeColor(ctx,App.Palette[1]);
ctx.lineWidth = 2;
var block = this._SelectedBlock;
var results = block.SearchResults.length;
var itemNo = this._ItemNo;
var pageNo = this._Page;
ctx.font = App.Metrics.TxtItalic;
ctx.textAlign = "left";
// TRACKS //
//clipping path //
ctx.save();
ctx.beginPath();
ctx.moveTo(margin - (5*units), centerY - (100*units));
ctx.lineTo(margin - (5*units), centerY + (130*units));
ctx.lineTo(margin + pageW + (10*units), centerY + (130*units));
ctx.lineTo(margin + pageW + (10*units), centerY - (100*units));
ctx.closePath();
ctx.clip();
// track loop //
for (var i=0; i<results; i++) {
var p = Math.floor(i/itemNo);
var n = i - (p * itemNo);
var x = this.OffsetX + ((pageW + (10*units)) * p);
var y = centerY - (70*units) + ((n*40)*units);
// TODO - try and reduce this some more (if not tweening, just p==(this._Page-1) )
if (p>(this._Page-3) && p<(this._Page+1)) { // range to draw
// divider //
if (n<4 && i<(results-1)) {
ctx.beginPath();
ctx.moveTo(x + margin, y + (12*units));
ctx.lineTo(x + margin + pageW, y + (12*units));
ctx.stroke();
}
// rollover //
if (p==(this._Page-1)) {
if (this._RollOvers[5+n]) {
var sy = centerY - (98*units) + ((40*n)*units);
App.FillColor(ctx,App.Palette[App.ThemeManager.MenuOrder[3]]);
ctx.fillRect(margin - (5*units),sy,pageW + (10*units),40*units);
ctx.beginPath();
ctx.moveTo((appWidth*0.5), sy + (45*units));
ctx.lineTo((appWidth*0.5) - (10*units), sy + (35*units));
ctx.lineTo((appWidth*0.5) + (10*units), sy + (35*units));
ctx.closePath();
ctx.fill();
}
}
// text //
App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]);
var track = block.SearchResults[i];
var title = track.Title;
var user = track.User;
ctx.fillText(title, x + margin + units, y - (10*units));
ctx.fillText("By "+user, x + margin + units, y);
// arrow //
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
ctx.beginPath();
ctx.moveTo(x + margin + pageW - (25 * units), y - (10.5*units));
ctx.lineTo(x + margin + pageW - (20 * units), y - (5.5*units));
ctx.lineTo(x + margin + pageW - (15 * units), y - (10.5*units));
ctx.stroke();
App.StrokeColor(ctx,App.Palette[1]);
}
}
ctx.restore();
ctx.font = App.Metrics.TxtMid;
var maxNo = itemNo*pageNo;
if (maxNo > results) {
maxNo = results;
}
// ITEM NUMBERS //
if (results > 0) {
ctx.fillText("" + (1 + (itemNo * (pageNo - 1))) + " - " + maxNo + " of " + results, margin, centerY + (160 * units));
} else {
//SEARCHING //
if (block.Searching) {
//App.AnimationsLayer.Spin();
App.AnimationsLayer.DrawSprite(ctx,'loading',appWidth*0.5, centerY,16,true);
}
// NO RESULTS //
else {
ctx.font = App.Metrics.TxtHeader;
ctx.textAlign = "center";
ctx.fillText(this._CopyJson.noResults.toLocaleUpperCase(), appWidth*0.5, centerY + (10*units));
}
}
var pageX = margin - (75*units);
var pageY = -68;
var arrowX = 275;
var arrowY = 0;
if (App.Metrics.Device === Device.tablet) {
pageX = margin - (45*units);
arrowX = 245;
}
if (App.Metrics.Device === Device.mobile) {
pageX = appWidth*0.5;
pageY = 170;
arrowX = 60;
arrowY = 160;
}
// PAGE NO //
if (results > itemNo) {
ctx.font = App.Metrics.TxtHeader;
var pNo = ""+this._Page;
var pTotal = ""+Math.ceil(results/itemNo);
ctx.textAlign = "center";
ctx.fillText(pNo + "/" + pTotal, pageX, centerY + (pageY*units));
}
// BACK ARROW //
App.StrokeColor(ctx,App.Palette[1]);
if (this._Page>1) {
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
}
ctx.beginPath();
ctx.moveTo((appWidth*0.5) - (arrowX * units), centerY + ((arrowY-20)*units));
ctx.lineTo((appWidth*0.5) - ((arrowX+20) * units), centerY + ((arrowY)*units));
ctx.lineTo((appWidth*0.5) - (arrowX * units), centerY + ((arrowY+20)*units));
ctx.stroke();
// FORWARD ARROW //
App.StrokeColor(ctx,App.Palette[1]);
if (this._Page < Math.ceil(results/itemNo)) {
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
}
ctx.beginPath();
ctx.moveTo((appWidth*0.5) + (arrowX * units), centerY + ((arrowY-20)*units));
ctx.lineTo((appWidth*0.5) + ((arrowX+20) * units), centerY + ((arrowY)*units));
ctx.lineTo((appWidth*0.5) + (arrowX * units), centerY + ((arrowY+20)*units));
ctx.stroke();
// TITLE //
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
ctx.beginPath();
ctx.moveTo(margin, centerY - (110*units));
ctx.lineTo(margin + pageW, centerY - (110*units));
ctx.stroke();
ctx.textAlign = "left";
/*ctx.font = headType;
ctx.fillText(this.SearchString.toUpperCase(), margin, centerY - (120*units) );
var titleW = ctx.measureText(this.SearchString.toUpperCase()).width;
// TYPE BAR //
if (this._Blink > 50) {
ctx.fillRect(margin + titleW + (5*units),centerY - (143*units),2*units,26*units);
}
this._Blink += 1;
if (this._Blink == 100) {
this._Blink = 0;
}*/
// SEARCH BUTTON //
ctx.font = midType;
var searchW = ctx.measureText(this._CopyJson.searchLine.toUpperCase()).width;
ctx.fillText(this._CopyJson.searchLine.toUpperCase(), (appWidth*0.5) + (205*units) - searchW, centerY - (126*units) );
ctx.beginPath();
ctx.moveTo((appWidth*0.5) + (210*units), centerY - (140*units));
ctx.lineTo((appWidth*0.5) + (200*units) - searchW, centerY - (140*units));
ctx.lineTo((appWidth*0.5) + (200*units) - searchW, centerY - (120*units));
ctx.lineTo((appWidth*0.5) + (210*units), centerY - (120*units));
ctx.closePath();
ctx.stroke();
// RANDOM BUTTON //
searchW = ctx.measureText(this._CopyJson.randomLine.toUpperCase()).width;
ctx.fillText(this._CopyJson.randomLine.toUpperCase(), (appWidth*0.5) + (210*units) - searchW, centerY + (160*units) );
var rx = (appWidth*0.5) + (210*units) - (searchW*0.5);
ctx.beginPath();
ctx.moveTo(rx - (7.5*units), centerY + (165*units));
ctx.lineTo(rx - (2.5*units), centerY + (170*units));
ctx.lineTo(rx + (2.5*units), centerY + (165*units));
ctx.lineTo(rx + (7.5*units), centerY + (170*units));
ctx.stroke();
var clx = 230;
var cly = 150;
if (App.Metrics.Device === Device.mobile) {
clx = 202.5;
cly = 170;
}
// CLOSE BUTTON //
ctx.beginPath();
ctx.moveTo((appWidth*0.5) + ((clx-7.5)*units), centerY - ((cly-7.5)*units));
ctx.lineTo((appWidth*0.5) + ((clx+7.5)*units), centerY - ((cly+7.5)*units));
ctx.moveTo((appWidth*0.5) + ((clx+7.5)*units), centerY - ((cly-7.5)*units));
ctx.lineTo((appWidth*0.5) + ((clx-7.5)*units), centerY - ((cly+7.5)*units));
ctx.stroke();
}
}
WordWrap( context , text, x, y, lineHeight, fitWidth) {
fitWidth = fitWidth || 0;
if (fitWidth <= 0)
{
context.fillText( text, x, y );
return;
}
var words = text.split(' ');
var currentLine = 0;
var idx = 1;
while (words.length > 0 && idx <= words.length)
{
var str = words.slice(0,idx).join(' ');
var w = context.measureText(str).width;
if ( w > fitWidth )
{
if (idx==1)
{
idx=2;
}
context.fillText( words.slice(0,idx-1).join(' '), x, y + (lineHeight*currentLine) );
currentLine++;
words = words.splice(idx-1);
idx = 1;
}
else
{idx++;}
}
if (idx > 0)
context.fillText( words.join(' '), x, y + (lineHeight*currentLine) );
}
//-------------------------------------------------------------------------------------------
// TWEEN
//-------------------------------------------------------------------------------------------
DelayTo(panel,destination,t,delay,v){
var offsetTween = new window.TWEEN.Tween({x: panel[""+v]});
offsetTween.to({x: destination}, t);
offsetTween.onUpdate(function () {
panel[""+v] = this.x;
if (v=="OffsetY") {
panel.TweenDom(panel.SearchInputContainer, this.x, "y", 152, 0);
}
});
offsetTween.onComplete(function() {
if (v=="OffsetY") {
if (destination!==0) {
panel.Open = false;
panel.HideDom();
}
}
});
offsetTween.easing(window.TWEEN.Easing.Exponential.InOut);
offsetTween.delay(delay);
offsetTween.start(this.LastVisualTick);
}
//-------------------------------------------------------------------------------------------
// INTERACTION
//-------------------------------------------------------------------------------------------
OpenPanel() {
this._SelectedBlock = App.MainScene.OptionsPanel.SelectedBlock;
if (!this._SelectedBlock.SearchString) {
this._SelectedBlock.Search(this.RandomSearch(this._SelectedBlock));
}
this._Page = this._SelectedBlock.ResultsPage;
this.SearchString = this._SelectedBlock.SearchString;
this.UpdateFormText(this.SearchInput, this.SearchString);
this.Open = true;
this.OffsetY = -App.Height;
this.OffsetX = - ((this._Page-1) * (430*App.Unit));
this.DelayTo(this,0,500,0,"OffsetY");
this.ShowDom();
//App.TypingManager.Enable(this);
}
ClosePanel() {
this._SelectedBlock.ResultsPage = this._Page;
this.DelayTo(this,-App.Height,500,0,"OffsetY");
//App.TypingManager.Disable();
}
MouseDown(point) {
this.HitTests(point);
var block = this._SelectedBlock;
if (this._RollOvers[1]) { // close
this.ClosePanel();
return;
}
if (this._RollOvers[2]) { // search
this.Submit();
return;
}
if (this._RollOvers[10]) { // random
block.Search(this.RandomSearch(this._SelectedBlock));
//App.TypingManager.Enable(this);
this._Page = 1;
this.OffsetX = 0;
return;
}
if (this._RollOvers[3]) { // back arrow
if (this._Page > 1) {
this._Page -= 1;
this.DelayTo(this,- ((this._Page-1) * (430*App.Unit)),350,0,"OffsetX");
}
return;
}
if (this._RollOvers[4]) { // next arrow
if (this._Page < Math.ceil(block.SearchResults.length/this._ItemNo)) {
this._Page += 1;
this.DelayTo(this,- ((this._Page-1) * (430*App.Unit)),350,0,"OffsetX");
}
return;
}
// LOAD SAMPLE //
for (var i=5; i<10; i++) {
if (this._RollOvers[i]) {
var n = ((this._Page-2)*this._ItemNo)+i;
var track = block.SearchResults[n];
if (track) {
block.LoadTrack(track);
this.ClosePanel();
}
return;
}
}
}
MouseUp(point) {
}
MouseMove(point) {
this.HitTests(point);
}
HitTests(point) {
var units = App.Unit;
var shareX = this.OffsetX + App.Width;
var centerY = this.OffsetY + (App.Height * 0.5);
var ctx = this.Ctx;
var midType = App.Metrics.TxtMid;
var appWidth = App.Width;
ctx.font = midType;
var searchW = ctx.measureText(this._CopyJson.searchLine.toUpperCase()).width;
var randomW = ctx.measureText(this._CopyJson.randomLine.toUpperCase()).width;
var clx = 230;
var cly = 150;
var arrowX = 285;
var arrowY = 0;
if (App.Metrics.Device === Device.tablet) {
arrowX = 255;
}
if (App.Metrics.Device === Device.mobile) {
clx = 202.5;
cly = 170;
arrowX = 70;
arrowY = 160;
}
this._RollOvers[0] = Dimensions.hitRect(shareX + (appWidth*0.5) - (210*units), centerY - (20*units),420*units,40*units, point.x, point.y); // url
this._RollOvers[1] = Dimensions.hitRect((appWidth*0.5) + ((clx-20)*units), centerY - ((cly+20)*units),40*units,40*units, point.x, point.y); // close
this._RollOvers[2] = Dimensions.hitRect((appWidth*0.5) + (200*units) - searchW, centerY - (150*units),searchW + (10*units),40*units, point.x, point.y); // search
this._RollOvers[3] = Dimensions.hitRect((appWidth*0.5) - ((arrowX+15)*units),centerY + (units*(arrowY-20)),30*units,40*units, point.x, point.y); // back
this._RollOvers[4] = Dimensions.hitRect((appWidth*0.5) + ((arrowX-15)*units),centerY + (units*(arrowY-20)),30*units,40*units, point.x, point.y); // next
this._RollOvers[5] = Dimensions.hitRect((appWidth*0.5) - (210*units),centerY - (units*98),420*units,40*units, point.x, point.y); // 1
this._RollOvers[6] = Dimensions.hitRect((appWidth*0.5) - (210*units),centerY - (units*58),420*units,40*units, point.x, point.y); // 2
this._RollOvers[7] = Dimensions.hitRect((appWidth*0.5) - (210*units),centerY - (units*18),420*units,40*units, point.x, point.y); // 3
this._RollOvers[8] = Dimensions.hitRect((appWidth*0.5) - (210*units),centerY + (units*22),420*units,40*units, point.x, point.y); // 4
this._RollOvers[9] = Dimensions.hitRect((appWidth*0.5) - (210*units),centerY + (units*62),420*units,40*units, point.x, point.y); // 5
this._RollOvers[10] = Dimensions.hitRect((appWidth*0.5) + (205*units) - randomW, centerY + (136*units),randomW + (10*units),40*units, point.x, point.y); // random
}
Resize() {
this.OffsetX = - ((this._Page-1) * (430*App.Unit));
this.ClearScroll();
if (this.SearchInput) {
this.StyleDom(this.SearchInputContainer, 300, 42, 210, 152, 0, App.Metrics.TxtHeaderPR);
}
}
RandomSearch(block) {
var words = this._RandomWords;
var q = ""+ words[Math.floor(Math.random()*words.length)] + " " + words[Math.floor(Math.random()*words.length)];
this.SearchString = q;
block.SearchString = q;
this.UpdateFormText(this.SearchInput, q);
return q;
}
//-------------------------------------------------------------------------------------------
// CSS / DOM
//-------------------------------------------------------------------------------------------
TweenDom(element: HTMLElement, value: number, mode: string, position: number, offset: number) {
var units = (App.Unit);
var pr = App.Metrics.PixelRatio;
switch (mode) {
case "x":
element.style.left = "" + ((value + (App.Width*(0.5 + offset)) - (units*position))/pr) + "px";
break;
case "y":
element.style.top = "" + ((value + (App.Height*0.5) - (units*position))/pr) + "px";
break;
}
}
StyleDom(element: HTMLElement, width: number, height: number, x: number, y: number, xOffset: number, font: string) {
var units = (App.Unit);
var pr = App.Metrics.PixelRatio;
element.style.font = font;
element.style.width = "" + (units*(width/pr)) + "px";
element.style.height = "" + (units*(height/pr)) + "px";
element.style.lineHeight = "" + (units*(height/pr)) + "px";
element.style.display = "block";
if (!this.Open) {
this.OffsetY = -App.Height;
element.style.display = "none";
element.style.visibility = "false";
}
var offsetX = xOffset/pr;
var offsetY = this.OffsetY/pr;
var width = App.Width/pr;
var height = App.Height/pr;
element.style.left = "" + (offsetX + (width*0.5) - (units*(x/pr))) + "px";
element.style.top = "" + (offsetY + (height*0.5) - (units*(y/pr))) + "px";
}
ShowDom() {
var search = this.SearchInputContainer;
search.style.display = "block";
search.style.visibility = "true";
}
HideDom() {
var search = this.SearchInputContainer;
search.style.display = "none";
search.style.visibility = "false";
}
ClearScroll() {
window.scrollTo(0,0);
}
} | the_stack |
import { mockAwsS3 } from './mock';
import { handler } from '../index';
import { ImageHandlerError, ImageHandlerEvent, StatusCodes } from '../lib';
describe('index', () => {
// Arrange
process.env.SOURCE_BUCKETS = 'source-bucket';
const mockImage = Buffer.from('SampleImageContent\n');
const mockFallbackImage = Buffer.from('SampleFallbackImageContent\n');
describe('TC: Success', () => {
beforeEach(() => {
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
Body: mockImage,
ContentType: 'image/jpeg'
});
}
}));
});
it('001/should return the image when there is no error', async () => {
// Arrange
const event: ImageHandlerEvent = { path: '/test.jpg' };
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.OK,
isBase64Encoded: true,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Content-Type': 'image/jpeg',
Expires: undefined,
'Cache-Control': 'max-age=31536000,public',
'Last-Modified': undefined
},
body: mockImage.toString('base64')
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
it('002/should return the image with custom headers when custom headers are provided', async () => {
// Arrange
const event: ImageHandlerEvent = {
path: '/eyJidWNrZXQiOiJzb3VyY2UtYnVja2V0Iiwia2V5IjoidGVzdC5qcGciLCJoZWFkZXJzIjp7IkN1c3RvbS1IZWFkZXIiOiJDdXN0b21WYWx1ZSJ9fQ=='
};
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.OK,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Content-Type': 'image/jpeg',
Expires: undefined,
'Cache-Control': 'max-age=31536000,public',
'Last-Modified': undefined,
'Custom-Header': 'CustomValue'
},
body: mockImage.toString('base64'),
isBase64Encoded: true
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
it('003/should return the image when the request is from ALB', async () => {
// Arrange
const event: ImageHandlerEvent = {
path: '/test.jpg',
requestContext: {
elb: {}
}
};
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.OK,
isBase64Encoded: true,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Content-Type': 'image/jpeg',
Expires: undefined,
'Cache-Control': 'max-age=31536000,public',
'Last-Modified': undefined
},
body: mockImage.toString('base64')
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
});
describe('TC: Error', () => {
it('001/should return an error JSON when an error occurs', async () => {
// Arrange
const event: ImageHandlerEvent = { path: '/test.jpg' };
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.NOT_FOUND, 'NoSuchKey', 'NoSuchKey error happened.'));
}
}));
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.NOT_FOUND,
isBase64Encoded: false,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: StatusCodes.NOT_FOUND,
code: 'NoSuchKey',
message: `The image test.jpg does not exist or the request may not be base64 encoded properly.`
})
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
it('002/should return 500 error when there is no error status in the error', async () => {
// Arrange
const event: ImageHandlerEvent = {
path: 'eyJidWNrZXQiOiJzb3VyY2UtYnVja2V0Iiwia2V5IjoidGVzdC5qcGciLCJlZGl0cyI6eyJ3cm9uZ0ZpbHRlciI6dHJ1ZX19'
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
Body: mockImage,
ContentType: 'image/jpeg'
});
}
}));
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
isBase64Encoded: false,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: 'Internal error. Please contact the system administrator.',
code: 'InternalError',
status: StatusCodes.INTERNAL_SERVER_ERROR
})
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
it('003/should return the default fallback image when an error occurs if the default fallback image is enabled', async () => {
// Arrange
process.env.ENABLE_DEFAULT_FALLBACK_IMAGE = 'Yes';
process.env.DEFAULT_FALLBACK_IMAGE_BUCKET = 'fallback-image-bucket';
process.env.DEFAULT_FALLBACK_IMAGE_KEY = 'fallback-image.png';
process.env.CORS_ENABLED = 'Yes';
process.env.CORS_ORIGIN = '*';
const event: ImageHandlerEvent = {
path: '/test.jpg'
};
// Mock
mockAwsS3.getObject.mockReset();
mockAwsS3.getObject
.mockImplementationOnce(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'UnknownError', null));
}
}))
.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
Body: mockFallbackImage,
ContentType: 'image/png'
});
}
}));
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
isBase64Encoded: true,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*',
'Content-Type': 'image/png',
'Cache-Control': 'max-age=31536000,public',
'Last-Modified': undefined
},
body: mockFallbackImage.toString('base64')
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenNthCalledWith(1, { Bucket: 'source-bucket', Key: 'test.jpg' });
expect(mockAwsS3.getObject).toHaveBeenNthCalledWith(2, { Bucket: 'fallback-image-bucket', Key: 'fallback-image.png' });
expect(result).toEqual(expectedResult);
});
it('004/should return an error JSON when getting the default fallback image fails if the default fallback image is enabled', async () => {
// Arrange
const event: ImageHandlerEvent = {
path: '/test.jpg'
};
// Mock
mockAwsS3.getObject.mockReset();
mockAwsS3.getObject.mockImplementation(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.NOT_FOUND, 'NoSuchKey', 'NoSuchKey error happened.'));
}
}));
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.NOT_FOUND,
isBase64Encoded: false,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: StatusCodes.NOT_FOUND,
code: 'NoSuchKey',
message: `The image test.jpg does not exist or the request may not be base64 encoded properly.`
})
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenNthCalledWith(1, { Bucket: 'source-bucket', Key: 'test.jpg' });
expect(mockAwsS3.getObject).toHaveBeenNthCalledWith(2, { Bucket: 'fallback-image-bucket', Key: 'fallback-image.png' });
expect(result).toEqual(expectedResult);
});
it('005/should return an error JSON when the default fallback image key is not provided if the default fallback image is enabled', async () => {
// Arrange
process.env.DEFAULT_FALLBACK_IMAGE_KEY = '';
const event: ImageHandlerEvent = {
path: '/test.jpg'
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.NOT_FOUND, 'NoSuchKey', 'NoSuchKey error happened.'));
}
}));
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.NOT_FOUND,
isBase64Encoded: false,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: StatusCodes.NOT_FOUND,
code: 'NoSuchKey',
message: `The image test.jpg does not exist or the request may not be base64 encoded properly.`
})
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
it('006/should return an error JSON when the default fallback image bucket is not provided if the default fallback image is enabled', async () => {
// Arrange
process.env.DEFAULT_FALLBACK_IMAGE_BUCKET = '';
const event: ImageHandlerEvent = {
path: '/test.jpg'
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.NOT_FOUND, 'NoSuchKey', 'NoSuchKey error happened.'));
}
}));
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.NOT_FOUND,
isBase64Encoded: false,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: StatusCodes.NOT_FOUND,
code: 'NoSuchKey',
message: `The image test.jpg does not exist or the request may not be base64 encoded properly.`
})
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
});
it('007/should return an error JSON when ALB request is failed', async () => {
// Arrange
const event: ImageHandlerEvent = {
path: '/test.jpg',
requestContext: {
elb: {}
}
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.NOT_FOUND, 'NoSuchKey', 'NoSuchKey error happened.'));
}
}));
// Act
const result = await handler(event);
const expectedResult = {
statusCode: StatusCodes.NOT_FOUND,
isBase64Encoded: false,
headers: {
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: StatusCodes.NOT_FOUND,
code: 'NoSuchKey',
message: `The image test.jpg does not exist or the request may not be base64 encoded properly.`
})
};
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'source-bucket', Key: 'test.jpg' });
expect(result).toEqual(expectedResult);
});
}); | the_stack |
module Kiwi.Sound {
/**
* Manages the initialisation of assets necessary when dealing with audio in the game, either through Audio Tags or the Web Audio API.
* Also provides global sound controls that will be applyed to all Audio objects at the same time, within the Game this manager is a part of.
*
* @class AudioManager
* @constructor
* @namespace Kiwi.Sound
* @param game {Kiwi.Game} The game that this audio manager belongs to.
* @return {Kiwi.Sound.AudioManager}
*/
export class AudioManager {
constructor(game: Kiwi.Game) {
this._game = game;
}
/**
* The type of object that this is.
* @method objType
* @return {String} "AudioManager"
* @public
*/
public objType() {
return "AudioManager";
}
/**
* The game that this manager belongs to.
* @property _game
* @type Kiwi.Game
* @private
*/
private _game: Kiwi.Game;
/**
* The global volume of all of the games audio.
* @property _volume
* @type number
* @default 1
* @private
*/
private _volume: number;
/**
* A boolean that controls whether the whole games audio should be muted or not.
* @property _muted
* @type boolean
* @default false
* @private
*/
private _muted: boolean;
/**
* An array containing all of the sounds on the game.
* @property _sounds
* @type Array
* @private
*/
private _sounds: any;
/**
* The number of channels that are supported.
* Not in much use at this point in time.
* @property channels
* @type number
* @public
*/
public channels: number;
/**
* If the current game has audio support or not.
* Useful because audio support is spotty in mobile browsers.
* @property noAudio
* @type boolean
* @public
*/
public noAudio: boolean = false;
/**
* If the game is currently using the Web Audio API for the sound.
* @property usingWebAudio
* @type boolean
* @public
*/
public usingWebAudio: boolean = false;
/**
* If the game is using audio tags for the sound. This is the fallback if the web audio api is not supported.
* @property usingAudioTag
* @type boolean
* @public
*/
public usingAudioTag: boolean = false;
/**
* Web Audio API ONLY - The audio context that is used for decoding audio, e.t.c.
* @property context
* @type any
* @public
*/
public context: any = null;
/**
* Web Audio API ONLY - The master gain node through which all sounds play.
* @property masterGain
* @type any
* @public
*/
public masterGain: any = null;
/**
* The volume of the audio before it was muted. This is used so that when the audio is unmuted the volume will resume at this point.
* @property _muteVolume
* @type number
* @private
*/
private _muteVolume: number;
/**
* Indicates if the sounds is currently 'locked' or not.
* If it is 'locked' then no audio can play until a user touch's the device.
* @property _locked
* @type boolean
* @private
*/
private _locked: boolean;
/**
* Sound buffer
* @property _unlockedSource
* @type {any}
* @private
*/
private _unlockedSource: any = null;
/**
* Returns a boolean indicating whether the device has been touched or not. READ ONLY.
* @property locked
* @type boolean
* @public
*/
public get locked():boolean {
return this._locked;
}
/**
* The boot method is executed when all of the DOM elements needed for the game are loaded and the game is ready to 'start' up.
*
* @method boot
* @public
*/
public boot() {
this._volume = 1;
this._muted = false;
this._sounds = [];
//check to see if it is an iOS device and if it doesn't support webAudio
if (Kiwi.DEVICE.iOS && Kiwi.DEVICE.webaudio == false) {
this.channels = 1;
}
//Add mouse event here to 'unlock' the device.
if (Kiwi.DEVICE.iOS && this._game.deviceTargetOption !== Kiwi.TARGET_COCOON) {
this._locked = true;
this._game.input.onUp.addOnce(this._unlocked, this);
Kiwi.Log.log('Kiwi.AudioManager: Audio is currently Locked until at touch event.', '#audio', '#locked');
} else {
this._locked = false;
}
this.usingWebAudio = true; //we hope for the best....
this.usingAudioTag = false;
if (!!window['AudioContext']) {//if audio context is supported
this.context = new window['AudioContext']();
}
else if (!!window['webkitAudioContext']) {//if webkit audio context is supported
this.context = new window['webkitAudioContext']();
}
else if (!!window['Audio']) {//no awesome audio support...so maybe the audio tags?
this.usingWebAudio = false;
this.usingAudioTag = true;
}
else {//they have no audio support........no sound for you :(
this.usingWebAudio = false;
this.noAudio = true; //prepared for the worst :(
}
if (this.context !== null) {
if (this.context.createGain === undefined) {
this.masterGain = this.context.createGainNode();
} else {
this.masterGain = this.context.createGain();
}
this.masterGain.gain.value = 1;
this.masterGain.connect(this.context.destination);
}
}
/**
* Is executed when a mouse event is fired on the device. This is used to enabled playback of sounds on the current device if they were awaiting for a user event.
* @method _unlocked
* @private
*/
private _unlocked() {
Kiwi.Log.log('Kiwi.AudioManager: Audio now Unlocked.', '#audio', '#unlocked');
if (this.usingAudioTag) {
this._locked = false;
for (var i = 0; i < this._sounds.length; i++) {
this._sounds[i].playable = true;
}
} else {
// Create empty buffer and play it
var buffer = this.context.createBuffer(1, 1, 22050);
this._unlockedSource = this.context.createBufferSource();
this._unlockedSource.buffer = buffer;
this._unlockedSource.connect(this.context.destination);
if (this._unlockedSource.start === undefined) {
this._unlockedSource.noteOn(0);
} else {
this._unlockedSource.start(0);
}
}
}
/**
* Used to mute the audio on the device, or to check to see if the device is muted.
* This will not stop audio from being played, will just mean that the audio is silent.
*
* @property mute
* @type boolean
* @default false
* @public
*/
public set mute(value: boolean) {
if (value === true) {
if (this._muted) return;
this._muted = true;
//mute the sounds
if (this.usingWebAudio) {
this._muteVolume = this.masterGain.gain.value;
this.masterGain.gain.value = 0;
} else if (this.usingAudioTag) {
for (var i = 0; i < this._sounds.length; i++) {
this._sounds[i].mute = true;
}
}
} else {
if (this._muted == false) return;
this._muted = false;
if (this.usingWebAudio) {
this.masterGain.gain.value = this._muteVolume;
} else if (this.usingAudioTag) {
for (var i = 0; i < this._sounds.length; i++) {
this._sounds[i].mute = false;
}
}
}
}
public get mute(): boolean {
return this._muted;
}
/**
* Global setting and getting of the volume.
* A number between 0 (silence) and 1 (full volume).
*
* @property volume
* @type number
* @default 1
* @public
*/
public set volume(value: number) {
if (value !== undefined) {
value = Kiwi.Utils.GameMath.clamp(value, 1, 0);
this._volume = value;
if (this._muted) {
this._muteVolume = this._volume;
}
if (this.usingWebAudio) {
this.masterGain.gain.value = value;
} else if (this.usingAudioTag) {
for (var i = 0; i < this._sounds.length; i++) {
//for each sound tag to update.
this._sounds[i].volume = this._sounds[i].volume;
}
}
}
}
public get volume(): number {
return this._volume;
}
/**
* Indicates whether or not an Audio Object is registered with this Audio Manager or not. For Kiwi Internal use only.
* @method isRegistered
* @param sound {Audio} The Audio object you are checking for.
* @return {Boolean} If the piece of audio is registered or not.
* @public
*/
public isRegistered(sound: Kiwi.Sound.Audio):boolean {
if (this.noAudio) return;
if (this._sounds.indexOf(sound) !== -1) {
return true;
} else {
return false;
}
}
/**
* Registers an Audio Object with this audio manager. Also assign's the audio piece a unique ID to identify it by. Internal Kiwi use only.
* @method registerSound
* @param sound {Audio} The audio piece you are wanting to register.
* @return { Boolean } Indication of if the sound was successfully added or not.
* @public
*/
public registerSound(sound:Kiwi.Sound.Audio):boolean {
if (this.isRegistered(sound) === false) {
sound.id = this._game.rnd.uuid();
this._sounds.push(sound);
return true;
}
return false;
}
/**
* Used to create a new sound on the audio manager. Returns the newly created sound.
*
* @method add
* @param key {string} The key for the audio file that is to be loaded from the AudioLibrary.
* @param [volume=1] {number} The volume for the piece of audio.
* @param [loop=false] {boolean} If the audio should keep repeat when it gets to the end.
* @return {Kiwi.Sound.Audio}
* @public
*/
public add(key: string, volume: number = 1, loop: boolean = false): Kiwi.Sound.Audio {//rename to create
if (this.noAudio) return;
var sound: Kiwi.Sound.Audio = new Kiwi.Sound.Audio(this._game, key, volume, loop);
return sound;
}
/**
* Removes the passed sound from the AudioManager.
* If you remove a Audio Object from the AudioManager, then that Audio Object will not have a update loop.
*
* @method remove
* @param sound {Kiwi.Sound.Audio} The Audio object that you want to remove.
* @param [destory=true] If the Audio Object should be removed or not.
* @public
*/
public remove(sound: Kiwi.Sound.Audio, destroy:boolean=true) {
for (var i = 0; i < this._sounds.length; i++) {
if (sound.id == this._sounds[i].id) {
if (this.usingWebAudio && sound.gainNode) sound.gainNode.disconnect();
if (destroy == true) sound.destroy();
this._sounds.splice(i, 1);
return;
}
}
}
/**
* Plays all of the sounds listed in the AudioManager.
* @method playAll
* @public
*/
public playAll() {
for (var i = 0; i < this._sounds.length; i++) {
if (this._sounds[i]) {
this._sounds[i].play();
}
}
}
/**
* Stops all of the sounds that are listed in the AudioManager from playing.
* @method stopAll
* @public
*/
public stopAll() {
for (var i = 0; i < this._sounds.length; i++) {
if (this._sounds[i]) {
this._sounds[i].stop();
}
}
}
/**
* Pauses all of the sounds listed in the AudioManager.
* @method pauseAll
* @public
*/
public pauseAll() {
for (var i = 0; i < this._sounds.length; i++) {
if (this._sounds[i]) {
this._sounds[i].pause();
}
}
}
/**
* Resumes all of the sounds listed in the AudioManager.
* @method resumeAll
* @public
*/
public resumeAll() {
for (var i = 0; i < this._sounds.length; i++) {
if (this._sounds[i]) {
this._sounds[i].resume();
}
}
}
/**
* The update loop that is executed every frame.
* @method update
* @public
*/
public update() {
if (this._locked) {
if (this.usingWebAudio && this._unlockedSource !== null) {
if ((this._unlockedSource.playbackState === this._unlockedSource.PLAYING_STATE || this._unlockedSource.playbackState === this._unlockedSource.FINISHED_STATE))
{
this._locked = false;
this._unlockedSource = null;
for (var i = 0; i < this._sounds.length; i++) {
this._sounds[i].playable = true;
}
}
}
}
if (!this.noAudio) {
for (var i = 0; i < this._sounds.length; i++) {
this._sounds[i].update();
}
}
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.