text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {BigInt} from 'app/common/BigInt';
import * as MemBuffer from 'app/common/MemBuffer';
import {EventEmitter} from 'events';
import * as util from 'util';
export interface MarshalOptions {
stringToBuffer?: boolean;
version?: number;
}
export interface UnmarshalOptions {
bufferToString?: boolean;
}
function ord(str: string): number {
return str.charCodeAt(0);
}
/**
* Type codes used for python marshalling of values.
* See pypy: rpython/translator/sandbox/_marshal.py.
*/
const marshalCodes = {
NULL : ord('0'),
NONE : ord('N'),
FALSE : ord('F'),
TRUE : ord('T'),
STOPITER : ord('S'),
ELLIPSIS : ord('.'),
INT : ord('i'),
INT64 : ord('I'),
/*
BFLOAT, for 'binary float', is an encoding of float that just encodes the bytes of the
double in standard IEEE 754 float64 format. It is used by Version 2+ of Python's marshal
module. Previously (in versions 0 and 1), the FLOAT encoding is used, which stores floats
through their string representations.
Version 0 (FLOAT) is mandatory for system calls within the sandbox, while Version 2 (BFLOAT)
is recommended for Grist's communication because it is more efficient and faster to
encode/decode
*/
BFLOAT : ord('g'),
FLOAT : ord('f'),
COMPLEX : ord('x'),
LONG : ord('l'),
STRING : ord('s'),
INTERNED : ord('t'),
STRINGREF: ord('R'),
TUPLE : ord('('),
LIST : ord('['),
DICT : ord('{'),
CODE : ord('c'),
UNICODE : ord('u'),
UNKNOWN : ord('?'),
SET : ord('<'),
FROZENSET: ord('>'),
};
type MarshalCode = keyof typeof marshalCodes;
// A little hack to test if the value is a 32-bit integer. Actually, for Python, int might be up
// to 64 bits (if that's the native size), but this is simpler.
// See http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer.
function isInteger(n: number): boolean {
// Float have +0.0 and -0.0. To represent -0.0 precisely, we have to use a float, not an int
// (see also https://stackoverflow.com/questions/7223359/are-0-and-0-the-same).
// tslint:disable-next-line:no-bitwise
return n === +n && n === (n | 0) && !Object.is(n, -0.0);
}
// ----------------------------------------------------------------------
/**
* To force a value to be serialized using a particular representation (e.g. a number as INT64),
* wrap it into marshal.wrap('INT64', value) and serialize that.
*/
export function wrap(codeStr: MarshalCode, value: unknown) {
return new WrappedObj(marshalCodes[codeStr], value);
}
export class WrappedObj {
constructor(public code: number, public value: unknown) {}
public inspect() {
return util.inspect(this.value);
}
}
// ----------------------------------------------------------------------
/**
* @param {Boolean} options.stringToBuffer - If set, JS strings will become Python strings rather
* than unicode objects (as if each JS string is wrapped into MemBuffer.stringToArray(str)).
* This flag becomes a same-named property of Marshaller, which can be set at any time.
* @param {Number} options.version - If version >= 2, uses binary representation for floats. The
* default version 0 formats floats as strings.
*
* TODO: The default should be version 2. (0 was used historically because it was needed for
* communication with PyPy-based sandbox.)
*/
export class Marshaller {
private _memBuf: MemBuffer;
private readonly _floatCode: number;
private readonly _stringCode: number;
constructor(options?: MarshalOptions) {
this._memBuf = new MemBuffer(undefined);
this._floatCode = options && options.version && options.version >= 2 ? marshalCodes.BFLOAT : marshalCodes.FLOAT;
this._stringCode = options && options.stringToBuffer ? marshalCodes.STRING : marshalCodes.UNICODE;
}
public dump(): Uint8Array {
// asByteArray returns a view on the underlying data, and the constructor creates a new copy.
// For some usages, we may want to avoid making the copy.
const bytes = new Uint8Array(this._memBuf.asByteArray());
this._memBuf.clear();
return bytes;
}
public dumpAsBuffer(): Buffer {
const bytes = Buffer.from(this._memBuf.asByteArray());
this._memBuf.clear();
return bytes;
}
public getCode(value: any) {
switch (typeof value) {
case 'number': return isInteger(value) ? marshalCodes.INT : this._floatCode;
case 'string': return this._stringCode;
case 'boolean': return value ? marshalCodes.TRUE : marshalCodes.FALSE;
case 'undefined': return marshalCodes.NONE;
case 'object': {
if (value instanceof WrappedObj) {
return value.code;
} else if (value === null) {
return marshalCodes.NONE;
} else if (value instanceof Uint8Array) {
return marshalCodes.STRING;
} else if (Buffer.isBuffer(value)) {
return marshalCodes.STRING;
} else if (Array.isArray(value)) {
return marshalCodes.LIST;
}
return marshalCodes.DICT;
}
default: {
throw new Error("Marshaller: Unsupported value of type " + (typeof value));
}
}
}
public marshal(value: any): void {
const code = this.getCode(value);
if (value instanceof WrappedObj) {
value = value.value;
}
this._memBuf.writeUint8(code);
switch (code) {
case marshalCodes.NULL: return;
case marshalCodes.NONE: return;
case marshalCodes.FALSE: return;
case marshalCodes.TRUE: return;
case marshalCodes.INT: return this._memBuf.writeInt32LE(value);
case marshalCodes.INT64: return this._writeInt64(value);
case marshalCodes.FLOAT: return this._writeStringFloat(value);
case marshalCodes.BFLOAT: return this._memBuf.writeFloat64LE(value);
case marshalCodes.STRING:
return (value instanceof Uint8Array || Buffer.isBuffer(value) ?
this._writeByteArray(value) :
this._writeUtf8String(value));
case marshalCodes.TUPLE: return this._writeList(value);
case marshalCodes.LIST: return this._writeList(value);
case marshalCodes.DICT: return this._writeDict(value);
case marshalCodes.UNICODE: return this._writeUtf8String(value);
// None of the following are supported.
case marshalCodes.STOPITER:
case marshalCodes.ELLIPSIS:
case marshalCodes.COMPLEX:
case marshalCodes.LONG:
case marshalCodes.INTERNED:
case marshalCodes.STRINGREF:
case marshalCodes.CODE:
case marshalCodes.UNKNOWN:
case marshalCodes.SET:
case marshalCodes.FROZENSET: throw new Error("Marshaller: Can't serialize code " + code);
default: throw new Error("Marshaller: Can't serialize code " + code);
}
}
private _writeInt64(value: number) {
if (!isInteger(value)) {
// TODO We could actually support 53 bits or so.
throw new Error("Marshaller: int64 still only supports 32-bit ints for now: " + value);
}
this._memBuf.writeInt32LE(value);
this._memBuf.writeInt32LE(value >= 0 ? 0 : -1);
}
private _writeStringFloat(value: number) {
// This could be optimized a bit, but it's only used in V0 marshalling, which is only used in
// sandbox system calls, which don't really ever use floats anyway.
const bytes = MemBuffer.stringToArray(value.toString());
if (bytes.byteLength >= 127) {
throw new Error("Marshaller: Trying to write a float that takes " + bytes.byteLength + " bytes");
}
this._memBuf.writeUint8(bytes.byteLength);
this._memBuf.writeByteArray(bytes);
}
private _writeByteArray(value: Uint8Array|Buffer) {
// This works for both Uint8Arrays and Node Buffers.
this._memBuf.writeInt32LE(value.length);
this._memBuf.writeByteArray(value);
}
private _writeUtf8String(value: string) {
const offset = this._memBuf.size();
// We don't know the length until we write the value.
this._memBuf.writeInt32LE(0);
this._memBuf.writeString(value);
const byteLength = this._memBuf.size() - offset - 4;
// Overwrite the 0 length we wrote earlier with the correct byte length.
this._memBuf.asDataView.setInt32(this._memBuf.startPos + offset, byteLength, true);
}
private _writeList(array: unknown[]) {
this._memBuf.writeInt32LE(array.length);
for (const item of array) {
this.marshal(item);
}
}
private _writeDict(obj: {[key: string]: any}) {
const keys = Object.keys(obj);
keys.sort();
for (const key of keys) {
this.marshal(key);
this.marshal(obj[key]);
}
this._memBuf.writeUint8(marshalCodes.NULL);
}
}
// ----------------------------------------------------------------------
const TwoTo32 = 0x100000000; // 2**32
const TwoTo15 = 0x8000; // 2**15
/**
* @param {Boolean} options.bufferToString - If set, Python strings will become JS strings rather
* than Buffers (as if each decoded buffer is wrapped into `buf.toString()`).
* This flag becomes a same-named property of Unmarshaller, which can be set at any time.
* Note that options.version isn't needed, since this will decode both formats.
* TODO: Integers (such as int64 and longs) that are too large for JS are currently represented as
* decimal strings. They may need a better representation, or a configurable option.
*/
export class Unmarshaller extends EventEmitter {
public memBuf: MemBuffer;
private _consumer: any = null;
private _lastCode: number|null = null;
private readonly _bufferToString: boolean;
private _emitter: (v: any) => boolean;
private _stringTable: Array<string|Uint8Array> = [];
constructor(options?: UnmarshalOptions) {
super();
this.memBuf = new MemBuffer(undefined);
this._bufferToString = Boolean(options && options.bufferToString);
this._emitter = this.emit.bind(this, 'value');
}
/**
* Adds more data for parsing. Parsed values will be emitted as 'value' events.
* @param {Uint8Array|Buffer} byteArray: Uint8Array or Node Buffer with bytes to parse.
*/
public push(byteArray: Uint8Array|Buffer) {
this.parse(byteArray, this._emitter);
}
/**
* Adds data to parse, and calls valueCB(value) for each value parsed. If valueCB returns the
* Boolean false, stops parsing and returns.
*/
public parse(byteArray: Uint8Array|Buffer, valueCB: (val: any) => boolean|void) {
this.memBuf.writeByteArray(byteArray);
try {
while (this.memBuf.size() > 0) {
this._consumer = this.memBuf.makeConsumer();
// Have to reset stringTable for interned strings before each top-level parse call.
this._stringTable.length = 0;
const value = this._parse();
this.memBuf.consume(this._consumer);
if (valueCB(value) === false) {
return;
}
}
} catch (err) {
// If the error is `needMoreData`, we silently return. We'll retry by reparsing the message
// from scratch after the next push(). If buffers contain complete serialized messages, the
// cost should be minor. But this design might get very inefficient if we have big messages
// of arrays or dictionaries.
if (err.needMoreData) {
if (!err.consumedData || err.consumedData > 1024) {
// tslint:disable-next-line:no-console
console.log("Unmarshaller: Need more data; wasted parsing of %d bytes", err.consumedData);
}
} else {
err.message = "Unmarshaller: " + err.message;
throw err;
}
}
}
private _parse(): unknown {
const code = this.memBuf.readUint8(this._consumer);
this._lastCode = code;
switch (code) {
case marshalCodes.NULL: return null;
case marshalCodes.NONE: return null;
case marshalCodes.FALSE: return false;
case marshalCodes.TRUE: return true;
case marshalCodes.INT: return this._parseInt();
case marshalCodes.INT64: return this._parseInt64();
case marshalCodes.FLOAT: return this._parseStringFloat();
case marshalCodes.BFLOAT: return this._parseBinaryFloat();
case marshalCodes.STRING: return this._parseByteString();
case marshalCodes.TUPLE: return this._parseList();
case marshalCodes.LIST: return this._parseList();
case marshalCodes.DICT: return this._parseDict();
case marshalCodes.UNICODE: return this._parseUnicode();
case marshalCodes.INTERNED: return this._parseInterned();
case marshalCodes.STRINGREF: return this._parseStringRef();
case marshalCodes.LONG: return this._parseLong();
// None of the following are supported.
// case marshalCodes.STOPITER:
// case marshalCodes.ELLIPSIS:
// case marshalCodes.COMPLEX:
// case marshalCodes.CODE:
// case marshalCodes.UNKNOWN:
// case marshalCodes.SET:
// case marshalCodes.FROZENSET:
default:
throw new Error(`Unmarshaller: unsupported code "${String.fromCharCode(code)}" (${code})`);
}
}
private _parseInt() {
return this.memBuf.readInt32LE(this._consumer);
}
private _parseInt64() {
const low = this.memBuf.readInt32LE(this._consumer);
const hi = this.memBuf.readInt32LE(this._consumer);
if ((hi === 0 && low >= 0) || (hi === -1 && low < 0)) {
return low;
}
const unsignedLow = low < 0 ? TwoTo32 + low : low;
if (hi >= 0) {
return new BigInt(TwoTo32, [unsignedLow, hi], 1).toNative();
} else {
// This part is tricky. See unittests for check of correctness.
return new BigInt(TwoTo32, [TwoTo32 - unsignedLow, -hi - 1], -1).toNative();
}
}
private _parseLong() {
// The format is a 32-bit size whose sign is the sign of the result, followed by 16-bit digits
// in base 2**15.
const size = this.memBuf.readInt32LE(this._consumer);
const sign = size < 0 ? -1 : 1;
const numDigits = size < 0 ? -size : size;
const digits = [];
for (let i = 0; i < numDigits; i++) {
digits.push(this.memBuf.readInt16LE(this._consumer));
}
return new BigInt(TwoTo15, digits, sign).toNative();
}
private _parseStringFloat() {
const len = this.memBuf.readUint8(this._consumer);
const buf = this.memBuf.readString(this._consumer, len);
return parseFloat(buf);
}
private _parseBinaryFloat() {
return this.memBuf.readFloat64LE(this._consumer);
}
private _parseByteString(): string|Uint8Array {
const len = this.memBuf.readInt32LE(this._consumer);
return (this._bufferToString ?
this.memBuf.readString(this._consumer, len) :
this.memBuf.readByteArray(this._consumer, len));
}
private _parseInterned() {
const s = this._parseByteString();
this._stringTable.push(s);
return s;
}
private _parseStringRef() {
const index = this._parseInt();
return this._stringTable[index];
}
private _parseList() {
const len = this.memBuf.readInt32LE(this._consumer);
const value = [];
for (let i = 0; i < len; i++) {
value[i] = this._parse();
}
return value;
}
private _parseDict() {
const dict: {[key: string]: any} = {};
while (true) { // eslint-disable-line no-constant-condition
let key = this._parse() as string|Uint8Array;
if (key === null && this._lastCode === marshalCodes.NULL) {
break;
}
const value = this._parse();
if (key !== null) {
if (key instanceof Uint8Array) {
key = MemBuffer.arrayToString(key);
}
dict[key as string] = value;
}
}
return dict;
}
private _parseUnicode() {
const len = this.memBuf.readInt32LE(this._consumer);
return this.memBuf.readString(this._consumer, len);
}
}
/**
* Similar to python's marshal.loads(). Parses the given bytes and returns the parsed value. There
* must not be any trailing data beyond the single marshalled value.
*/
export function loads(byteArray: Uint8Array|Buffer, options?: UnmarshalOptions): any {
const unmarshaller = new Unmarshaller(options);
let parsedValue;
unmarshaller.parse(byteArray, function(value) {
parsedValue = value;
return false;
});
if (typeof parsedValue === 'undefined') {
throw new Error("loads: input data truncated");
} else if (unmarshaller.memBuf.size() > 0) {
throw new Error("loads: extra bytes past end of input");
}
return parsedValue;
}
/**
* Serializes arbitrary data by first marshalling then converting to a base64 string.
*/
export function dumpBase64(data: any, options?: MarshalOptions) {
const marshaller = new Marshaller(options || {version: 2});
marshaller.marshal(data);
return marshaller.dumpAsBuffer().toString('base64');
}
/**
* Loads data from a base64 string, as serialized by dumpBase64().
*/
export function loadBase64(data: string, options?: UnmarshalOptions) {
return loads(Buffer.from(data, 'base64'), options);
} | the_stack |
import {assert} from 'chai';
import type * as puppeteer from 'puppeteer';
import {$, getBrowserAndPages, step} from '../../shared/helper.js';
import {describe, it} from '../../shared/mocha-extensions.js';
import {CONSOLE_MESSAGE_WRAPPER_SELECTOR, deleteConsoleMessagesFilter, filterConsoleMessages, getConsoleMessages, getCurrentConsoleMessages, showVerboseMessages, toggleShowCorsErrors, waitForConsoleMessagesToBeNonEmpty} from '../helpers/console-helpers.js';
type MessageCheck = (msg: string) => boolean;
function createUrlFilter(url: string) {
return `-url:${url}`;
}
function collectSourceUrlsFromConsoleOutput(frontend: puppeteer.Page) {
return frontend.evaluate(CONSOLE_MESSAGE_WRAPPER_SELECTOR => {
return Array.from(document.querySelectorAll(CONSOLE_MESSAGE_WRAPPER_SELECTOR)).map(wrapper => {
return wrapper.querySelector('.devtools-link').textContent.split(':')[0];
});
}, CONSOLE_MESSAGE_WRAPPER_SELECTOR);
}
function getExpectedMessages(unfilteredMessages: string[], filter: MessageCheck) {
return unfilteredMessages.filter((msg: string) => {
return filter(msg);
});
}
async function testMessageFilter(filter: string, expectedMessageFilter: MessageCheck) {
const {frontend} = getBrowserAndPages();
let unfilteredMessages: string[];
const showMessagesWithAnchor = true;
await step('navigate to console-filter.html and get console messages', async () => {
unfilteredMessages = await getConsoleMessages('console-filter', showMessagesWithAnchor);
});
await step(`filter to only show messages containing '${filter}'`, async () => {
await filterConsoleMessages(frontend, filter);
});
await step('check that messages are correctly filtered', async () => {
const filteredMessages = await getCurrentConsoleMessages(showMessagesWithAnchor);
const expectedMessages = getExpectedMessages(unfilteredMessages, expectedMessageFilter);
assert.isNotEmpty(filteredMessages);
assert.deepEqual(filteredMessages, expectedMessages);
});
}
describe('The Console Tab', async () => {
it('shows logged messages', async () => {
let messages: string[];
const withAnchor = true;
await step('navigate to console-filter.html and get console messages', async () => {
messages = await getConsoleMessages('console-filter', withAnchor);
});
await step('check that all console messages appear', async () => {
assert.deepEqual(messages, [
'console-filter.html:10 1topGroup: log1()',
'log-source.js:6 2topGroup: log2()',
'console-filter.html:10 3topGroup: log1()',
'console-filter.html:17 outerGroup',
'console-filter.html:10 1outerGroup: log1()',
'log-source.js:6 2outerGroup: log2()',
'console-filter.html:21 innerGroup',
'console-filter.html:10 1innerGroup: log1()',
'log-source.js:6 2innerGroup: log2()',
'console-filter.html:30 Hello 1',
'console-filter.html:31 Hello 2',
'console-filter.html:34 end',
]);
});
});
it('shows messages from all levels', async () => {
let messages: string[];
const withAnchor = true;
await step('navigate to console-filter.html and get console messages', async () => {
messages = await getConsoleMessages('console-filter', withAnchor, showVerboseMessages);
});
await step('ensure that all levels are logged', async () => {
const allLevelsDropdown = await $('[aria-label^="Log level: All levels"]');
assert.isNotNull(allLevelsDropdown);
});
await step('check that all console messages appear', async () => {
assert.deepEqual(messages, [
'console-filter.html:10 1topGroup: log1()',
'log-source.js:6 2topGroup: log2()',
'console-filter.html:10 3topGroup: log1()',
'console-filter.html:17 outerGroup',
'console-filter.html:10 1outerGroup: log1()',
'log-source.js:6 2outerGroup: log2()',
'console-filter.html:21 innerGroup',
'console-filter.html:10 1innerGroup: log1()',
'log-source.js:6 2innerGroup: log2()',
'console-filter.html:30 Hello 1',
'console-filter.html:31 Hello 2',
'console-filter.html:33 verbose debug message',
'console-filter.html:34 end',
]);
});
});
it('can exclude messages from a source url', async () => {
const {frontend} = getBrowserAndPages();
let sourceUrls: string[];
let uniqueUrls: Set<string> = new Set();
await step('navigate to console-filter.html and wait for console messages', async () => {
await getConsoleMessages('console-filter');
});
await step('collect source urls from all messages', async () => {
sourceUrls = await collectSourceUrlsFromConsoleOutput(frontend);
});
await step('find unique urls', async () => {
uniqueUrls = new Set(sourceUrls);
assert.isNotEmpty(uniqueUrls);
});
for (const urlToExclude of uniqueUrls) {
const filter = createUrlFilter(urlToExclude);
const expectedMessageFilter: MessageCheck = msg => {
return msg.indexOf(urlToExclude) === -1;
};
await testMessageFilter(filter, expectedMessageFilter);
await step(`remove filter '${filter}'`, async () => {
await deleteConsoleMessagesFilter(frontend);
});
}
});
it('can include messages from a given source url', async () => {
const {frontend} = getBrowserAndPages();
let sourceUrls: string[];
let uniqueUrls: Set<string> = new Set();
await step('navigate to console-filter.html and wait for console messages', async () => {
await getConsoleMessages('console-filter');
});
await step('collect source urls from all messages', async () => {
sourceUrls = await collectSourceUrlsFromConsoleOutput(frontend);
});
await step('find unique urls', async () => {
uniqueUrls = new Set(sourceUrls);
assert.isNotEmpty(uniqueUrls);
});
for (const urlToKeep of uniqueUrls) {
const filter = `url:${urlToKeep}`;
const expectedMessageFilter: MessageCheck = msg => {
return msg.indexOf(urlToKeep) !== -1;
};
await testMessageFilter(filter, expectedMessageFilter);
await step(`remove filter '${filter}'`, async () => {
await deleteConsoleMessagesFilter(frontend);
});
}
});
it('can apply empty filter', async () => {
const filter = '';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const expectedMessageFilter: MessageCheck = _ => true;
await testMessageFilter(filter, expectedMessageFilter);
});
it('can apply text filter', async () => {
const filter = 'outer';
const expectedMessageFilter: MessageCheck = msg => {
// With new implementation of console group filtering, we also include child messages
// if parent group is filtered.
return msg.indexOf(filter) !== -1 || msg.indexOf('inner') !== -1;
};
await testMessageFilter(filter, expectedMessageFilter);
});
it('can apply start/end line regex filter', async () => {
const filter = new RegExp(/.*Hello\s\d$/);
const expectedMessageFilter: MessageCheck = msg => {
return filter.test(msg);
};
await testMessageFilter(filter.toString(), expectedMessageFilter);
});
it('can apply context filter', async () => {
const expectedMessageFilter: MessageCheck = msg => {
return msg.indexOf('Hello') !== -1;
};
await testMessageFilter('context:context', expectedMessageFilter);
});
it('can apply multi text filter', async () => {
const filter = 'Group /[2-3]top/';
const expectedMessageFilter: MessageCheck = msg => {
return /[2-3]top/.test(msg);
};
await testMessageFilter(filter, expectedMessageFilter);
});
it('can apply filter on anchor', async () => {
const filter = new RegExp(/.*log-source\.js:\d+/);
const expectedMessageFilter: MessageCheck = msg => {
return filter.test(msg);
};
await testMessageFilter(filter.toString(), expectedMessageFilter);
});
it('can reset filter', async () => {
const {frontend} = getBrowserAndPages();
let unfilteredMessages: string[];
await step('get unfiltered messages', async () => {
unfilteredMessages = await getConsoleMessages('console-filter');
});
await step('apply message filter', async () => {
await filterConsoleMessages(frontend, 'outer');
});
await step('delete message filter', async () => {
deleteConsoleMessagesFilter(frontend);
});
await step('check if messages are unfiltered', async () => {
const messages = await getCurrentConsoleMessages();
assert.deepEqual(messages, unfilteredMessages);
});
});
it('will show group parent message if child is filtered', async () => {
const filter = '1outerGroup';
const expectedMessageFilter: MessageCheck = msg => {
return new RegExp(/.* (1|)outerGroup.*$/).test(msg);
};
await testMessageFilter(filter, expectedMessageFilter);
});
it('will show messages in group if group name is filtered', async () => {
const filter = 'innerGroup';
const expectedMessageFilter: MessageCheck = msg => {
return msg.indexOf(filter) !== -1 || new RegExp(/.* outerGroup.*$/).test(msg);
};
await testMessageFilter(filter, expectedMessageFilter);
});
it('can exclude CORS error messages', async () => {
const CORS_DETAILED_ERROR_PATTERN =
/Access to fetch at 'https:.*' from origin 'https:.*' has been blocked by CORS policy: .*/;
const NETWORK_ERROR_PATTERN = /GET https:.* net::ERR_FAILED/;
const JS_ERROR_PATTERN = /Uncaught \(in promise\) TypeError: Failed to fetch.*/;
const allMessages = await getConsoleMessages('cors-issue', false, () => waitForConsoleMessagesToBeNonEmpty(6));
allMessages.sort();
assert.strictEqual(allMessages.length, 6);
assert.match(allMessages[0], CORS_DETAILED_ERROR_PATTERN);
assert.match(allMessages[1], CORS_DETAILED_ERROR_PATTERN);
assert.match(allMessages[2], NETWORK_ERROR_PATTERN);
assert.match(allMessages[3], NETWORK_ERROR_PATTERN);
assert.match(allMessages[4], JS_ERROR_PATTERN);
assert.match(allMessages[5], JS_ERROR_PATTERN);
await toggleShowCorsErrors();
const filteredMessages = await getCurrentConsoleMessages();
assert.strictEqual(2, filteredMessages.length);
for (const message of filteredMessages) {
assert.match(message, JS_ERROR_PATTERN);
}
});
}); | the_stack |
import * as ts from 'typescript';
import { inspect } from 'util';
import { TARGET_LANGUAGES, TargetLanguage } from './languages';
import { RecordReferencesVisitor } from './languages/record-references';
import * as logging from './logging';
import { renderTree } from './o-tree';
import { AstRenderer, AstHandler, AstRendererOptions } from './renderer';
import { TypeScriptSnippet, completeSource, SnippetParameters, formatLocation } from './snippet';
import { snippetKey } from './tablets/key';
import { ORIGINAL_SNIPPET_KEY } from './tablets/schema';
import { TranslatedSnippet } from './tablets/tablets';
import { SyntaxKindCounter } from './typescript/syntax-kind-counter';
import { TypeScriptCompiler, CompilationResult } from './typescript/ts-compiler';
import { Spans } from './typescript/visible-spans';
import { annotateStrictDiagnostic, File, hasStrictBranding, mkDict } from './util';
export function translateTypeScript(
source: File,
visitor: AstHandler<any>,
options: SnippetTranslatorOptions = {},
): TranslateResult {
const translator = new SnippetTranslator(
{ visibleSource: source.contents, location: { api: { api: 'file', fileName: source.fileName } } },
options,
);
const translated = translator.renderUsing(visitor);
return {
translation: translated,
diagnostics: translator.diagnostics.map(rosettaDiagFromTypescript),
};
}
/**
* Translate one or more TypeScript snippets into other languages
*
* Can be configured to fully typecheck the samples, or perform only syntactical
* translation.
*/
export class Translator {
private readonly compiler = new TypeScriptCompiler();
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#diagnostics: ts.Diagnostic[] = [];
public constructor(private readonly includeCompilerDiagnostics: boolean) {}
public translate(snip: TypeScriptSnippet, languages: readonly TargetLanguage[] = Object.values(TargetLanguage)) {
logging.debug(`Translating ${snippetKey(snip)} ${inspect(snip.parameters ?? {})}`);
const translator = this.translatorFor(snip);
const translations = mkDict(
languages.map((lang) => {
const languageConverterFactory = TARGET_LANGUAGES[lang];
const translated = translator.renderUsing(languageConverterFactory.createVisitor());
return [lang, { source: translated, version: languageConverterFactory.version }] as const;
}),
);
if (snip.parameters?.infused === undefined) {
this.#diagnostics.push(...translator.diagnostics);
}
return TranslatedSnippet.fromSchema({
translations: {
...translations,
[ORIGINAL_SNIPPET_KEY]: { source: snip.visibleSource, version: '0' },
},
location: snip.location,
didCompile: translator.didSuccessfullyCompile,
fqnsReferenced: translator.fqnsReferenced(),
fullSource: completeSource(snip),
syntaxKindCounter: translator.syntaxKindCounter(),
});
}
public get diagnostics(): readonly RosettaDiagnostic[] {
return ts.sortAndDeduplicateDiagnostics(this.#diagnostics).map(rosettaDiagFromTypescript);
}
/**
* Return the snippet translator for the given snippet
*
* We used to cache these, but each translator holds on to quite a bit of memory,
* so we don't do that anymore.
*/
public translatorFor(snippet: TypeScriptSnippet) {
const translator = new SnippetTranslator(snippet, {
compiler: this.compiler,
includeCompilerDiagnostics: this.includeCompilerDiagnostics,
});
return translator;
}
}
export interface SnippetTranslatorOptions extends AstRendererOptions {
/**
* Re-use the given compiler if given
*/
readonly compiler?: TypeScriptCompiler;
/**
* Include compiler errors in return diagnostics
*
* If false, only translation diagnostics will be returned.
*
* @default false
*/
readonly includeCompilerDiagnostics?: boolean;
}
export interface TranslateResult {
translation: string;
diagnostics: readonly RosettaDiagnostic[];
}
/**
* A translation of a TypeScript diagnostic into a data-only representation for Rosetta
*
* We cannot use the original `ts.Diagnostic` since it holds on to way too much
* state (the source file and by extension the entire parse tree), which grows
* too big to be properly serialized by a worker and also takes too much memory.
*
* Reduce it down to only the information we need.
*/
export interface RosettaDiagnostic {
/**
* If this is an error diagnostic or not
*/
readonly isError: boolean;
/**
* If the diagnostic was emitted from an assembly that has its 'strict' flag set
*/
readonly isFromStrictAssembly: boolean;
/**
* The formatted message, ready to be printed (will have colors and newlines in it)
*
* Ends in a newline.
*/
readonly formattedMessage: string;
}
export function makeRosettaDiagnostic(isError: boolean, formattedMessage: string): RosettaDiagnostic {
return { isError, formattedMessage, isFromStrictAssembly: false };
}
/**
* Translate a single TypeScript snippet
*/
export class SnippetTranslator {
public readonly translateDiagnostics: ts.Diagnostic[] = [];
public readonly compileDiagnostics: ts.Diagnostic[] = [];
private readonly visibleSpans: Spans;
private readonly compilation!: CompilationResult;
private readonly tryCompile: boolean;
public constructor(snippet: TypeScriptSnippet, private readonly options: SnippetTranslatorOptions = {}) {
const compiler = options.compiler ?? new TypeScriptCompiler();
const source = completeSource(snippet);
const fakeCurrentDirectory =
snippet.parameters?.[SnippetParameters.$COMPILATION_DIRECTORY] ??
snippet.parameters?.[SnippetParameters.$PROJECT_DIRECTORY];
this.compilation = compiler.compileInMemory(
removeSlashes(formatLocation(snippet.location)),
source,
fakeCurrentDirectory,
);
// Respect '/// !hide' and '/// !show' directives
this.visibleSpans = Spans.visibleSpansFromSource(source);
// This makes it about 5x slower, so only do it on demand
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
this.tryCompile = (options.includeCompilerDiagnostics || snippet.strict) ?? false;
if (this.tryCompile) {
const program = this.compilation.program;
const diagnostics = [
...neverThrowing(program.getGlobalDiagnostics)(),
...neverThrowing(program.getSyntacticDiagnostics)(this.compilation.rootFile),
...neverThrowing(program.getDeclarationDiagnostics)(this.compilation.rootFile),
...neverThrowing(program.getSemanticDiagnostics)(this.compilation.rootFile),
];
if (snippet.strict) {
// In a strict assembly, so we'll need to brand all diagnostics here...
diagnostics.forEach(annotateStrictDiagnostic);
}
this.compileDiagnostics.push(...diagnostics);
}
/**
* Intercepts all exceptions thrown by the wrapped call, and logs them to
* console.error instead of re-throwing, then returns an empty array. This
* is here to avoid compiler crashes due to broken code examples that cause
* the TypeScript compiler to hit a "Debug Failure".
*/
function neverThrowing<A extends unknown[], R>(call: (...args: A) => readonly R[]): (...args: A) => readonly R[] {
return (...args: A) => {
try {
return call(...args);
} catch (err: any) {
const isExpectedTypescriptError = err.message.includes('Debug Failure');
if (!isExpectedTypescriptError) {
console.error(`Failed to execute ${call.name}: ${err}`);
}
return [];
}
};
}
}
/**
* Returns a boolean if compilation was attempted, and undefined if it was not.
*/
public get didSuccessfullyCompile() {
return this.tryCompile ? this.compileDiagnostics.length === 0 : undefined;
}
public renderUsing(visitor: AstHandler<any>) {
const converter = new AstRenderer(
this.compilation.rootFile,
this.compilation.program.getTypeChecker(),
visitor,
this.options,
);
const converted = converter.convert(this.compilation.rootFile);
this.translateDiagnostics.push(...filterVisibleDiagnostics(converter.diagnostics, this.visibleSpans));
return renderTree(converted, { indentChar: visitor.indentChar, visibleSpans: this.visibleSpans });
}
public syntaxKindCounter(): Record<string, number> {
const kindCounter = new SyntaxKindCounter(this.visibleSpans);
return kindCounter.countKinds(this.compilation.rootFile);
}
public fqnsReferenced() {
const visitor = new RecordReferencesVisitor(this.visibleSpans);
const converter = new AstRenderer(
this.compilation.rootFile,
this.compilation.program.getTypeChecker(),
visitor,
this.options,
);
converter.convert(this.compilation.rootFile);
return visitor.fqnsReferenced();
}
public get diagnostics(): readonly ts.Diagnostic[] {
return ts.sortAndDeduplicateDiagnostics(this.compileDiagnostics.concat(this.translateDiagnostics));
}
}
/**
* Hide diagnostics that are rosetta-sourced if they are reported against a non-visible span
*/
function filterVisibleDiagnostics(diags: readonly ts.Diagnostic[], visibleSpans: Spans): ts.Diagnostic[] {
return diags.filter((d) => d.source !== 'rosetta' || d.start === undefined || visibleSpans.containsPosition(d.start));
}
/**
* Turn TypeScript diagnostics into Rosetta diagnostics
*/
export function rosettaDiagFromTypescript(diag: ts.Diagnostic): RosettaDiagnostic {
return {
isError: diag.category === ts.DiagnosticCategory.Error,
isFromStrictAssembly: hasStrictBranding(diag),
formattedMessage: ts.formatDiagnosticsWithColorAndContext([diag], DIAG_HOST),
};
}
const DIAG_HOST = {
getCurrentDirectory() {
return '.';
},
getCanonicalFileName(fileName: string) {
return fileName;
},
getNewLine() {
return '\n';
},
};
/**
* Remove slashes from a "where" description, as the TS compiler will interpret it as a directory
* and we can't have that for compiling literate files
*/
function removeSlashes(x: string) {
return x.replace(/\/|\\/g, '.');
} | the_stack |
import { WebXRFeaturesManager, WebXRFeatureName } from "../webXRFeaturesManager";
import { WebXRSessionManager } from "../webXRSessionManager";
import { AbstractMesh } from "../../Meshes/abstractMesh";
import { Observer } from "../../Misc/observable";
import { WebXRInput } from "../webXRInput";
import { WebXRInputSource } from "../webXRInputSource";
import { Scene } from "../../scene";
import { WebXRControllerComponent } from "../motionController/webXRControllerComponent";
import { Nullable } from "../../types";
import { Matrix, Vector3 } from "../../Maths/math.vector";
import { Color3 } from "../../Maths/math.color";
import { Axis } from "../../Maths/math.axis";
import { StandardMaterial } from "../../Materials/standardMaterial";
import { CreateCylinder } from "../../Meshes/Builders/cylinderBuilder";
import { CreateTorus } from "../../Meshes/Builders/torusBuilder";
import { Ray } from "../../Culling/ray";
import { PickingInfo } from "../../Collisions/pickingInfo";
import { WebXRAbstractFeature } from "./WebXRAbstractFeature";
import { UtilityLayerRenderer } from "../../Rendering/utilityLayerRenderer";
import { WebXRAbstractMotionController } from "../motionController/webXRAbstractMotionController";
import { WebXRCamera } from "../webXRCamera";
import { Node } from "../../node";
import { Viewport } from "../../Maths/math.viewport";
/**
* Options interface for the pointer selection module
*/
export interface IWebXRControllerPointerSelectionOptions {
/**
* if provided, this scene will be used to render meshes.
*/
customUtilityLayerScene?: Scene;
/**
* Disable the pointer up event when the xr controller in screen and gaze mode is disposed (meaning - when the user removed the finger from the screen)
* If not disabled, the last picked point will be used to execute a pointer up event
* If disabled, pointer up event will be triggered right after the pointer down event.
* Used in screen and gaze target ray mode only
*/
disablePointerUpOnTouchOut: boolean;
/**
* For gaze mode for tracked-pointer / controllers (time to select instead of button press)
*/
forceGazeMode: boolean;
/**
* Factor to be applied to the pointer-moved function in the gaze mode. How sensitive should the gaze mode be when checking if the pointer moved
* to start a new countdown to the pointer down event.
* Defaults to 1.
*/
gazeModePointerMovedFactor?: number;
/**
* Different button type to use instead of the main component
*/
overrideButtonId?: string;
/**
* use this rendering group id for the meshes (optional)
*/
renderingGroupId?: number;
/**
* The amount of time in milliseconds it takes between pick found something to a pointer down event.
* Used in gaze modes. Tracked pointer uses the trigger, screen uses touch events
* 3000 means 3 seconds between pointing at something and selecting it
*/
timeToSelect?: number;
/**
* Should meshes created here be added to a utility layer or the main scene
*/
useUtilityLayer?: boolean;
/**
* Optional WebXR camera to be used for gaze selection
*/
gazeCamera?: WebXRCamera;
/**
* the xr input to use with this pointer selection
*/
xrInput: WebXRInput;
/**
* Should the scene pointerX and pointerY update be disabled
* This is required for fullscreen AR GUI, but might slow down other experiences.
* Disable in VR, if not needed.
* The first rig camera (left eye) will be used to calculate the projection
*/
disableScenePointerVectorUpdate: boolean;
/**
* Enable pointer selection on all controllers instead of switching between them
*/
enablePointerSelectionOnAllControllers?: boolean;
/**
* The preferred hand to give the pointer selection to. This will be prioritized when the controller initialize.
* If switch is enabled, it will still allow the user to switch between the different controllers
*/
preferredHandedness?: XRHandedness;
/**
* Disable switching the pointer selection from one controller to the other.
* If the preferred hand is set it will be fixed on this hand, and if not it will be fixed on the first controller added to the scene
*/
disableSwitchOnClick?: boolean;
/**
* The maximum distance of the pointer selection feature. Defaults to 100.
*/
maxPointerDistance?: number;
}
/**
* A module that will enable pointer selection for motion controllers of XR Input Sources
*/
export class WebXRControllerPointerSelection extends WebXRAbstractFeature {
private static _idCounter = 200;
private _attachController = (xrController: WebXRInputSource) => {
if (this._controllers[xrController.uniqueId]) {
// already attached
return;
}
const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController.pointer);
// get two new meshes
this._controllers[xrController.uniqueId] = {
xrController,
laserPointer,
selectionMesh,
meshUnderPointer: null,
pick: null,
tmpRay: new Ray(new Vector3(), new Vector3()),
disabledByNearInteraction: false,
id: WebXRControllerPointerSelection._idCounter++,
};
if (this._attachedController) {
if (
!this._options.enablePointerSelectionOnAllControllers &&
this._options.preferredHandedness &&
xrController.inputSource.handedness === this._options.preferredHandedness
) {
this._attachedController = xrController.uniqueId;
}
} else {
if (!this._options.enablePointerSelectionOnAllControllers) {
this._attachedController = xrController.uniqueId;
}
}
switch (xrController.inputSource.targetRayMode) {
case "tracked-pointer":
return this._attachTrackedPointerRayMode(xrController);
case "gaze":
return this._attachGazeMode(xrController);
case "screen":
return this._attachScreenRayMode(xrController);
}
};
private _controllers: {
[controllerUniqueId: string]: {
xrController?: WebXRInputSource;
webXRCamera?: WebXRCamera;
selectionComponent?: WebXRControllerComponent;
onButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
onFrameObserver?: Nullable<Observer<XRFrame>>;
laserPointer: AbstractMesh;
selectionMesh: AbstractMesh;
meshUnderPointer: Nullable<AbstractMesh>;
pick: Nullable<PickingInfo>;
id: number;
tmpRay: Ray;
disabledByNearInteraction: boolean;
// event support
eventListeners?: { [event in XREventType]?: (event: XRInputSourceEvent) => void };
};
} = {};
private _scene: Scene;
private _tmpVectorForPickCompare = new Vector3();
private _attachedController: string;
/**
* The module's name
*/
public static readonly Name = WebXRFeatureName.POINTER_SELECTION;
/**
* The (Babylon) version of this module.
* This is an integer representing the implementation version.
* This number does not correspond to the WebXR specs version
*/
public static readonly Version = 1;
/**
* Disable lighting on the laser pointer (so it will always be visible)
*/
public disablePointerLighting: boolean = true;
/**
* Disable lighting on the selection mesh (so it will always be visible)
*/
public disableSelectionMeshLighting: boolean = true;
/**
* Should the laser pointer be displayed
*/
public displayLaserPointer: boolean = true;
/**
* Should the selection mesh be displayed (The ring at the end of the laser pointer)
*/
public displaySelectionMesh: boolean = true;
/**
* This color will be set to the laser pointer when selection is triggered
*/
public laserPointerPickedColor: Color3 = new Color3(0.9, 0.9, 0.9);
/**
* Default color of the laser pointer
*/
public laserPointerDefaultColor: Color3 = new Color3(0.7, 0.7, 0.7);
/**
* default color of the selection ring
*/
public selectionMeshDefaultColor: Color3 = new Color3(0.8, 0.8, 0.8);
/**
* This color will be applied to the selection ring when selection is triggered
*/
public selectionMeshPickedColor: Color3 = new Color3(0.3, 0.3, 1.0);
/**
* Optional filter to be used for ray selection. This predicate shares behavior with
* scene.pointerMovePredicate which takes priority if it is also assigned.
*/
public raySelectionPredicate: (mesh: AbstractMesh) => boolean;
/**
* constructs a new background remover module
* @param _xrSessionManager the session manager for this module
* @param _options read-only options to be used in this module
*/
constructor(_xrSessionManager: WebXRSessionManager, private readonly _options: IWebXRControllerPointerSelectionOptions) {
super(_xrSessionManager);
this._scene = this._xrSessionManager.scene;
}
/**
* attach this feature
* Will usually be called by the features manager
*
* @returns true if successful.
*/
public attach(): boolean {
if (!super.attach()) {
return false;
}
this._options.xrInput.controllers.forEach(this._attachController);
this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
// REMOVE the controller
this._detachController(controller.uniqueId);
});
this._scene.constantlyUpdateMeshUnderPointer = true;
if (this._options.gazeCamera) {
const webXRCamera = this._options.gazeCamera;
const { laserPointer, selectionMesh } = this._generateNewMeshPair(webXRCamera);
this._controllers["camera"] = {
webXRCamera,
laserPointer,
selectionMesh,
meshUnderPointer: null,
pick: null,
tmpRay: new Ray(new Vector3(), new Vector3()),
disabledByNearInteraction: false,
id: WebXRControllerPointerSelection._idCounter++,
};
this._attachGazeMode();
}
return true;
}
/**
* detach this feature.
* Will usually be called by the features manager
*
* @returns true if successful.
*/
public detach(): boolean {
if (!super.detach()) {
return false;
}
Object.keys(this._controllers).forEach((controllerId) => {
this._detachController(controllerId);
});
return true;
}
/**
* Will get the mesh under a specific pointer.
* `scene.meshUnderPointer` will only return one mesh - either left or right.
* @param controllerId the controllerId to check
* @returns The mesh under pointer or null if no mesh is under the pointer
*/
public getMeshUnderPointer(controllerId: string): Nullable<AbstractMesh> {
if (this._controllers[controllerId]) {
return this._controllers[controllerId].meshUnderPointer;
} else {
return null;
}
}
/**
* Get the xr controller that correlates to the pointer id in the pointer event
*
* @param id the pointer id to search for
* @returns the controller that correlates to this id or null if not found
*/
public getXRControllerByPointerId(id: number): Nullable<WebXRInputSource> {
const keys = Object.keys(this._controllers);
for (let i = 0; i < keys.length; ++i) {
if (this._controllers[keys[i]].id === id) {
return this._controllers[keys[i]].xrController || null;
}
}
return null;
}
/** @hidden */
public _getPointerSelectionDisabledByPointerId(id: number): boolean {
const keys = Object.keys(this._controllers);
for (let i = 0; i < keys.length; ++i) {
if (this._controllers[keys[i]].id === id) {
return this._controllers[keys[i]].disabledByNearInteraction;
}
}
return true;
}
/** @hidden */
public _setPointerSelectionDisabledByPointerId(id: number, state: boolean) {
const keys = Object.keys(this._controllers);
for (let i = 0; i < keys.length; ++i) {
if (this._controllers[keys[i]].id === id) {
this._controllers[keys[i]].disabledByNearInteraction = state;
return;
}
}
}
private _identityMatrix = Matrix.Identity();
private _screenCoordinatesRef = Vector3.Zero();
private _viewportRef = new Viewport(0, 0, 0, 0);
protected _onXRFrame(_xrFrame: XRFrame) {
Object.keys(this._controllers).forEach((id) => {
// only do this for the selected pointer
const controllerData = this._controllers[id];
if ((!this._options.enablePointerSelectionOnAllControllers && id !== this._attachedController) || controllerData.disabledByNearInteraction) {
controllerData.selectionMesh.isVisible = false;
controllerData.laserPointer.isVisible = false;
controllerData.pick = null;
return;
}
controllerData.laserPointer.isVisible = this.displayLaserPointer;
let controllerGlobalPosition: Vector3;
// Every frame check collisions/input
if (controllerData.xrController) {
controllerGlobalPosition = controllerData.xrController.pointer.position;
controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay);
} else if (controllerData.webXRCamera) {
controllerGlobalPosition = controllerData.webXRCamera.position;
controllerData.webXRCamera.getForwardRayToRef(controllerData.tmpRay);
} else {
return;
}
if (this._options.maxPointerDistance) {
controllerData.tmpRay.length = this._options.maxPointerDistance;
}
// update pointerX and pointerY of the scene. Only if the flag is set to true!
if (!this._options.disableScenePointerVectorUpdate && controllerGlobalPosition) {
const scene = this._xrSessionManager.scene;
const camera = this._options.xrInput.xrCamera;
if (camera) {
camera.viewport.toGlobalToRef(scene.getEngine().getRenderWidth(), scene.getEngine().getRenderHeight(), this._viewportRef);
Vector3.ProjectToRef(controllerGlobalPosition, this._identityMatrix, scene.getTransformMatrix(), this._viewportRef, this._screenCoordinatesRef);
scene.pointerX = this._screenCoordinatesRef.x;
scene.pointerY = this._screenCoordinatesRef.y;
}
}
let utilityScenePick = null;
if (this._utilityLayerScene) {
utilityScenePick = this._utilityLayerScene.pickWithRay(controllerData.tmpRay, this._utilityLayerScene.pointerMovePredicate || this.raySelectionPredicate);
}
let originalScenePick = this._scene.pickWithRay(controllerData.tmpRay, this._scene.pointerMovePredicate || this.raySelectionPredicate);
if (!utilityScenePick || !utilityScenePick.hit) {
// No hit in utility scene
controllerData.pick = originalScenePick;
} else if (!originalScenePick || !originalScenePick.hit) {
// No hit in original scene
controllerData.pick = utilityScenePick;
} else if (utilityScenePick.distance < originalScenePick.distance) {
// Hit is closer in utility scene
controllerData.pick = utilityScenePick;
} else {
// Hit is closer in original scene
controllerData.pick = originalScenePick;
}
if (controllerData.pick && controllerData.xrController) {
controllerData.pick.aimTransform = controllerData.xrController.pointer;
controllerData.pick.gripTransform = controllerData.xrController.grip || null;
}
const pick = controllerData.pick;
if (pick && pick.pickedPoint && pick.hit) {
// Update laser state
this._updatePointerDistance(controllerData.laserPointer, pick.distance);
// Update cursor state
controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
// To avoid z-fighting
let pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay);
let deltaFighting = 0.001;
controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
if (pickNormal) {
let axis1 = Vector3.Cross(Axis.Y, pickNormal);
let axis2 = Vector3.Cross(pickNormal, axis1);
Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
}
controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;
controllerData.meshUnderPointer = pick.pickedMesh;
} else {
controllerData.selectionMesh.isVisible = false;
this._updatePointerDistance(controllerData.laserPointer, 1);
controllerData.meshUnderPointer = null;
}
});
}
private get _utilityLayerScene() {
return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;
}
private _attachGazeMode(xrController?: WebXRInputSource) {
const controllerData = this._controllers[(xrController && xrController.uniqueId) || "camera"];
// attached when touched, detaches when raised
const timeToSelect = this._options.timeToSelect || 3000;
const sceneToRenderTo = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene;
let oldPick = new PickingInfo();
let discMesh = CreateTorus(
"selection",
{
diameter: 0.0035 * 15,
thickness: 0.0025 * 6,
tessellation: 20,
},
sceneToRenderTo
);
discMesh.isVisible = false;
discMesh.isPickable = false;
discMesh.parent = controllerData.selectionMesh;
let timer = 0;
let downTriggered = false;
const pointerEventInit: PointerEventInit = {
pointerId: controllerData.id,
pointerType: "xr",
};
controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
if (!controllerData.pick) {
return;
}
controllerData.laserPointer.material!.alpha = 0;
discMesh.isVisible = false;
if (controllerData.pick.hit) {
if (!this._pickingMoved(oldPick, controllerData.pick)) {
if (timer > timeToSelect / 10) {
discMesh.isVisible = true;
}
timer += this._scene.getEngine().getDeltaTime();
if (timer >= timeToSelect) {
this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
downTriggered = true;
// pointer up right after down, if disable on touch out
if (this._options.disablePointerUpOnTouchOut) {
this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
}
discMesh.isVisible = false;
} else {
const scaleFactor = 1 - timer / timeToSelect;
discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);
}
} else {
if (downTriggered) {
if (!this._options.disablePointerUpOnTouchOut) {
this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
}
}
downTriggered = false;
timer = 0;
}
} else {
downTriggered = false;
timer = 0;
}
this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
oldPick = controllerData.pick;
});
if (this._options.renderingGroupId !== undefined) {
discMesh.renderingGroupId = this._options.renderingGroupId;
}
if (xrController) {
xrController.onDisposeObservable.addOnce(() => {
if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
}
discMesh.dispose();
});
}
}
private _attachScreenRayMode(xrController: WebXRInputSource) {
const controllerData = this._controllers[xrController.uniqueId];
let downTriggered = false;
const pointerEventInit: PointerEventInit = {
pointerId: controllerData.id,
pointerType: "xr",
};
controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) {
return;
}
if (!downTriggered) {
this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
downTriggered = true;
if (this._options.disablePointerUpOnTouchOut) {
this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
}
} else {
this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
}
});
xrController.onDisposeObservable.addOnce(() => {
if (controllerData.pick && downTriggered && !this._options.disablePointerUpOnTouchOut) {
this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
}
});
}
private _attachTrackedPointerRayMode(xrController: WebXRInputSource) {
const controllerData = this._controllers[xrController.uniqueId];
if (this._options.forceGazeMode) {
return this._attachGazeMode(xrController);
}
const pointerEventInit: PointerEventInit = {
pointerId: controllerData.id,
pointerType: "xr",
};
controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
(<StandardMaterial>controllerData.laserPointer.material).disableLighting = this.disablePointerLighting;
(<StandardMaterial>controllerData.selectionMesh.material).disableLighting = this.disableSelectionMeshLighting;
if (controllerData.pick) {
this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
}
});
if (xrController.inputSource.gamepad) {
const init = (motionController: WebXRAbstractMotionController) => {
if (this._options.overrideButtonId) {
controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId);
}
if (!controllerData.selectionComponent) {
controllerData.selectionComponent = motionController.getMainComponent();
}
controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {
if (component.changes.pressed) {
const pressed = component.changes.pressed.current;
if (controllerData.pick) {
if (this._options.enablePointerSelectionOnAllControllers || xrController.uniqueId === this._attachedController) {
if (pressed) {
this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
(<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
(<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
} else {
this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
(<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
(<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerDefaultColor;
}
} else {
}
} else {
if (pressed && !this._options.enablePointerSelectionOnAllControllers && !this._options.disableSwitchOnClick) {
this._attachedController = xrController.uniqueId;
}
}
}
});
};
if (xrController.motionController) {
init(xrController.motionController);
} else {
xrController.onMotionControllerInitObservable.add(init);
}
} else {
// use the select and squeeze events
const selectStartListener = (event: XRInputSourceEvent) => {
if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {
this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
(<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
(<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
}
};
const selectEndListener = (event: XRInputSourceEvent) => {
if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {
this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
(<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
(<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerDefaultColor;
}
};
controllerData.eventListeners = {
selectend: selectEndListener,
selectstart: selectStartListener,
};
this._xrSessionManager.session.addEventListener("selectstart", selectStartListener);
this._xrSessionManager.session.addEventListener("selectend", selectEndListener);
}
}
private _convertNormalToDirectionOfRay(normal: Nullable<Vector3>, ray: Ray) {
if (normal) {
let angle = Math.acos(Vector3.Dot(normal, ray.direction));
if (angle < Math.PI / 2) {
normal.scaleInPlace(-1);
}
}
return normal;
}
private _detachController(xrControllerUniqueId: string) {
const controllerData = this._controllers[xrControllerUniqueId];
if (!controllerData) {
return;
}
if (controllerData.selectionComponent) {
if (controllerData.onButtonChangedObserver) {
controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
}
}
if (controllerData.onFrameObserver) {
this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
}
if (controllerData.eventListeners) {
Object.keys(controllerData.eventListeners).forEach((eventName: string) => {
const func = controllerData.eventListeners && controllerData.eventListeners[eventName as XREventType];
if (func) {
this._xrSessionManager.session.removeEventListener(eventName as XREventType, func);
}
});
}
this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(() => {
// Fire a pointerup
const pointerEventInit: PointerEventInit = {
pointerId: controllerData.id,
pointerType: "xr",
};
this._scene.simulatePointerUp(new PickingInfo(), pointerEventInit);
controllerData.selectionMesh.dispose();
controllerData.laserPointer.dispose();
// remove from the map
delete this._controllers[xrControllerUniqueId];
if (this._attachedController === xrControllerUniqueId) {
// check for other controllers
const keys = Object.keys(this._controllers);
if (keys.length) {
this._attachedController = keys[0];
} else {
this._attachedController = "";
}
}
});
}
private _generateNewMeshPair(meshParent: Node) {
const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;
const laserPointer = CreateCylinder(
"laserPointer",
{
height: 1,
diameterTop: 0.0002,
diameterBottom: 0.004,
tessellation: 20,
subdivisions: 1,
},
sceneToRenderTo
);
laserPointer.parent = meshParent;
let laserPointerMaterial = new StandardMaterial("laserPointerMat", sceneToRenderTo);
laserPointerMaterial.emissiveColor = this.laserPointerDefaultColor;
laserPointerMaterial.alpha = 0.7;
laserPointer.material = laserPointerMaterial;
laserPointer.rotation.x = Math.PI / 2;
this._updatePointerDistance(laserPointer, 1);
laserPointer.isPickable = false;
// Create a gaze tracker for the XR controller
const selectionMesh = CreateTorus(
"gazeTracker",
{
diameter: 0.0035 * 3,
thickness: 0.0025 * 3,
tessellation: 20,
},
sceneToRenderTo
);
selectionMesh.bakeCurrentTransformIntoVertices();
selectionMesh.isPickable = false;
selectionMesh.isVisible = false;
let targetMat = new StandardMaterial("targetMat", sceneToRenderTo);
targetMat.specularColor = Color3.Black();
targetMat.emissiveColor = this.selectionMeshDefaultColor;
targetMat.backFaceCulling = false;
selectionMesh.material = targetMat;
if (this._options.renderingGroupId !== undefined) {
laserPointer.renderingGroupId = this._options.renderingGroupId;
selectionMesh.renderingGroupId = this._options.renderingGroupId;
}
return {
laserPointer,
selectionMesh,
};
}
private _pickingMoved(oldPick: PickingInfo, newPick: PickingInfo) {
if (!oldPick.hit || !newPick.hit) {
return true;
}
if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) {
return true;
}
if (oldPick.pickedMesh !== newPick.pickedMesh) {
return true;
}
oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 * newPick.distance;
const length = this._tmpVectorForPickCompare.length();
if (length > delta) {
return true;
}
return false;
}
private _updatePointerDistance(_laserPointer: AbstractMesh, distance: number = 100) {
_laserPointer.scaling.y = distance;
// a bit of distance from the controller
if (this._scene.useRightHandedSystem) {
distance *= -1;
}
_laserPointer.position.z = distance / 2 + 0.05;
}
/** @hidden */
public get lasterPointerDefaultColor(): Color3 {
// here due to a typo
return this.laserPointerDefaultColor;
}
}
//register the plugin
WebXRFeaturesManager.AddWebXRFeature(
WebXRControllerPointerSelection.Name,
(xrSessionManager, options) => {
return () => new WebXRControllerPointerSelection(xrSessionManager, options);
},
WebXRControllerPointerSelection.Version,
true
); | the_stack |
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>You do not have sufficient access to perform this action.</p>
*/
export interface AccessDeniedException extends __SmithyException, $MetadataBearer {
name: "AccessDeniedException";
$fault: "client";
Message?: string;
}
export namespace AccessDeniedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AccessDeniedException): any => ({
...obj,
});
}
/**
* <p>The name of the data and how often it should be pulled from the source.</p>
*/
export interface ScheduleConfiguration {
/**
* <p>The start date for objects to import in the first flow run.</p>
*/
FirstExecutionFrom?: string;
/**
* <p>The name of the object to pull from the data source.</p>
*/
Object?: string;
/**
* <p>How often the data should be pulled from data source.</p>
*/
ScheduleExpression?: string;
}
export namespace ScheduleConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ScheduleConfiguration): any => ({
...obj,
});
}
export interface CreateDataIntegrationRequest {
/**
* <p>The name of the DataIntegration.</p>
*/
Name: string | undefined;
/**
* <p>A description of the DataIntegration.</p>
*/
Description?: string;
/**
* <p>The KMS key for the DataIntegration.</p>
*/
KmsKey?: string;
/**
* <p>The URI of the data source.</p>
*/
SourceURI?: string;
/**
* <p>The name of the data and how often it should be pulled from the source.</p>
*/
ScheduleConfig?: ScheduleConfiguration;
/**
* <p>One or more tags.</p>
*/
Tags?: { [key: string]: string };
/**
* <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the
* request.</p>
*/
ClientToken?: string;
}
export namespace CreateDataIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateDataIntegrationRequest): any => ({
...obj,
});
}
export interface CreateDataIntegrationResponse {
/**
* <p>The Amazon Resource Name (ARN)</p>
*/
Arn?: string;
/**
* <p>A unique identifier.</p>
*/
Id?: string;
/**
* <p>The name of the DataIntegration.</p>
*/
Name?: string;
/**
* <p>A description of the DataIntegration.</p>
*/
Description?: string;
/**
* <p>The KMS key for the DataIntegration.</p>
*/
KmsKey?: string;
/**
* <p>The URI of the data source.</p>
*/
SourceURI?: string;
/**
* <p>The name of the data and how often it should be pulled from the source.</p>
*/
ScheduleConfiguration?: ScheduleConfiguration;
/**
* <p>One or more tags.</p>
*/
Tags?: { [key: string]: string };
/**
* <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the
* request.</p>
*/
ClientToken?: string;
}
export namespace CreateDataIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateDataIntegrationResponse): any => ({
...obj,
});
}
/**
* <p>A resource with the specified name already exists.</p>
*/
export interface DuplicateResourceException extends __SmithyException, $MetadataBearer {
name: "DuplicateResourceException";
$fault: "client";
Message?: string;
}
export namespace DuplicateResourceException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DuplicateResourceException): any => ({
...obj,
});
}
/**
* <p>Request processing failed due to an error or failure with the service.</p>
*/
export interface InternalServiceError extends __SmithyException, $MetadataBearer {
name: "InternalServiceError";
$fault: "server";
Message?: string;
}
export namespace InternalServiceError {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalServiceError): any => ({
...obj,
});
}
/**
* <p>The request is not valid. </p>
*/
export interface InvalidRequestException extends __SmithyException, $MetadataBearer {
name: "InvalidRequestException";
$fault: "client";
Message?: string;
}
export namespace InvalidRequestException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidRequestException): any => ({
...obj,
});
}
/**
* <p>The allowed quota for the resource has been exceeded.</p>
*/
export interface ResourceQuotaExceededException extends __SmithyException, $MetadataBearer {
name: "ResourceQuotaExceededException";
$fault: "client";
Message?: string;
}
export namespace ResourceQuotaExceededException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceQuotaExceededException): any => ({
...obj,
});
}
/**
* <p>The throttling limit has been exceeded.</p>
*/
export interface ThrottlingException extends __SmithyException, $MetadataBearer {
name: "ThrottlingException";
$fault: "client";
Message?: string;
}
export namespace ThrottlingException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ThrottlingException): any => ({
...obj,
});
}
/**
* <p>The event filter.</p>
*/
export interface EventFilter {
/**
* <p>The source of the events.</p>
*/
Source: string | undefined;
}
export namespace EventFilter {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EventFilter): any => ({
...obj,
});
}
export interface CreateEventIntegrationRequest {
/**
* <p>The name of the event integration.</p>
*/
Name: string | undefined;
/**
* <p>The description of the event integration.</p>
*/
Description?: string;
/**
* <p>The event filter.</p>
*/
EventFilter: EventFilter | undefined;
/**
* <p>The EventBridge bus.</p>
*/
EventBridgeBus: string | undefined;
/**
* <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the
* request.</p>
*/
ClientToken?: string;
/**
* <p>One or more tags.</p>
*/
Tags?: { [key: string]: string };
}
export namespace CreateEventIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateEventIntegrationRequest): any => ({
...obj,
});
}
export interface CreateEventIntegrationResponse {
/**
* <p>The Amazon Resource Name (ARN) of the event integration. </p>
*/
EventIntegrationArn?: string;
}
export namespace CreateEventIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateEventIntegrationResponse): any => ({
...obj,
});
}
export interface DeleteDataIntegrationRequest {
/**
* <p>A unique identifier for the DataIntegration.</p>
*/
DataIntegrationIdentifier: string | undefined;
}
export namespace DeleteDataIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteDataIntegrationRequest): any => ({
...obj,
});
}
export interface DeleteDataIntegrationResponse {}
export namespace DeleteDataIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteDataIntegrationResponse): any => ({
...obj,
});
}
/**
* <p>The specified resource was not found.</p>
*/
export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer {
name: "ResourceNotFoundException";
$fault: "client";
Message?: string;
}
export namespace ResourceNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({
...obj,
});
}
export interface DeleteEventIntegrationRequest {
/**
* <p>The name of the event integration.</p>
*/
Name: string | undefined;
}
export namespace DeleteEventIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteEventIntegrationRequest): any => ({
...obj,
});
}
export interface DeleteEventIntegrationResponse {}
export namespace DeleteEventIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteEventIntegrationResponse): any => ({
...obj,
});
}
export interface GetDataIntegrationRequest {
/**
* <p>A unique identifier.</p>
*/
Identifier: string | undefined;
}
export namespace GetDataIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetDataIntegrationRequest): any => ({
...obj,
});
}
export interface GetDataIntegrationResponse {
/**
* <p>The Amazon Resource Name (ARN) for the DataIntegration.</p>
*/
Arn?: string;
/**
* <p>A unique identifier.</p>
*/
Id?: string;
/**
* <p>The name of the DataIntegration.</p>
*/
Name?: string;
/**
* <p>The KMS key for the DataIntegration.</p>
*/
Description?: string;
/**
* <p>The KMS key for the DataIntegration.</p>
*/
KmsKey?: string;
/**
* <p>The URI of the data source.</p>
*/
SourceURI?: string;
/**
* <p>The name of the data and how often it should be pulled from the source.</p>
*/
ScheduleConfiguration?: ScheduleConfiguration;
/**
* <p>One or more tags.</p>
*/
Tags?: { [key: string]: string };
}
export namespace GetDataIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetDataIntegrationResponse): any => ({
...obj,
});
}
export interface GetEventIntegrationRequest {
/**
* <p>The name of the event integration. </p>
*/
Name: string | undefined;
}
export namespace GetEventIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetEventIntegrationRequest): any => ({
...obj,
});
}
export interface GetEventIntegrationResponse {
/**
* <p>The name of the event integration. </p>
*/
Name?: string;
/**
* <p>The description of the event integration.</p>
*/
Description?: string;
/**
* <p>The Amazon Resource Name (ARN) for the event integration.</p>
*/
EventIntegrationArn?: string;
/**
* <p>The EventBridge bus.</p>
*/
EventBridgeBus?: string;
/**
* <p>The event filter.</p>
*/
EventFilter?: EventFilter;
/**
* <p>One or more tags.</p>
*/
Tags?: { [key: string]: string };
}
export namespace GetEventIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetEventIntegrationResponse): any => ({
...obj,
});
}
export interface ListDataIntegrationAssociationsRequest {
/**
* <p>A unique identifier for the DataIntegration.</p>
*/
DataIntegrationIdentifier: string | undefined;
/**
* <p>The token for the next set of results. Use the value returned in the previous
* response in the next request to retrieve the next set of results.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of results to return per page.</p>
*/
MaxResults?: number;
}
export namespace ListDataIntegrationAssociationsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDataIntegrationAssociationsRequest): any => ({
...obj,
});
}
/**
* <p>Summary information about the DataIntegration association.</p>
*/
export interface DataIntegrationAssociationSummary {
/**
* <p>The Amazon Resource Name (ARN) of the DataIntegration association.</p>
*/
DataIntegrationAssociationArn?: string;
/**
* <p>The Amazon Resource Name (ARN)of the DataIntegration.</p>
*/
DataIntegrationArn?: string;
/**
* <p>The identifier for teh client that is associated with the DataIntegration
* association.</p>
*/
ClientId?: string;
}
export namespace DataIntegrationAssociationSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DataIntegrationAssociationSummary): any => ({
...obj,
});
}
export interface ListDataIntegrationAssociationsResponse {
/**
* <p>The Amazon Resource Name (ARN) and unique ID of the DataIntegration association.</p>
*/
DataIntegrationAssociations?: DataIntegrationAssociationSummary[];
/**
* <p>If there are additional results, this is the token for the next set of results.</p>
*/
NextToken?: string;
}
export namespace ListDataIntegrationAssociationsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDataIntegrationAssociationsResponse): any => ({
...obj,
});
}
export interface ListDataIntegrationsRequest {
/**
* <p>The token for the next set of results. Use the value returned in the previous
* response in the next request to retrieve the next set of results.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of results to return per page.</p>
*/
MaxResults?: number;
}
export namespace ListDataIntegrationsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDataIntegrationsRequest): any => ({
...obj,
});
}
/**
* <p>Summary information about the DataIntegration.</p>
*/
export interface DataIntegrationSummary {
/**
* <p>The Amazon Resource Name (ARN) of the DataIntegration.</p>
*/
Arn?: string;
/**
* <p>The name of the DataIntegration.</p>
*/
Name?: string;
/**
* <p>The URI of the data source.</p>
*/
SourceURI?: string;
}
export namespace DataIntegrationSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DataIntegrationSummary): any => ({
...obj,
});
}
export interface ListDataIntegrationsResponse {
/**
* <p>The DataIntegrations associated with this account.</p>
*/
DataIntegrations?: DataIntegrationSummary[];
/**
* <p>If there are additional results, this is the token for the next set of results.</p>
*/
NextToken?: string;
}
export namespace ListDataIntegrationsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDataIntegrationsResponse): any => ({
...obj,
});
}
export interface ListEventIntegrationAssociationsRequest {
/**
* <p>The name of the event integration. </p>
*/
EventIntegrationName: string | undefined;
/**
* <p>The token for the next set of results. Use the value returned in the previous
* response in the next request to retrieve the next set of results.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of results to return per page.</p>
*/
MaxResults?: number;
}
export namespace ListEventIntegrationAssociationsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListEventIntegrationAssociationsRequest): any => ({
...obj,
});
}
/**
* <p>The event integration association.</p>
*/
export interface EventIntegrationAssociation {
/**
* <p>The Amazon Resource Name (ARN) for the event integration association.</p>
*/
EventIntegrationAssociationArn?: string;
/**
* <p>The identifier for the event integration association.</p>
*/
EventIntegrationAssociationId?: string;
/**
* <p>The name of the event integration.</p>
*/
EventIntegrationName?: string;
/**
* <p>The identifier for the client that is associated with the event integration.</p>
*/
ClientId?: string;
/**
* <p>The name of the EventBridge rule.</p>
*/
EventBridgeRuleName?: string;
/**
* <p>The metadata associated with the client.</p>
*/
ClientAssociationMetadata?: { [key: string]: string };
}
export namespace EventIntegrationAssociation {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EventIntegrationAssociation): any => ({
...obj,
});
}
export interface ListEventIntegrationAssociationsResponse {
/**
* <p>The event integration associations.</p>
*/
EventIntegrationAssociations?: EventIntegrationAssociation[];
/**
* <p>If there are additional results, this is the token for the next set of results.</p>
*/
NextToken?: string;
}
export namespace ListEventIntegrationAssociationsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListEventIntegrationAssociationsResponse): any => ({
...obj,
});
}
export interface ListEventIntegrationsRequest {
/**
* <p>The token for the next set of results. Use the value returned in the previous
* response in the next request to retrieve the next set of results.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of results to return per page.</p>
*/
MaxResults?: number;
}
export namespace ListEventIntegrationsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListEventIntegrationsRequest): any => ({
...obj,
});
}
/**
* <p>The event integration.</p>
*/
export interface EventIntegration {
/**
* <p>The Amazon Resource Name (ARN) of the event integration.</p>
*/
EventIntegrationArn?: string;
/**
* <p>The name of the event integration.</p>
*/
Name?: string;
/**
* <p>The event integration description.</p>
*/
Description?: string;
/**
* <p>The event integration filter.</p>
*/
EventFilter?: EventFilter;
/**
* <p>The Amazon EventBridge bus for the event integration.</p>
*/
EventBridgeBus?: string;
/**
* <p>The tags.</p>
*/
Tags?: { [key: string]: string };
}
export namespace EventIntegration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EventIntegration): any => ({
...obj,
});
}
export interface ListEventIntegrationsResponse {
/**
* <p>The event integrations.</p>
*/
EventIntegrations?: EventIntegration[];
/**
* <p>If there are additional results, this is the token for the next set of results.</p>
*/
NextToken?: string;
}
export namespace ListEventIntegrationsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListEventIntegrationsResponse): any => ({
...obj,
});
}
export interface ListTagsForResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource. </p>
*/
resourceArn: string | undefined;
}
export namespace ListTagsForResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({
...obj,
});
}
export interface ListTagsForResourceResponse {
/**
* <p>Information about the tags.</p>
*/
tags?: { [key: string]: string };
}
export namespace ListTagsForResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({
...obj,
});
}
export interface TagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource.</p>
*/
resourceArn: string | undefined;
/**
* <p>One or more tags. </p>
*/
tags: { [key: string]: string } | undefined;
}
export namespace TagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceRequest): any => ({
...obj,
});
}
export interface TagResourceResponse {}
export namespace TagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceResponse): any => ({
...obj,
});
}
export interface UntagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource.</p>
*/
resourceArn: string | undefined;
/**
* <p>The tag keys.</p>
*/
tagKeys: string[] | undefined;
}
export namespace UntagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({
...obj,
});
}
export interface UntagResourceResponse {}
export namespace UntagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({
...obj,
});
}
export interface UpdateDataIntegrationRequest {
/**
* <p>A unique identifier for the DataIntegration.</p>
*/
Identifier: string | undefined;
/**
* <p>The name of the DataIntegration.</p>
*/
Name?: string;
/**
* <p>A description of the DataIntegration.</p>
*/
Description?: string;
}
export namespace UpdateDataIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateDataIntegrationRequest): any => ({
...obj,
});
}
export interface UpdateDataIntegrationResponse {}
export namespace UpdateDataIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateDataIntegrationResponse): any => ({
...obj,
});
}
export interface UpdateEventIntegrationRequest {
/**
* <p>The name of the event integration.</p>
*/
Name: string | undefined;
/**
* <p>The description of the event inegration.</p>
*/
Description?: string;
}
export namespace UpdateEventIntegrationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateEventIntegrationRequest): any => ({
...obj,
});
}
export interface UpdateEventIntegrationResponse {}
export namespace UpdateEventIntegrationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateEventIntegrationResponse): any => ({
...obj,
});
} | the_stack |
import { Buffer } from '@stacks/common';
import { cloneDeep } from './utils';
import {
ClarityValue,
uintCV,
intCV,
contractPrincipalCV,
standardPrincipalCV,
noneCV,
bufferCV,
falseCV,
trueCV,
ClarityType,
getCVTypeString,
bufferCVFromString,
} from './clarity';
import { ContractCallPayload } from './payload';
import { NotImplementedError } from './errors';
import { stringAsciiCV, stringUtf8CV } from './clarity/types/stringCV';
// From https://github.com/blockstack/stacks-blockchain-sidecar/blob/master/src/event-stream/contract-abi.ts
export type ClarityAbiTypeBuffer = { buffer: { length: number } };
export type ClarityAbiTypeStringAscii = { 'string-ascii': { length: number } };
export type ClarityAbiTypeStringUtf8 = { 'string-utf8': { length: number } };
export type ClarityAbiTypeResponse = { response: { ok: ClarityAbiType; error: ClarityAbiType } };
export type ClarityAbiTypeOptional = { optional: ClarityAbiType };
export type ClarityAbiTypeTuple = { tuple: { name: string; type: ClarityAbiType }[] };
export type ClarityAbiTypeList = { list: { type: ClarityAbiType; length: number } };
export type ClarityAbiTypeUInt128 = 'uint128';
export type ClarityAbiTypeInt128 = 'int128';
export type ClarityAbiTypeBool = 'bool';
export type ClarityAbiTypePrincipal = 'principal';
export type ClarityAbiTypeTraitReference = 'trait_reference';
export type ClarityAbiTypeNone = 'none';
export type ClarityAbiTypePrimitive =
| ClarityAbiTypeUInt128
| ClarityAbiTypeInt128
| ClarityAbiTypeBool
| ClarityAbiTypePrincipal
| ClarityAbiTypeTraitReference
| ClarityAbiTypeNone;
export type ClarityAbiType =
| ClarityAbiTypePrimitive
| ClarityAbiTypeBuffer
| ClarityAbiTypeResponse
| ClarityAbiTypeOptional
| ClarityAbiTypeTuple
| ClarityAbiTypeList
| ClarityAbiTypeStringAscii
| ClarityAbiTypeStringUtf8
| ClarityAbiTypeTraitReference;
export enum ClarityAbiTypeId {
ClarityAbiTypeUInt128 = 1,
ClarityAbiTypeInt128 = 2,
ClarityAbiTypeBool = 3,
ClarityAbiTypePrincipal = 4,
ClarityAbiTypeNone = 5,
ClarityAbiTypeBuffer = 6,
ClarityAbiTypeResponse = 7,
ClarityAbiTypeOptional = 8,
ClarityAbiTypeTuple = 9,
ClarityAbiTypeList = 10,
ClarityAbiTypeStringAscii = 11,
ClarityAbiTypeStringUtf8 = 12,
ClarityAbiTypeTraitReference = 13,
}
export const isClarityAbiPrimitive = (val: ClarityAbiType): val is ClarityAbiTypePrimitive =>
typeof val === 'string';
export const isClarityAbiBuffer = (val: ClarityAbiType): val is ClarityAbiTypeBuffer =>
(val as ClarityAbiTypeBuffer).buffer !== undefined;
export const isClarityAbiStringAscii = (val: ClarityAbiType): val is ClarityAbiTypeStringAscii =>
(val as ClarityAbiTypeStringAscii)['string-ascii'] !== undefined;
export const isClarityAbiStringUtf8 = (val: ClarityAbiType): val is ClarityAbiTypeStringUtf8 =>
(val as ClarityAbiTypeStringUtf8)['string-utf8'] !== undefined;
export const isClarityAbiResponse = (val: ClarityAbiType): val is ClarityAbiTypeResponse =>
(val as ClarityAbiTypeResponse).response !== undefined;
export const isClarityAbiOptional = (val: ClarityAbiType): val is ClarityAbiTypeOptional =>
(val as ClarityAbiTypeOptional).optional !== undefined;
export const isClarityAbiTuple = (val: ClarityAbiType): val is ClarityAbiTypeTuple =>
(val as ClarityAbiTypeTuple).tuple !== undefined;
export const isClarityAbiList = (val: ClarityAbiType): val is ClarityAbiTypeList =>
(val as ClarityAbiTypeList).list !== undefined;
export type ClarityAbiTypeUnion =
| { id: ClarityAbiTypeId.ClarityAbiTypeUInt128; type: ClarityAbiTypeUInt128 }
| { id: ClarityAbiTypeId.ClarityAbiTypeInt128; type: ClarityAbiTypeInt128 }
| { id: ClarityAbiTypeId.ClarityAbiTypeBool; type: ClarityAbiTypeBool }
| { id: ClarityAbiTypeId.ClarityAbiTypePrincipal; type: ClarityAbiTypePrincipal }
| { id: ClarityAbiTypeId.ClarityAbiTypeTraitReference; type: ClarityAbiTypeTraitReference }
| { id: ClarityAbiTypeId.ClarityAbiTypeNone; type: ClarityAbiTypeNone }
| { id: ClarityAbiTypeId.ClarityAbiTypeBuffer; type: ClarityAbiTypeBuffer }
| { id: ClarityAbiTypeId.ClarityAbiTypeResponse; type: ClarityAbiTypeResponse }
| { id: ClarityAbiTypeId.ClarityAbiTypeOptional; type: ClarityAbiTypeOptional }
| { id: ClarityAbiTypeId.ClarityAbiTypeTuple; type: ClarityAbiTypeTuple }
| { id: ClarityAbiTypeId.ClarityAbiTypeList; type: ClarityAbiTypeList }
| { id: ClarityAbiTypeId.ClarityAbiTypeStringAscii; type: ClarityAbiTypeStringAscii }
| { id: ClarityAbiTypeId.ClarityAbiTypeStringUtf8; type: ClarityAbiTypeStringUtf8 };
export function getTypeUnion(val: ClarityAbiType): ClarityAbiTypeUnion {
if (isClarityAbiPrimitive(val)) {
if (val === 'uint128') {
return { id: ClarityAbiTypeId.ClarityAbiTypeUInt128, type: val };
} else if (val === 'int128') {
return { id: ClarityAbiTypeId.ClarityAbiTypeInt128, type: val };
} else if (val === 'bool') {
return { id: ClarityAbiTypeId.ClarityAbiTypeBool, type: val };
} else if (val === 'principal') {
return { id: ClarityAbiTypeId.ClarityAbiTypePrincipal, type: val };
} else if (val === 'trait_reference') {
return { id: ClarityAbiTypeId.ClarityAbiTypeTraitReference, type: val };
} else if (val === 'none') {
return { id: ClarityAbiTypeId.ClarityAbiTypeNone, type: val };
} else {
throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(val)}`);
}
} else if (isClarityAbiBuffer(val)) {
return { id: ClarityAbiTypeId.ClarityAbiTypeBuffer, type: val };
} else if (isClarityAbiResponse(val)) {
return { id: ClarityAbiTypeId.ClarityAbiTypeResponse, type: val };
} else if (isClarityAbiOptional(val)) {
return { id: ClarityAbiTypeId.ClarityAbiTypeOptional, type: val };
} else if (isClarityAbiTuple(val)) {
return { id: ClarityAbiTypeId.ClarityAbiTypeTuple, type: val };
} else if (isClarityAbiList(val)) {
return { id: ClarityAbiTypeId.ClarityAbiTypeList, type: val };
} else if (isClarityAbiStringAscii(val)) {
return { id: ClarityAbiTypeId.ClarityAbiTypeStringAscii, type: val };
} else if (isClarityAbiStringUtf8(val)) {
return { id: ClarityAbiTypeId.ClarityAbiTypeStringUtf8, type: val };
} else {
throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(val)}`);
}
}
function encodeClarityValue(type: ClarityAbiType, val: string): ClarityValue;
function encodeClarityValue(type: ClarityAbiTypeUnion, val: string): ClarityValue;
function encodeClarityValue(
input: ClarityAbiTypeUnion | ClarityAbiType,
val: string
): ClarityValue {
let union: ClarityAbiTypeUnion;
if ((input as ClarityAbiTypeUnion).id !== undefined) {
union = input as ClarityAbiTypeUnion;
} else {
union = getTypeUnion(input as ClarityAbiType);
}
switch (union.id) {
case ClarityAbiTypeId.ClarityAbiTypeUInt128:
return uintCV(val);
case ClarityAbiTypeId.ClarityAbiTypeInt128:
return intCV(val);
case ClarityAbiTypeId.ClarityAbiTypeBool:
if (val === 'false' || val === '0') return falseCV();
else if (val === 'true' || val === '1') return trueCV();
else throw new Error(`Unexpected Clarity bool value: ${JSON.stringify(val)}`);
case ClarityAbiTypeId.ClarityAbiTypePrincipal:
if (val.includes('.')) {
const [addr, name] = val.split('.');
return contractPrincipalCV(addr, name);
} else {
return standardPrincipalCV(val);
}
case ClarityAbiTypeId.ClarityAbiTypeTraitReference:
const [addr, name] = val.split('.');
return contractPrincipalCV(addr, name);
case ClarityAbiTypeId.ClarityAbiTypeNone:
return noneCV();
case ClarityAbiTypeId.ClarityAbiTypeBuffer:
return bufferCV(Buffer.from(val, 'utf8'));
case ClarityAbiTypeId.ClarityAbiTypeStringAscii:
return stringAsciiCV(val);
case ClarityAbiTypeId.ClarityAbiTypeStringUtf8:
return stringUtf8CV(val);
case ClarityAbiTypeId.ClarityAbiTypeResponse:
throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
case ClarityAbiTypeId.ClarityAbiTypeOptional:
throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
case ClarityAbiTypeId.ClarityAbiTypeTuple:
throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
case ClarityAbiTypeId.ClarityAbiTypeList:
throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
default:
throw new Error(`Unexpected Clarity type ID: ${JSON.stringify(union)}`);
}
}
export { encodeClarityValue };
export function getTypeString(val: ClarityAbiType): string {
if (isClarityAbiPrimitive(val)) {
if (val === 'int128') {
return 'int';
} else if (val === 'uint128') {
return 'uint';
}
return val;
} else if (isClarityAbiBuffer(val)) {
return `(buff ${val.buffer.length})`;
} else if (isClarityAbiStringAscii(val)) {
return `(string-ascii ${val['string-ascii'].length})`;
} else if (isClarityAbiStringUtf8(val)) {
return `(string-utf8 ${val['string-utf8'].length})`;
} else if (isClarityAbiResponse(val)) {
return `(response ${getTypeString(val.response.ok)} ${getTypeString(val.response.error)})`;
} else if (isClarityAbiOptional(val)) {
return `(optional ${getTypeString(val.optional)})`;
} else if (isClarityAbiTuple(val)) {
return `(tuple ${val.tuple.map(t => `(${t.name} ${getTypeString(t.type)})`).join(' ')})`;
} else if (isClarityAbiList(val)) {
return `(list ${val.list.length} ${getTypeString(val.list.type)})`;
} else {
throw new Error(`Type string unsupported for Clarity type: ${JSON.stringify(val)}`);
}
}
export interface ClarityAbiFunction {
name: string;
access: 'private' | 'public' | 'read_only';
args: {
name: string;
type: ClarityAbiType;
}[];
outputs: {
type: ClarityAbiType;
};
}
export function abiFunctionToString(func: ClarityAbiFunction): string {
const access = func.access === 'read_only' ? 'read-only' : func.access;
return `(define-${access} (${func.name} ${func.args
.map(arg => `(${arg.name} ${getTypeString(arg.type)})`)
.join(' ')}))`;
}
export interface ClarityAbiVariable {
name: string;
access: 'variable' | 'constant';
type: ClarityAbiType;
}
export interface ClarityAbiMap {
name: string;
key: {
name: string;
type: ClarityAbiType;
}[];
value: {
name: string;
type: ClarityAbiType;
}[];
}
export interface ClarityAbiTypeFungibleToken {
name: string;
}
export interface ClarityAbiTypeNonFungibleToken {
name: string;
type: ClarityAbiType;
}
export interface ClarityAbi {
functions: ClarityAbiFunction[];
variables: ClarityAbiVariable[];
maps: ClarityAbiMap[];
fungible_tokens: ClarityAbiTypeFungibleToken[];
non_fungible_tokens: ClarityAbiTypeNonFungibleToken[];
}
function matchType(cv: ClarityValue, abiType: ClarityAbiType): boolean {
const union = getTypeUnion(abiType);
switch (cv.type) {
case ClarityType.BoolTrue:
case ClarityType.BoolFalse:
return union.id === ClarityAbiTypeId.ClarityAbiTypeBool;
case ClarityType.Int:
return union.id === ClarityAbiTypeId.ClarityAbiTypeInt128;
case ClarityType.UInt:
return union.id === ClarityAbiTypeId.ClarityAbiTypeUInt128;
case ClarityType.Buffer:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypeBuffer &&
union.type.buffer.length >= cv.buffer.length
);
case ClarityType.StringASCII:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypeStringAscii &&
union.type['string-ascii'].length >= cv.data.length
);
case ClarityType.StringUTF8:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypeStringUtf8 &&
union.type['string-utf8'].length >= cv.data.length
);
case ClarityType.OptionalNone:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypeNone ||
union.id === ClarityAbiTypeId.ClarityAbiTypeOptional
);
case ClarityType.OptionalSome:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypeOptional &&
matchType(cv.value, union.type.optional)
);
case ClarityType.ResponseErr:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypeResponse &&
matchType(cv.value, union.type.response.error)
);
case ClarityType.ResponseOk:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypeResponse &&
matchType(cv.value, union.type.response.ok)
);
case ClarityType.PrincipalContract:
return (
union.id === ClarityAbiTypeId.ClarityAbiTypePrincipal ||
union.id === ClarityAbiTypeId.ClarityAbiTypeTraitReference
);
case ClarityType.PrincipalStandard:
return union.id === ClarityAbiTypeId.ClarityAbiTypePrincipal;
case ClarityType.List:
return (
union.id == ClarityAbiTypeId.ClarityAbiTypeList &&
union.type.list.length >= cv.list.length &&
cv.list.every(val => matchType(val, union.type.list.type))
);
case ClarityType.Tuple:
if (union.id == ClarityAbiTypeId.ClarityAbiTypeTuple) {
const tuple = cloneDeep(cv.data);
for (let i = 0; i < union.type.tuple.length; i++) {
const abiTupleEntry = union.type.tuple[i];
const key = abiTupleEntry.name;
const val = tuple[key];
// if key exists in cv tuple, check if its type matches the abi
// return false if key doesn't exist
if (val) {
if (!matchType(val, abiTupleEntry.type)) {
return false;
}
delete tuple[key];
} else {
return false;
}
}
return true;
} else {
return false;
}
default:
return false;
}
}
/**
* Validates a contract-call payload with a contract ABI
*
* @param {ContractCallPayload} payload - a contract-call payload
* @param {ClarityAbi} abi - a contract ABI
*
* @returns {boolean} true if the payloads functionArgs type check against those in the ABI
*/
export function validateContractCall(payload: ContractCallPayload, abi: ClarityAbi): boolean {
const filtered = abi.functions.filter(fn => fn.name === payload.functionName.content);
if (filtered.length === 1) {
const abiFunc = filtered[0];
const abiArgs = abiFunc.args;
if (payload.functionArgs.length !== abiArgs.length) {
throw new Error(
`Clarity function expects ${abiArgs.length} argument(s) but received ${payload.functionArgs.length}`
);
}
for (let i = 0; i < payload.functionArgs.length; i++) {
const payloadArg = payload.functionArgs[i];
const abiArg = abiArgs[i];
if (!matchType(payloadArg, abiArg.type)) {
const argNum = i + 1;
throw new Error(
`Clarity function \`${
payload.functionName.content
}\` expects argument ${argNum} to be of type ${getTypeString(
abiArg.type
)}, not ${getCVTypeString(payloadArg)}`
);
}
}
return true;
} else if (filtered.length === 0) {
throw new Error(`ABI doesn't contain a function with the name ${payload.functionName.content}`);
} else {
throw new Error(
`Malformed ABI. Contains multiple functions with the name ${payload.functionName.content}`
);
}
}
/**
* Convert string input to Clarity value based on contract ABI data. Only handles Clarity
* primitives and buffers. Responses, optionals, tuples and lists are not supported.
*
* @param {string} input - string to be parsed into Clarity value
* @param {ClarityAbiType} type - the contract function argument object
*
* @returns {ClarityValue} returns a Clarity value
*/
export function parseToCV(input: string, type: ClarityAbiType): ClarityValue {
const typeString = getTypeString(type);
if (isClarityAbiPrimitive(type)) {
if (type === 'uint128') {
return uintCV(input);
} else if (type === 'int128') {
return intCV(input);
} else if (type === 'bool') {
if (input.toLowerCase() === 'true') {
return trueCV();
} else if (input.toLowerCase() === 'false') {
return falseCV();
} else {
throw new Error(`Invalid bool value: ${input}`);
}
} else if (type === 'principal') {
if (input.includes('.')) {
const [address, contractName] = input.split('.');
return contractPrincipalCV(address, contractName);
} else {
return standardPrincipalCV(input);
}
} else {
throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
}
} else if (isClarityAbiBuffer(type)) {
const inputLength = Buffer.from(input).byteLength;
if (inputLength > type.buffer.length) {
throw new Error(`Input exceeds specified buffer length limit of ${type.buffer.length}`);
}
return bufferCVFromString(input);
} else if (isClarityAbiResponse(type)) {
throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
} else if (isClarityAbiOptional(type)) {
throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
} else if (isClarityAbiTuple(type)) {
throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
} else if (isClarityAbiList(type)) {
throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
} else {
throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
}
} | the_stack |
var forPrettyPrinter = false;
interface ITypeDefinition {
name: string;
baseType: string;
interfaces?: string[];
children: IMemberDefinition[];
isTypeScriptSpecific: boolean;
}
interface IMemberDefinition {
name: string;
type?: string;
isToken?: boolean;
isList?: boolean;
isSeparatedList?: boolean;
requiresAtLeastOneItem?: boolean;
isOptional?: boolean;
isTypeScriptSpecific: boolean;
elementType?: string;
}
var interfaces: any = {
IMemberDeclarationSyntax: 'IClassElementSyntax',
IStatementSyntax: 'IModuleElementSyntax',
INameSyntax: 'ITypeSyntax',
IUnaryExpressionSyntax: 'IExpressionSyntax',
IPostfixExpressionSyntax: 'IUnaryExpressionSyntax',
ILeftHandSideExpressionSyntax: 'IPostfixExpressionSyntax',
// Note: for simplicity's sake, we merge CallExpression, NewExpression and MemberExpression
// into IMemberExpression.
IMemberExpressionSyntax: 'ILeftHandSideExpressionSyntax',
ICallExpressionSyntax: 'ILeftHandSideExpressionSyntax',
IPrimaryExpressionSyntax: 'IMemberExpressionSyntax',
};
var definitions: ITypeDefinition[] = [
<any>{
name: 'SourceUnitSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'moduleElements', isList: true, elementType: 'IModuleElementSyntax' },
<any>{ name: 'endOfFileToken', isToken: true }
]
},
<any>{
name: 'ExternalModuleReferenceSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleReferenceSyntax'],
children: [
<any>{ name: 'requireKeyword', isToken: true },
<any>{ name: 'openParenToken', isToken: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ModuleNameModuleReferenceSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleReferenceSyntax'],
children: [
<any>{ name: 'moduleName', type: 'INameSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ImportDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'importKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'equalsToken', isToken: true, excludeFromAST: true },
<any>{ name: 'moduleReference', type: 'IModuleReferenceSyntax' },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ExportAssignmentSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'exportKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'equalsToken', isToken: true, excludeFromAST: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ClassDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'classKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'typeParameterList', type: 'TypeParameterListSyntax', isOptional: true },
<any>{ name: 'heritageClauses', isList: true, elementType: 'HeritageClauseSyntax' },
<any>{ name: 'openBraceToken', isToken: true, excludeFromAST: true },
<any>{ name: 'classElements', isList: true, elementType: 'IClassElementSyntax' },
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'InterfaceDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'interfaceKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'typeParameterList', type: 'TypeParameterListSyntax', isOptional: true },
<any>{ name: 'heritageClauses', isList: true, elementType: 'HeritageClauseSyntax' },
<any>{ name: 'body', type: 'ObjectTypeSyntax' }
],
isTypeScriptSpecific: true
},
<any> {
name: 'HeritageClauseSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'extendsOrImplementsKeyword', isToken: true },
<any>{ name: 'typeNames', isSeparatedList: true, requiresAtLeastOneItem: true, elementType: 'INameSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ModuleDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'moduleKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'name', type: 'INameSyntax' },
<any>{ name: 'openBraceToken', isToken: true, excludeFromAST: true },
<any>{ name: 'moduleElements', isList: true, elementType: 'IModuleElementSyntax' },
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'TypeAliasSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'typeKeyword', isToken: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'equalsToken', isToken: true },
<any>{ name: 'type', type: 'ITypeSyntax' },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'FunctionDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
<any>{ name: 'functionKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'asterixToken', isToken: true, isOptional: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'body', type: 'BlockSyntax | ExpressionBody | ISyntaxToken', isOptional: true }
]
},
<any> {
name: 'ExpressionBody',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'equalsGreaterThanToken', isToken: true, },
<any>{ name: 'expression', type: 'IExpressionSyntax' }
]
},
<any>{
name: 'VariableStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
<any>{ name: 'variableDeclaration', type: 'VariableDeclarationSyntax' },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
]
},
<any>{
name: 'VariableDeclarationSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'varConstOrLetKeyword', isToken: true },
<any>{ name: 'variableDeclarators', isSeparatedList: true, requiresAtLeastOneItem: true, elementType: 'VariableDeclaratorSyntax' }
]
},
<any>{
name: 'VariableDeclaratorSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true, isTypeScriptSpecific: true },
<any>{ name: 'equalsValueClause', type: 'EqualsValueClauseSyntax', isOptional: true }
]
},
<any>{
name: 'EqualsValueClauseSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'equalsToken', isToken: true, excludeFromAST: true },
<any>{ name: 'value', type: 'IExpressionSyntax' }
]
},
<any>{
name: 'PrefixUnaryExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'operatorToken', isToken: true },
<any>{ name: 'operand', type: 'IUnaryExpressionSyntax' }
],
},
<any>{
name: 'ArrayLiteralExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPrimaryExpressionSyntax'],
children: [
<any>{ name: 'openBracketToken', isToken: true, excludeFromAST: true },
<any>{ name: 'expressions', isSeparatedList: true, elementType: 'IExpressionSyntax' },
<any>{ name: 'closeBracketToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'OmittedExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IExpressionSyntax'],
children: <any>[]
},
<any>{
name: 'ParenthesizedExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPrimaryExpressionSyntax'],
children: [
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'SimpleArrowFunctionExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'asyncKeyword', isToken: true, isOptional: true },
<any>{ name: 'parameter', type: 'ParameterSyntax' },
<any>{ name: 'equalsGreaterThanToken', isToken: true, excludeFromAST: true },
<any>{ name: 'body', type: 'BlockSyntax | IExpressionSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ParenthesizedArrowFunctionExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'asyncKeyword', isToken: true, isOptional: true },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'equalsGreaterThanToken', isToken: true, isOptional: true },
<any>{ name: 'body', type: 'BlockSyntax | IExpressionSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'QualifiedNameSyntax',
baseType: 'ISyntaxNode',
interfaces: ['INameSyntax'],
children: [
<any>{ name: 'left', type: 'INameSyntax' },
<any>{ name: 'dotToken', isToken: true, excludeFromAST: true },
<any>{ name: 'right', isToken: true }
],
// Qualified names only show up in Types, which are TypeScript specific. Note that a dotted
// expression (like A.B.Foo()) is a MemberAccessExpression, not a QualifiedName.
isTypeScriptSpecific: true
},
<any>{
name: 'TypeArgumentListSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'lessThanToken', isToken: true },
<any>{ name: 'typeArguments', isSeparatedList: true, elementType: 'ITypeSyntax' },
<any>{ name: 'greaterThanToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ConstructorTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'newKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'typeParameterList', type: 'TypeParameterListSyntax', isOptional: true },
<any>{ name: 'parameterList', type: 'ParameterListSyntax' },
<any>{ name: 'equalsGreaterThanToken', isToken: true, excludeFromAST: true },
<any>{ name: 'type', type: 'ITypeSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'FunctionTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'typeParameterList', type: 'TypeParameterListSyntax', isOptional: true },
<any>{ name: 'parameterList', type: 'ParameterListSyntax' },
<any>{ name: 'equalsGreaterThanToken', isToken: true, excludeFromAST: true },
<any>{ name: 'type', type: 'ITypeSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ObjectTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'openBraceToken', isToken: true, excludeFromAST: true },
<any>{ name: 'typeMembers', isList: true, elementType: 'ITypeMemberSyntax' },
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ArrayTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'type', type: 'ITypeSyntax' },
<any>{ name: 'openBracketToken', isToken: true, excludeFromAST: true },
<any>{ name: 'closeBracketToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'GenericTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'name', type: 'INameSyntax' },
<any>{ name: 'typeArgumentList', type: 'TypeArgumentListSyntax' }
],
isTypeScriptSpecific: true
},
<any> {
name: 'TypeQuerySyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'typeOfKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'name', type: 'INameSyntax' }
],
isTypeScriptSpecific: true
},
<any> {
name: 'TupleTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'openBracketToken', isToken: true, excludeFromAST: true },
<any>{ name: 'types', isSeparatedList: true, elementType: 'ITypeSyntax' },
<any>{ name: 'closeBracketToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any> {
name: 'UnionTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'left', type: 'ITypeSyntax' },
<any>{ name: 'barToken', isToken: true, excludeFromAST: true },
<any>{ name: 'right', type: 'ITypeSyntax' }
],
isTypeScriptSpecific: true
},
<any> {
name: 'ParenthesizedTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'type', type: 'ITypeSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'TypeAnnotationSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'colonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'type', type: 'ITypeSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'BlockSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'equalsGreaterThanToken', isToken: true, isOptional: 'true' },
<any>{ name: 'openBraceToken', isToken: true, },
<any>{ name: 'statements', isList: true, elementType: 'IStatementSyntax' },
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'ParameterSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'dotDotDotToken', isToken: true, isOptional: true, isTypeScriptSpecific: true },
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'questionToken', isToken: true, isOptional: true, isTypeScriptSpecific: true },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true, isTypeScriptSpecific: true },
<any>{ name: 'equalsValueClause', type: 'EqualsValueClauseSyntax', isOptional: true, isTypeScriptSpecific: true }
]
},
<any>{
name: 'PropertyAccessExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberExpressionSyntax', 'ICallExpressionSyntax'],
children: [
<any>{ name: 'expression', type: 'ILeftHandSideExpressionSyntax' },
<any>{ name: 'dotToken', isToken: true, excludeFromAST: true },
<any>{ name: 'name', isToken: true }
]
},
<any>{
name: 'PostfixUnaryExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPostfixExpressionSyntax'],
children: [
<any>{ name: 'operand', type: 'ILeftHandSideExpressionSyntax' },
<any>{ name: 'operatorToken', isToken: true }
],
},
<any>{
name: 'ElementAccessExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberExpressionSyntax', 'ICallExpressionSyntax'],
children: [
<any>{ name: 'expression', type: 'ILeftHandSideExpressionSyntax' },
<any>{ name: 'openBracketToken', isToken: true, excludeFromAST: true },
<any>{ name: 'argumentExpression', type: 'IExpressionSyntax', isOptional: true },
<any>{ name: 'closeBracketToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'TemplateAccessExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberExpressionSyntax', 'ICallExpressionSyntax'],
children: [
<any>{ name: 'expression', type: 'ILeftHandSideExpressionSyntax' },
<any>{ name: 'templateExpression', type: 'IPrimaryExpressionSyntax' }
]
},
<any>{
name: 'TemplateExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPrimaryExpressionSyntax'],
children: [
<any>{ name: 'templateStartToken', isToken: true, excludeFromAST: true },
<any>{ name: 'templateClauses', isList: true, elementType: 'TemplateClauseSyntax' }
]
},
<any>{
name: 'TemplateClauseSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'templateMiddleOrEndToken', isToken: true, elementType: 'TemplateSpanSyntax' }
]
},
<any>{
name: 'InvocationExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ICallExpressionSyntax'],
children: [
<any>{ name: 'expression', type: 'ILeftHandSideExpressionSyntax' },
<any>{ name: 'argumentList', type: 'ArgumentListSyntax' }
]
},
<any>{
name: 'ArgumentListSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'typeArgumentList', type: 'TypeArgumentListSyntax', isOptional: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'arguments', isSeparatedList: true, elementType: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'BinaryExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IExpressionSyntax'],
children: [
<any>{ name: 'left', type: 'IExpressionSyntax' },
<any>{ name: 'operatorToken', isToken: true },
<any>{ name: 'right', type: 'IExpressionSyntax' }
],
},
<any>{
name: 'ConditionalExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IExpressionSyntax'],
children: [
<any>{ name: 'condition', type: 'IExpressionSyntax' },
<any>{ name: 'questionToken', isToken: true, excludeFromAST: true },
<any>{ name: 'whenTrue', type: 'IExpressionSyntax' },
<any>{ name: 'colonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'whenFalse', type: 'IExpressionSyntax' }
]
},
<any>{
name: 'ConstructSignatureSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
<any>{ name: 'newKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'MethodSignatureSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'questionToken', isToken: true, isOptional: true, itTypeScriptSpecific: true },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' }
]
},
<any>{
name: 'IndexSignatureSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax', 'IClassElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'openBracketToken', isToken: true },
<any>{ name: 'parameters', isSeparatedList: true, elementType: 'ParameterSyntax' },
<any>{ name: 'closeBracketToken', isToken: true },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true },
<any>{ name: 'semicolonOrCommaToken', isToken: true, isOptional: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'PropertySignatureSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'questionToken', isToken: true, isOptional: true },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true },
<any>{ name: 'semicolonOrCommaToken', isToken: true, isOptional: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'CallSignatureSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
<any>{ name: 'typeParameterList', type: 'TypeParameterListSyntax', isOptional: true, isTypeScriptSpecific: true },
<any>{ name: 'parameterList', type: 'ParameterListSyntax' },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true, isTypeScriptSpecific: true },
<any>{ name: 'semicolonOrCommaToken', isToken: true, isOptional: true }
]
},
<any>{
name: 'ParameterListSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'parameters', isSeparatedList: true, elementType: 'ParameterSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'TypeParameterListSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'lessThanToken', isToken: true },
<any>{ name: 'typeParameters', isSeparatedList: true, elementType: 'TypeParameterSyntax' },
<any>{ name: 'greaterThanToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'TypeParameterSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'constraint', type: 'ConstraintSyntax', isOptional: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ConstraintSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'extendsKeyword', isToken: true, excludeFromAST: true },
// Expression only in error cases.
<any>{ name: 'typeOrExpression', type: 'ISyntaxNodeOrToken' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ElseClauseSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'elseKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' }
]
},
<any>{
name: 'IfStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'ifKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'condition', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' },
<any>{ name: 'elseClause', type: 'ElseClauseSyntax', isOptional: true }
]
},
<any>{
name: 'ExpressionStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
]
},
<any>{
name: 'ConstructorDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IClassElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'constructorKeyword', isToken: true },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'body', type: 'BlockSyntax | ExpressionBody | ISyntaxToken', isOptional: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'MethodDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberDeclarationSyntax', 'IPropertyAssignmentSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'asterixToken', isToken: true, isOptional: true },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'body', type: 'BlockSyntax | ExpressionBody | ISyntaxToken', isOptional: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'GetAccessorSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IAccessorSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
<any>{ name: 'getKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'body', type: 'BlockSyntax | ExpressionBody | ISyntaxToken', isOptional: true }
]
},
<any>{
name: 'SetAccessorSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IAccessorSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
<any>{ name: 'setKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'body', type: 'BlockSyntax | ExpressionBody | ISyntaxToken', isOptional: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'PropertyDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberDeclarationSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'variableDeclarator', type: 'VariableDeclaratorSyntax' },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ThrowStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'throwKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IExpressionSyntax', isOptional: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
]
},
<any>{
name: 'ReturnStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'returnKeyword', isToken: true },
<any>{ name: 'expression', type: 'IExpressionSyntax', isOptional: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
]
},
<any>{
name: 'ObjectCreationExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPrimaryExpressionSyntax'],
children: [
<any>{ name: 'newKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IMemberExpressionSyntax' },
<any>{ name: 'argumentList', type: 'ArgumentListSyntax', isOptional: true }
]
},
<any>{
name: 'SwitchStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'switchKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'openBraceToken', isToken: true, excludeFromAST: true },
<any>{ name: 'switchClauses', isList: true, elementType: 'ISwitchClauseSyntax' },
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'CaseSwitchClauseSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ISwitchClauseSyntax'],
children: [
<any>{ name: 'caseKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'colonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statements', isList: true, elementType: 'IStatementSyntax' }
]
},
<any>{
name: 'DefaultSwitchClauseSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ISwitchClauseSyntax'],
children: [
<any>{ name: 'defaultKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'colonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statements', isList: true, elementType: 'IStatementSyntax' }
]
},
<any>{
name: 'BreakStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'breakKeyword', isToken: true },
<any>{ name: 'identifier', isToken: true, isOptional: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
]
},
<any>{
name: 'ContinueStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'continueKeyword', isToken: true },
<any>{ name: 'identifier', isToken: true, isOptional: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
]
},
<any>{
name: 'ForStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'forKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'initializer', type: 'VariableDeclarationSyntax | IExpressionSyntax', isOptional: true },
<any>{ name: 'firstSemicolonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'condition', type: 'IExpressionSyntax', isOptional: true },
<any>{ name: 'secondSemicolonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'incrementor', type: 'IExpressionSyntax', isOptional: true },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' }
]
},
<any>{
name: 'ForInStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'forKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'left', type: 'VariableDeclarationSyntax | IExpressionSyntax' },
<any>{ name: 'inKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'right', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' }
]
},
<any>{
name: 'WhileStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'whileKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'condition', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' }
]
},
<any>{
name: 'WithStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'withKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'condition', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' }
]
},
<any>{
name: 'EnumDeclarationSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IModuleElementSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'enumKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'openBraceToken', isToken: true, excludeFromAST: true },
<any>{ name: 'enumElements', isSeparatedList: true, elementType: 'EnumElementSyntax' },
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'EnumElementSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'equalsValueClause', type: 'EqualsValueClauseSyntax', isOptional: true }
]
},
<any>{
name: 'TypeAssertionExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'lessThanToken', isToken: true, excludeFromAST: true },
<any>{ name: 'type', type: 'ITypeSyntax' },
<any>{ name: 'greaterThanToken', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IUnaryExpressionSyntax' }
],
isTypeScriptSpecific: true
},
<any>{
name: 'ObjectLiteralExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPrimaryExpressionSyntax'],
children: [
<any>{ name: 'openBraceToken', isToken: true, excludeFromAST: true },
<any>{ name: 'propertyAssignments', isSeparatedList: true, elementType: 'IPropertyAssignmentSyntax' },
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'ComputedPropertyNameSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPropertyNameSyntax'],
children: [
<any>{ name: 'openBracketToken', isToken: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'closeBracketToken', isToken: true }
]
},
<any>{
name: 'PropertyAssignmentSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPropertyAssignmentSyntax'],
children: [
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'colonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' }
]
},
<any>{
name: 'FunctionExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPrimaryExpressionSyntax'],
children: [
<any>{ name: 'asyncKeyword', isToken: true, isOptional: true },
<any>{ name: 'functionKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'asterixToken', isToken: true, isOptional: true },
<any>{ name: 'identifier', isToken: true, isOptional: true },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'body', type: 'BlockSyntax | ExpressionBody | ISyntaxToken', isOptional: true }]
},
<any>{
name: 'EmptyStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'semicolonToken', isToken: true }]
},
<any>{
name: 'TryStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'tryKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'block', type: 'BlockSyntax' },
<any>{ name: 'catchClause', type: 'CatchClauseSyntax', isOptional: true },
<any>{ name: 'finallyClause', type: 'FinallyClauseSyntax', isOptional: true }]
},
<any>{
name: 'CatchClauseSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'catchKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true, isTypeScriptSpecified: true },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'block', type: 'BlockSyntax' }]
},
<any>{
name: 'FinallyClauseSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'finallyKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'block', type: 'BlockSyntax' }]
},
<any>{
name: 'LabeledStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'identifier', isToken: true },
<any>{ name: 'colonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' }]
},
<any>{
name: 'DoStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'doKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'statement', type: 'IStatementSyntax' },
<any>{ name: 'whileKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'condition', type: 'IExpressionSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }]
},
<any>{
name: 'TypeOfExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'typeOfKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IUnaryExpressionSyntax' }]
},
<any>{
name: 'DeleteExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'deleteKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IUnaryExpressionSyntax' }]
},
<any>{
name: 'VoidExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'voidKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IUnaryExpressionSyntax' }]
},
<any>{
name: 'YieldExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IExpressionSyntax'],
children: [
<any>{ name: 'yieldKeyword', isToken: true },
<any>{ name: 'asterixToken', isToken: true, isOptional: true },
<any>{ name: 'expression', type: 'IExpressionSyntax', isOptional: true }]
},
<any>{
name: 'AwaitExpressionSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IUnaryExpressionSyntax'],
children: [
<any>{ name: 'awaitKeyword', isToken: true },
<any>{ name: 'expression', type: 'IUnaryExpressionSyntax', isOptional: true }]
},
<any>{
name: 'DebuggerStatementSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IStatementSyntax'],
children: [
<any>{ name: 'debuggerKeyword', isToken: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }]
}];
function getSyntaxKindEnum() {
var name = "SyntaxKind";
return (<any>TypeScript)[name];
}
function firstKind(definition: ITypeDefinition): TypeScript.SyntaxKind {
var kindName = getNameWithoutSuffix(definition);
return getSyntaxKindEnum()[kindName];
}
definitions.sort((d1, d2) => firstKind(d1) - firstKind(d2));
function getStringWithoutSuffix(definition: string) {
if (TypeScript.StringUtilities.endsWith(definition, "Syntax")) {
return definition.substring(0, definition.length - "Syntax".length);
}
return definition;
}
function getNameWithoutSuffix(definition: ITypeDefinition) {
return getStringWithoutSuffix(definition.name);
}
function getType(child: IMemberDefinition): string {
if (child.isToken) {
return "ISyntaxToken";
}
else if (child.isSeparatedList) {
return "ISeparatedSyntaxList<" + child.elementType + ">";
}
else if (child.isList) {
return child.elementType + "[]";
}
else {
return child.type;
}
}
function camelCase(value: string): string {
return value.substr(0, 1).toLowerCase() + value.substr(1);
}
function getSafeName(child: IMemberDefinition) {
if (child.name === "arguments") {
return "_" + child.name;
}
return child.name;
}
function generateConstructorFunction(definition: ITypeDefinition) {
var result = " export var " + definition.name + ": " + getNameWithoutSuffix(definition) + "Constructor = <any>function(data: number";
for (var i = 0; i < definition.children.length; i++) {
var child = definition.children[i];
result += ", ";
result += getSafeName(child);
result += ": " + getType(child);
}
result += ") {\r\n";
result += " if (data) { this.__data = data; }\r\n";
result += " this.parent = undefined";
if (definition.children.length) {
for (var i = 0; i < definition.children.length; i++) {
//if (i) {
result += ",\r\n";
//}
var child = definition.children[i];
result += " this." + child.name + " = " + getSafeName(child);
}
}
result += ";\r\n";
result += " };\r\n";
result += " " + definition.name + ".prototype.kind = SyntaxKind." + getNameWithoutSuffix(definition) + ";\r\n";
result += " " + definition.name + ".prototype.childCount = " + definition.children.length + ";\r\n";
result += " " + definition.name + ".prototype.childAt = function(index: number): ISyntaxElement {\r\n";
if (definition.children.length) {
result += " switch (index) {\r\n";
for (var j = 0; j < definition.children.length; j++) {
result += " case " + j + ": return this." + definition.children[j].name + ";\r\n";
}
result += " }\r\n";
}
else {
result += " throw Errors.invalidOperation();\r\n";
}
result += " }\r\n";
return result;
}
function generateSyntaxInterfaces(): string {
var result = "///<reference path='references.ts' />\r\n\r\n";
result += "module TypeScript {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
if (i > 0) {
result += "\r\n";
}
result += generateSyntaxInterface(definition);
}
result += "}";
return result;
}
function generateSyntaxInterface(definition: ITypeDefinition): string {
var result = " export interface " + definition.name + " extends ISyntaxNode"
if (definition.interfaces) {
result += ", ";
result += definition.interfaces.join(", ");
}
result += " {\r\n";
if (definition.name === "SourceUnitSyntax") {
result += " syntaxTree: SyntaxTree;\r\n";
}
for (var i = 0; i < definition.children.length; i++) {
var child = definition.children[i];
result += " " + child.name + ": " + getType(child) + ";\r\n";
}
result += " }\r\n";
result += " export interface " + getNameWithoutSuffix(definition) + "Constructor {";
result += " new (data: number";
for (var i = 0; i < definition.children.length; i++) {
var child = definition.children[i];
result += ", ";
result += getSafeName(child);
result += ": " + getType(child);
}
result += "): " + definition.name;
result += " }\r\n";
return result;
}
function generateNodes(): string {
var result = "///<reference path='references.ts' />\r\n\r\n";
result += "module TypeScript";
result += " {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
if (i) {
result += "\r\n";
}
result += generateConstructorFunction(definition);
}
result += "}";
return result;
}
function isInterface(name: string) {
return name.substr(0, 1) === "I" && name.substr(1, 1).toUpperCase() === name.substr(1, 1)
}
function generateWalker(): string {
var result = "";
result +=
"///<reference path='references.ts' />\r\n" +
"\r\n" +
"module TypeScript {\r\n" +
" export class SyntaxWalker implements ISyntaxVisitor {\r\n" +
" public visitToken(token: ISyntaxToken): void {\r\n" +
" }\r\n" +
"\r\n" +
" private visitOptionalToken(token: ISyntaxToken): void {\r\n" +
" if (token === undefined) {\r\n" +
" return;\r\n" +
" }\r\n" +
"\r\n" +
" this.visitToken(token);\r\n" +
" }\r\n" +
"\r\n" +
" public visitList(list: ISyntaxNodeOrToken[]): void {\r\n" +
" for (var i = 0, n = list.length; i < n; i++) {\r\n" +
" visitNodeOrToken(this, list[i]);\r\n" +
" }\r\n" +
" }\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += "\r\n";
result += " public visit" + getNameWithoutSuffix(definition) + "(node: " + definition.name + "): void {\r\n";
for (var j = 0; j < definition.children.length; j++) {
var child = definition.children[j];
if (child.isToken) {
if (child.isOptional) {
result += " this.visitOptionalToken(node." + child.name + ");\r\n";
}
else {
result += " this.visitToken(node." + child.name + ");\r\n";
}
}
else if (child.isList || child.isSeparatedList) {
result += " this.visitList(node." + child.name + ");\r\n";
}
else if (child.isToken) {
if (child.isOptional) {
result += " this.visitOptionalToken(node." + child.name + ");\r\n";
}
else {
result += " this.visitToken(node." + child.name + ");\r\n";
}
}
else {
result += " visitNodeOrToken(this, node." + child.name + ");\r\n";
}
}
result += " }\r\n";
}
result += " }";
result += "\r\n}";
return result;
}
function firstEnumName(e: any, value: number) {
for (var name in e) {
if (e[name] === value) {
return name;
}
}
}
function groupBy<T>(array: T[], func: (v: T) => string): any {
var result: any = {};
for (var i = 0, n = array.length; i < n; i++) {
var v: any = array[i];
var k = func(v);
var list: T[] = result[k] || [];
list.push(v);
result[k] = list;
}
return result;
}
function generateKeywordCondition(keywords: { text: string; kind: TypeScript.SyntaxKind; }[], currentCharacter: number, indent: string): string {
var length = keywords[0].text.length;
var result = "";
var index: string;
if (keywords.length === 1) {
var keyword = keywords[0];
if (currentCharacter === length) {
return " return SyntaxKind." + firstEnumName(getSyntaxKindEnum(), keyword.kind) + ";\r\n";
}
var keywordText = keywords[0].text;
result = " return ("
for (var i = currentCharacter; i < length; i++) {
if (i > currentCharacter) {
result += " && ";
}
index = i === 0 ? "start" : ("start + " + i);
result += "str.charCodeAt(" + index + ") === CharacterCodes." + keywordText.substr(i, 1);
}
result += ") ? SyntaxKind." + firstEnumName(getSyntaxKindEnum(), keyword.kind) + " : SyntaxKind.IdentifierName;\r\n";
}
else {
result += " // " + TypeScript.ArrayUtilities.select(keywords, k => k.text).join(", ") + "\r\n"
index = currentCharacter === 0 ? "start" : ("start + " + currentCharacter);
result += indent + "switch(str.charCodeAt(" + index + ")) {\r\n"
var groupedKeywords = groupBy(keywords, k => k.text.substr(currentCharacter, 1));
for (var c in groupedKeywords) {
if (groupedKeywords.hasOwnProperty(c)) {
result += indent + " case CharacterCodes." + c + ":";
result += generateKeywordCondition(groupedKeywords[c], currentCharacter + 1, indent + " ");
}
}
result += indent + " default: return SyntaxKind.IdentifierName;\r\n";
result += indent + "}\r\n";
}
return result;
}
function min<T>(array: T[], func: (v: T) => number): number {
var min = func(array[0]);
for (var i = 1; i < array.length; i++) {
var next = func(array[i]);
if (next < min) {
min = next;
}
}
return min;
}
function max<T>(array: T[], func: (v: T) => number): number {
var max = func(array[0]);
for (var i = 1; i < array.length; i++) {
var next = func(array[i]);
if (next > max) {
max = next;
}
}
return max;
}
function generateUtilities(): string {
var result = ""; //"module TypeScript.Scanner {";
//result += " function fixedWidthTokenLength(kind: SyntaxKind) {\r\n";
//result += " return fixedWidthArray[kind];\r\n";
//result += " switch (kind) {\r\n";
//for (var k = TypeScript.SyntaxKind.FirstFixedWidth; k <= TypeScript.SyntaxKind.LastFixedWidth; k++) {
// result += " case SyntaxKind." + syntaxKindName(k) + ": return " + TypeScript.SyntaxFacts.getText(k).length + ";\r\n";
//}
//result += " default: throw new Error();\r\n";
//result += " }\r\n";
// result += " }\r\n";
return result;
}
function generateScannerUtilities(): string {
var result = "///<reference path='references.ts' />\r\n" +
"\r\n" +
"module TypeScript {\r\n" +
" export module ScannerUtilities {\r\n";
result += " export var fixedWidthArray = [";
for (var i = 0; i <= TypeScript.SyntaxKind.LastFixedWidth; i++) {
if (i) {
result += ", ";
}
if (i < TypeScript.SyntaxKind.FirstFixedWidth) {
result += "0";
}
else {
result += TypeScript.SyntaxFacts.getText(i).length;
}
}
result += "];\r\n";
var i: number;
var keywords: { text: string; kind: TypeScript.SyntaxKind; }[] = [];
for (i = TypeScript.SyntaxKind.FirstKeyword; i <= TypeScript.SyntaxKind.LastKeyword; i++) {
keywords.push({ kind: i, text: TypeScript.SyntaxFacts.getText(i) });
}
keywords.sort((a, b) => a.text.localeCompare(b.text));
result += " export function identifierKind(str: string, start: number, length: number): SyntaxKind {\r\n";
var minTokenLength = min(keywords, k => k.text.length);
var maxTokenLength = max(keywords, k => k.text.length);
result += " switch (length) {\r\n";
for (i = minTokenLength; i <= maxTokenLength; i++) {
var keywordsOfLengthI = TypeScript.ArrayUtilities.where(keywords, k => k.text.length === i);
if (keywordsOfLengthI.length > 0) {
result += " case " + i + ":";
result += generateKeywordCondition(keywordsOfLengthI, 0, " ");
}
}
result += " default: return SyntaxKind.IdentifierName;\r\n";
result += " }\r\n";
result += " }\r\n";
result += " }\r\n";
result += "}";
return result;
}
function syntaxKindName(kind: TypeScript.SyntaxKind): string {
for (var name in getSyntaxKindEnum()) {
if (getSyntaxKindEnum()[name] === kind) {
return name;
}
}
throw new Error();
}
function generateVisitor(): string {
var result = "";
result += "///<reference path='references.ts' />\r\n\r\n";
result += "module TypeScript {\r\n";
result += " export function visitNodeOrToken(visitor: ISyntaxVisitor, element: ISyntaxNodeOrToken): any {\r\n";
result += " if (element === undefined) { return undefined; }\r\n";
result += " switch (element.kind) {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " case SyntaxKind." + getNameWithoutSuffix(definition) + ": ";
result += "return visitor.visit" + getNameWithoutSuffix(definition) + "(<" + definition.name + ">element);\r\n";
}
result += " default: return visitor.visitToken(<ISyntaxToken>element);\r\n";
result += " }\r\n";
result += " }\r\n\r\n";
result += " export interface ISyntaxVisitor {\r\n";
result += " visitToken(token: ISyntaxToken): any;\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " visit" + getNameWithoutSuffix(definition) + "(node: " + definition.name + "): any;\r\n";
}
result += " }";
result += "\r\n}";
return result;
}
var syntaxNodesConcrete = generateNodes();
var syntaxInterfaces = generateSyntaxInterfaces();
var walker = generateWalker();
var scannerUtilities = generateScannerUtilities();
var visitor = generateVisitor();
var utilities = generateUtilities();
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxNodes.concrete.generated.ts", syntaxNodesConcrete, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxInterfaces.generated.ts", syntaxInterfaces, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxWalker.generated.ts", walker, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\scannerUtilities.generated.ts", scannerUtilities, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxVisitor.generated.ts", visitor, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\utilities.generated.ts", utilities, false); | the_stack |
import { VectorChainReader, waitForTransaction } from "@connext/vector-contracts";
import {
AllowedSwap,
HydratedProviders,
jsonifyError,
Result,
TAddress,
TBytes32,
TIntegerString,
MinimalTransaction,
CheckStatusParams,
getConfirmationsForChain,
} from "@connext/vector-types";
import { getRandomBytes32 } from "@connext/vector-utils";
import { TransactionReceipt } from "@ethersproject/abstract-provider";
import { BigNumber } from "@ethersproject/bignumber";
import { parseUnits } from "@ethersproject/units";
import { Wallet } from "@ethersproject/wallet";
import { Type, Static } from "@sinclair/typebox";
import axios from "axios";
import { BaseLogger } from "pino";
import { v4 as uuidv4 } from "uuid";
import { getConfig } from "../config";
import { AutoRebalanceServiceError } from "../errors";
import { parseBalanceToNumber, rebalancedTokens } from "../metrics";
import { queueRebalance } from "./rebalanceQueue";
import { IRouterStore, RouterRebalanceRecord, RouterRebalanceStatus } from "./store";
const config = getConfig();
const DEFAULT_REBALANCE_THRESHOLD = 20;
const MIN_INTERVAL = 1_800_000;
// copied from chain-rebalancer-fastify
export const RebalanceParamsSchema = Type.Object({
amount: TIntegerString,
assetId: TAddress,
signer: TAddress,
txHash: Type.Optional(TBytes32),
fromProvider: Type.String({ format: "uri" }),
toProvider: Type.String({ format: "uri" }),
fromChainId: Type.Number(),
toChainId: Type.Number(),
});
export type RebalanceParams = Static<typeof RebalanceParamsSchema>;
export const startAutoRebalanceTask = (
interval: number,
logger: BaseLogger,
wallet: Wallet,
chainService: VectorChainReader,
hydratedProviders: HydratedProviders,
store: IRouterStore,
): void => {
if (interval < MIN_INTERVAL) {
throw new Error(`Interval ${interval} must be at least ${MIN_INTERVAL}`);
}
setInterval(() => {
autoRebalanceTask(logger, wallet, chainService, hydratedProviders, store);
}, interval);
};
export const autoRebalanceTask = async (
logger: BaseLogger,
wallet: Wallet,
chainService: VectorChainReader,
hydratedProviders: HydratedProviders,
store: IRouterStore,
): Promise<void> => {
const method = "autoRebalanceTask";
const methodId = getRandomBytes32();
logger.info({ method, methodId, allowedSwaps: config.allowedSwaps }, "Start task");
for (const swap of config.allowedSwaps) {
const rebalanced = await rebalanceIfNeeded(swap, logger, wallet, chainService, hydratedProviders, store);
if (rebalanced.isError) {
logger.error({ swap, error: jsonifyError(rebalanced.getError()!) }, "Error auto rebalancing");
return;
}
logger.info({ res: rebalanced.getValue() }, "Rebalance completed");
}
};
export const rebalanceIfNeeded = async (
swap: AllowedSwap,
logger: BaseLogger,
wallet: Wallet,
chainService: VectorChainReader,
hydratedProviders: HydratedProviders,
store: IRouterStore,
): Promise<Result<undefined, AutoRebalanceServiceError>> => {
return await queueRebalance<Result<undefined, AutoRebalanceServiceError>>(swap, () => {
return _rebalanceIfNeeded(
swap,
logger,
wallet,
chainService,
hydratedProviders,
store,
)
});
}
const _rebalanceIfNeeded = async (
swap: AllowedSwap,
logger: BaseLogger,
wallet: Wallet,
chainService: VectorChainReader,
hydratedProviders: HydratedProviders,
store: IRouterStore,
): Promise<Result<undefined, AutoRebalanceServiceError>> => {
const method = "rebalanceIfNeeded";
const methodId = getRandomBytes32();
if (!swap.rebalancerUrl) {
logger.debug({ method, intervalId: methodId, swap }, "No rebalancer configured for swap, doing nothing");
return Result.ok(undefined);
}
logger.info({ method, intervalId: methodId, swap }, "Checking if rebalance is needed");
const rebalanceThreshold = swap.rebalanceThresholdPct ? swap.rebalanceThresholdPct : DEFAULT_REBALANCE_THRESHOLD;
const fromAssetBalance = await chainService.getOnchainBalance(swap.fromAssetId, wallet.address, swap.fromChainId);
if (fromAssetBalance.isError) {
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.CouldNotGetAssetBalance,
swap.fromChainId,
swap.fromAssetId,
{ getOnchainBalanceError: jsonifyError(fromAssetBalance.getError()!), methodId, method },
),
);
}
const fromAssetBalanceNumber = await parseBalanceToNumber(
fromAssetBalance.getValue(),
swap.fromChainId.toString(),
swap.fromAssetId,
);
const toAssetBalance = await chainService.getOnchainBalance(swap.toAssetId, wallet.address, swap.toChainId);
if (toAssetBalance.isError) {
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.CouldNotGetAssetBalance,
swap.toChainId,
swap.toAssetId,
{ getOnchainBalanceError: jsonifyError(toAssetBalance.getError()!), methodId, method },
),
);
}
const toAssetBalanceNumber = await parseBalanceToNumber(
toAssetBalance.getValue(),
swap.toChainId.toString(),
swap.toAssetId,
);
// should be within 1/2 of total balance + threshold
const totalBalance = fromAssetBalanceNumber + toAssetBalanceNumber;
const midpoint = totalBalance / 2;
const threshold = midpoint * (1 + rebalanceThreshold / 100);
logger.info(
{
method,
intervalId: methodId,
fromAssetBalanceNumber,
toAssetBalanceNumber,
rebalanceThreshold,
totalBalance,
threshold,
midpoint,
},
"Calculated numbers",
);
if (fromAssetBalanceNumber <= threshold) {
logger.info(
{
method,
intervalId: methodId,
swap,
},
"No rebalance required",
);
return Result.ok(undefined);
}
const amountToSendNumber = fromAssetBalanceNumber - midpoint;
const amountToSend = parseUnits(
amountToSendNumber.toString(),
rebalancedTokens[swap.fromChainId][swap.fromAssetId].decimals!,
);
logger.info(
{
method,
intervalId: methodId,
amountToSendNumber,
amountToSend: amountToSend.toString(),
},
"Rebalance required",
);
// on each rebalance interval, check rebalance thresholds for allowedSwaps
// if out of threshold, check if active rebalance for that swap exists
// if it does not, create one and go through the approve/execute flow
// if it does exist, check status. if status == {completed: true} and/or
// if there is a tx in the response (is the case with matic withdraw),
// send the tx, and mark as completed. if no tx in the response, mark as completed immediately
// if it is not finished, wait for next poll
// check if an active rebalance is in progress
let latestRebalance = await store.getLatestRebalance(swap);
if (!latestRebalance || latestRebalance.status === RouterRebalanceStatus.COMPLETE) {
// If there's no record of a previous rebalance, or if the last one finished successfully,
// create a new rebalance record.
latestRebalance = {
swap,
status: RouterRebalanceStatus.PENDING,
id: uuidv4()
} as RouterRebalanceRecord;
await store.saveRebalance(latestRebalance);
}
// STEP 1: Approve rebalance.
if (latestRebalance.status === RouterRebalanceStatus.PENDING) {
// Check if Tx already sent.
let { approveHash, approveChain } = latestRebalance;
if (!approveHash) {
const approveResult = await approveRebalance(
amountToSend,
swap,
hydratedProviders,
wallet,
logger,
methodId,
);
// Check for error.
if (approveResult.isError) {
return Result.fail(approveResult.getError()!);
}
const value = approveResult.getValue();
approveHash = value.transactionHash;
approveChain = value.transactionChainId;
if (value.isRequired) {
// Tx was successfully sent if needed.
latestRebalance = {
...latestRebalance,
approveHash,
approveChain,
} as RouterRebalanceRecord;
await store.saveRebalance(latestRebalance);
}
}
// wait confirmation if the approveHash is defined (it will be undefined in the event
// an approve tx was not needed).
if (approveHash && approveChain) {
// Await confirmation.
const confirmationResult = await getConfirmation(
approveHash,
approveChain,
swap,
hydratedProviders,
logger,
methodId,
);
if (confirmationResult.isError) {
return Result.fail(confirmationResult.getError()!);
}
}
// Save approved status. Once method above returns, receipt has been received.
latestRebalance = {
...latestRebalance,
status: RouterRebalanceStatus.APPROVED,
};
await store.saveRebalance(latestRebalance);
}
// STEP 2. Execute.
if (latestRebalance.status === RouterRebalanceStatus.APPROVED) {
// Check if Tx already sent.
let { executeHash, executeChain } = latestRebalance;
if (!executeHash) {
const executeResult = await executeRebalance(
amountToSend,
swap,
hydratedProviders,
wallet,
logger,
methodId,
);
// Check for error.
if (executeResult.isError) {
return Result.fail(executeResult.getError()!);
}
const value = executeResult.getValue();
executeHash = value.transactionHash;
executeChain = value.transactionChainId;
// Save hash.
latestRebalance = {
...latestRebalance,
executeHash,
executeChain,
} as RouterRebalanceRecord;
await store.saveRebalance(latestRebalance);
}
// Await confirmation,
const confirmationResult = await getConfirmation(
executeHash,
// We can force unwrap here as it's impossible for the executeHash to have been
// saved/defined without executeChain being saved/defined.
executeChain!,
swap,
hydratedProviders,
logger,
methodId,
);
if (confirmationResult.isError) {
return Result.fail(confirmationResult.getError()!);
}
// Save executed status. Once method above returns, receipt has been received.
latestRebalance = {
...latestRebalance,
status: RouterRebalanceStatus.EXECUTED
};
await store.saveRebalance(latestRebalance);
}
// STEP 3. Complete rebalance.
if (latestRebalance.status === RouterRebalanceStatus.EXECUTED) {
// Ensure that the rebalance has been executed.
if (!latestRebalance.executeHash) {
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.ExecutedWithoutHash,
swap.fromChainId,
swap.fromAssetId,
{ method, methodId, latestRebalance },
),
);
}
// Check if Tx already sent.
let { completeHash, completeChain } = latestRebalance;
if (!completeHash) {
const completedResult = await completeRebalance(
amountToSend,
latestRebalance.executeHash,
swap,
hydratedProviders,
wallet,
logger,
methodId,
);
if (completedResult.isError) {
return Result.fail(completedResult.getError()!);
}
const value = completedResult.getValue();
if (value.isRequired) {
if (!completedResult.getValue().didComplete) {
// Rebalance hasn't completed yet, so we'll return here
// and retry on the next call of this method.
return Result.ok(undefined);
}
const value = completedResult.getValue();
completeHash = value.transactionHash;
completeChain = value.transactionChainId;
latestRebalance = {
...latestRebalance,
completeHash,
completeChain,
} as RouterRebalanceRecord;
await store.saveRebalance(latestRebalance);
}
}
// We do a separate check here once we're certain the above block has executed,
// guaranteeing completion tx has been sent if needed.
if (completeHash && completeChain) {
// Completion tx was needed and has been sent. Wait for confirmation.
const confirmationResult = await getConfirmation(
completeHash,
completeChain,
swap,
hydratedProviders,
logger,
methodId,
);
if (confirmationResult.isError) {
return Result.fail(confirmationResult.getError()!);
}
}
// Save complete status.
latestRebalance = {
...latestRebalance,
status: RouterRebalanceStatus.COMPLETE
};
await store.saveRebalance(latestRebalance);
}
return Result.ok(undefined);
};
// TODO: add rebalance txs to metrics/db
export const approveRebalance = async (
amount: BigNumber,
swap: AllowedSwap,
hydratedProviders: HydratedProviders,
wallet: Wallet,
logger: BaseLogger,
methodId: string = getRandomBytes32(),
): Promise<Result<{ isRequired: boolean; transactionHash?: string; transactionChainId?: number }, AutoRebalanceServiceError>> => {
const method = "approveRebalance";
logger.debug({ method, methodId, swap, amount: amount.toString() }, "Method started");
try {
const approveUrl = `${swap.rebalancerUrl}/approval`;
const postBody: RebalanceParams = {
amount: amount.toString(),
assetId: swap.fromAssetId,
fromProvider: config.chainProviders[swap.fromChainId],
fromChainId: swap.fromChainId,
toProvider: config.chainProviders[swap.toChainId],
toChainId: swap.toChainId,
signer: wallet.address,
};
logger.info(
{
method,
methodId,
approveUrl,
postBody,
},
"Sending approval request",
);
const approveRes = await axios.post(approveUrl, postBody);
logger.info(
{
method,
methodId,
approveRes: approveRes.data,
status: approveRes.data.status,
},
"Approval request complete",
);
const isRequired = !!approveRes.data.transaction;
if (!isRequired) {
logger.info(
{
method,
methodId,
allowance: approveRes.data.allowance,
status: approveRes.data.status,
},
"Approval not needed",
);
return Result.ok({
isRequired
});
}
logger.info(
{
method,
methodId,
transaction: approveRes.data.transaction,
},
"Approval required",
);
const transactionChainId = swap.fromChainId;
const transactionHash = await sendTransaction(
transactionChainId,
approveRes.data.transaction,
wallet,
hydratedProviders,
logger,
method,
methodId,
);
return Result.ok({
isRequired,
transactionHash,
transactionChainId,
});
} catch (e) {
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.CouldNotCompleteApproval,
swap.fromChainId,
swap.fromAssetId,
{ methodId, method, error: jsonifyError(e) },
),
);
}
};
// TODO: add rebalance txs to metrics/db
export const executeRebalance = async (
amount: BigNumber,
swap: AllowedSwap,
hydratedProviders: HydratedProviders,
wallet: Wallet,
logger: BaseLogger,
methodId: string = getRandomBytes32(),
): Promise<Result<{ transactionHash: string; transactionChainId: number; }, AutoRebalanceServiceError>> => {
// execute rebalance
const method = "executeRebalance";
logger.debug({ method, methodId, swap, amount: amount.toString() }, "Method started");
try {
const rebalanceUrl = `${swap.rebalancerUrl}/execute`;
const postBody: RebalanceParams = {
amount: amount.toString(),
assetId: swap.fromAssetId,
fromProvider: config.chainProviders[swap.fromChainId],
fromChainId: swap.fromChainId,
toProvider: config.chainProviders[swap.toChainId],
toChainId: swap.toChainId,
signer: wallet.address,
};
logger.info(
{
method,
methodId,
rebalanceUrl,
postBody,
},
"Sending rebalance execute request",
);
const rebalanceRes = await axios.post(rebalanceUrl, postBody);
logger.info(
{
method,
intervalId: methodId,
rebalanceRes: rebalanceRes.data,
status: rebalanceRes.status,
},
"Rebalance request sent",
);
if (!rebalanceRes.data.transaction) {
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.CouldNotCompleteRebalance,
swap.fromChainId,
swap.fromAssetId,
{ methodId, method, error: "No transaction data available", data: rebalanceRes.data },
),
);
}
const transactionChainId = swap.fromChainId;
const transactionHash = await sendTransaction(
transactionChainId,
rebalanceRes.data.transaction,
wallet,
hydratedProviders,
logger,
method,
methodId,
);
return Result.ok({
transactionHash,
transactionChainId,
});
} catch (e) {
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.CouldNotExecuteRebalance,
swap.fromChainId,
swap.fromAssetId,
{ methodId, method, error: jsonifyError(e) },
),
);
}
};
// TODO: add rebalance txs to metrics/db
// NOTE: only l2 --> l1 withdrawals have a completion tx
export const completeRebalance = async (
amount: BigNumber,
executedHash: string,
swap: AllowedSwap,
hydratedProviders: HydratedProviders,
wallet: Wallet,
logger: BaseLogger,
methodId: string = getRandomBytes32(),
): Promise<Result<{ isRequired: boolean; didComplete: boolean; transactionHash?: string; transactionChainId?: number }, AutoRebalanceServiceError>> => {
// complete/check rebalance status
const method = "completeRebalance";
logger.debug({ method, methodId, swap, amount: amount.toString() }, "Method started");
try {
const statusUrl = `${swap.rebalancerUrl}/status`;
const postBody: CheckStatusParams = {
txHash: executedHash,
fromProvider: config.chainProviders[swap.fromChainId],
fromChainId: swap.fromChainId,
toProvider: config.chainProviders[swap.toChainId],
toChainId: swap.toChainId,
signer: wallet.address,
};
logger.info(
{
method,
methodId,
statusUrl,
postBody,
},
"Sending rebalance status request",
);
// check status
const statusRes = await axios.post(statusUrl, postBody);
logger.info(
{
method,
intervalId: methodId,
statusRes: statusRes.data,
},
"Status request sent",
);
const { status } = statusRes.data;
if (!status || !status.completed) {
logger.info({ status, method, intervalId: methodId }, "Rebalance not completed");
return Result.ok({ isRequired: true, didComplete: status.completed });
}
// is completed, check if tx is needed
if (!status.transaction) {
logger.info({ intervalId: methodId }, "No completion tx required");
return Result.ok({ isRequired: false, didComplete: status.completed });
}
logger.info({ status, method, intervalId: methodId }, "Sending complete tx");
// need to send tx to complete rebalance
const transactionChainId = status.transaction.chainId;
const transactionHash = await sendTransaction(
transactionChainId,
status.transaction,
wallet,
hydratedProviders,
logger,
method,
methodId,
);
logger.info(
{ transactionHash, transaction: status.transaction, method, intervalId: methodId },
"Sent execute tx, completed",
);
return Result.ok({
isRequired: true,
didComplete: true,
transactionHash,
transactionChainId,
});
} catch (e) {
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.CouldNotCompleteRebalance,
swap.fromChainId,
swap.fromAssetId,
{ methodId, method, error: jsonifyError(e) },
),
);
}
};
const sendTransaction = async (
chainId: number,
transaction: MinimalTransaction,
wallet: Wallet,
providers: HydratedProviders,
logger: BaseLogger,
method: string = "sendTransaction",
methodId: string = getRandomBytes32(),
): Promise<string> => {
const provider = providers[chainId];
if (!provider) {
throw new Error(`No provider for chain ${chainId}, cannot send tx`);
}
const gasPrice = (transaction as any).gasPrice ?? (await provider.getGasPrice());
logger.info(
{
method,
intervalId: methodId,
chainId,
gasPrice: gasPrice.toString(),
from: wallet.address,
data: transaction.data,
to: transaction.to,
value: (transaction.value ?? 0).toString(),
},
"Sending tx",
);
const response = await wallet.connect(provider).sendTransaction({
to: transaction.to,
value: transaction.value ?? 0,
data: transaction.data,
gasPrice: BigNumber.from(gasPrice),
});
logger.info(
{
method,
intervalId: methodId,
hash: response.hash,
},
"Tx sent",
);
return response.hash;
};
const getConfirmation = async (
txHash: string,
chainId: number,
swap: AllowedSwap,
providers: HydratedProviders,
logger: BaseLogger,
method: string = "getConfirmation",
methodId: string = getRandomBytes32()
): Promise<Result<TransactionReceipt, AutoRebalanceServiceError>> => {
const result = await waitForTransaction(providers[chainId], txHash, getConfirmationsForChain(chainId));
const error = result.getError()
if (error) {
// Result's error would be of type ChainError, hence the need for wrapping here.
return Result.fail(
new AutoRebalanceServiceError(
AutoRebalanceServiceError.reasons.CouldNotCompleteRebalance,
chainId,
swap.fromAssetId,
{ methodId, method, error: jsonifyError(error) },
),
);
}
logger.info(
{
method,
intervalId: methodId,
hash: txHash,
},
"Tx mined",
);
return Result.ok(result.getValue());
} | the_stack |
import {SearchableProps} from './ui';
import {Logger} from 'flipper-common';
import {
Searchable,
Button,
ButtonGroup,
FlexBox,
FlexColumn,
FlexRow,
Glyph,
ContextMenu,
styled,
colors,
} from './ui';
import {PluginDefinition, DevicePluginMap, ClientPluginMap} from './plugin';
import {connect} from 'react-redux';
import React, {Component, Fragment} from 'react';
import {
PluginNotification,
updatePluginBlocklist,
updateCategoryBlocklist,
} from './reducers/notifications';
import {selectPlugin} from './reducers/connections';
import {State as StoreState} from './reducers/index';
import {textContent} from 'flipper-plugin';
import createPaste from './fb-stubs/createPaste';
import {getPluginTitle} from './utils/pluginUtils';
import {getFlipperLib} from 'flipper-plugin';
type OwnProps = {
onClear: () => void;
selectedID: string | null | undefined;
logger: Logger;
} & Partial<SearchableProps>;
type StateFromProps = {
activeNotifications: Array<PluginNotification>;
invalidatedNotifications: Array<PluginNotification>;
blocklistedPlugins: Array<string>;
blocklistedCategories: Array<string>;
devicePlugins: DevicePluginMap;
clientPlugins: ClientPluginMap;
};
type DispatchFromProps = {
selectPlugin: typeof selectPlugin;
updatePluginBlocklist: (blocklist: Array<string>) => any;
updateCategoryBlocklist: (blocklist: Array<string>) => any;
};
type Props = OwnProps & StateFromProps & DispatchFromProps;
type State = {
selectedNotification: string | null | undefined;
};
const Content = styled(FlexColumn)({
padding: '0 10px',
backgroundColor: colors.light02,
overflow: 'scroll',
flexGrow: 1,
});
const Heading = styled(FlexBox)({
display: 'block',
alignItems: 'center',
marginTop: 15,
marginBottom: 5,
color: colors.macOSSidebarSectionTitle,
fontSize: 11,
fontWeight: 500,
textOverflow: 'ellipsis',
overflow: 'hidden',
whiteSpace: 'nowrap',
flexShrink: 0,
});
const NoContent = styled(FlexColumn)({
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
flexGrow: 1,
fontWeight: 500,
lineHeight: 2.5,
color: colors.light30,
});
class NotificationsTable extends Component<Props & SearchableProps, State> {
contextMenuItems = [{label: 'Clear all', click: this.props.onClear}];
state: State = {
selectedNotification: this.props.selectedID,
};
componentDidUpdate(prevProps: Props & SearchableProps) {
if (this.props.filters.length !== prevProps.filters.length) {
this.props.updatePluginBlocklist(
this.props.filters
.filter(
(f) => f.type === 'exclude' && f.key.toLowerCase() === 'plugin',
)
.map((f) => String(f.value)),
);
this.props.updateCategoryBlocklist(
this.props.filters
.filter(
(f) => f.type === 'exclude' && f.key.toLowerCase() === 'category',
)
.map((f) => String(f.value)),
);
}
if (
this.props.selectedID &&
prevProps.selectedID !== this.props.selectedID
) {
this.setState({
selectedNotification: this.props.selectedID,
});
}
}
onHidePlugin = (pluginId: string) => {
// add filter to searchbar
this.props.addFilter({
value: pluginId,
type: 'exclude',
key: 'plugin',
});
this.props.updatePluginBlocklist(
this.props.blocklistedPlugins.concat(pluginId),
);
};
onHideCategory = (category: string) => {
// add filter to searchbar
this.props.addFilter({
value: category,
type: 'exclude',
key: 'category',
});
this.props.updatePluginBlocklist(
this.props.blocklistedCategories.concat(category),
);
};
getFilter =
(): ((n: PluginNotification) => boolean) => (n: PluginNotification) => {
const searchTerm = this.props.searchTerm.toLowerCase();
// filter plugins
const blocklistedPlugins = new Set(
this.props.blocklistedPlugins.map((p) => p.toLowerCase()),
);
if (blocklistedPlugins.has(n.pluginId.toLowerCase())) {
return false;
}
// filter categories
const {category} = n.notification;
if (category) {
const blocklistedCategories = new Set(
this.props.blocklistedCategories.map((p) => p.toLowerCase()),
);
if (blocklistedCategories.has(category.toLowerCase())) {
return false;
}
}
if (searchTerm.length === 0) {
return true;
} else if (n.notification.title.toLowerCase().indexOf(searchTerm) > -1) {
return true;
} else if (
typeof n.notification.message === 'string' &&
n.notification.message.toLowerCase().indexOf(searchTerm) > -1
) {
return true;
}
return false;
};
getPlugin = (id: string) =>
this.props.clientPlugins.get(id) || this.props.devicePlugins.get(id);
render() {
const activeNotifications = this.props.activeNotifications
.filter(this.getFilter())
.map((n: PluginNotification) => {
const {category} = n.notification;
return (
<NotificationItem
key={n.notification.id}
{...n}
plugin={this.getPlugin(n.pluginId)}
isSelected={this.state.selectedNotification === n.notification.id}
onHighlight={() =>
this.setState({selectedNotification: n.notification.id})
}
onClear={this.props.onClear}
onHidePlugin={() => this.onHidePlugin(n.pluginId)}
onHideCategory={
category ? () => this.onHideCategory(category) : undefined
}
selectPlugin={this.props.selectPlugin}
logger={this.props.logger}
/>
);
})
.reverse();
const invalidatedNotifications = this.props.invalidatedNotifications
.filter(this.getFilter())
.map((n: PluginNotification) => (
<NotificationItem
key={n.notification.id}
{...n}
plugin={this.getPlugin(n.pluginId)}
onClear={this.props.onClear}
inactive
/>
))
.reverse();
return (
<ContextMenu items={this.contextMenuItems} component={Content}>
{activeNotifications.length > 0 && (
<Fragment>
<Heading>Active notifications</Heading>
<FlexColumn shrink={false}>{activeNotifications}</FlexColumn>
</Fragment>
)}
{invalidatedNotifications.length > 0 && (
<Fragment>
<Heading>Past notifications</Heading>
<FlexColumn shrink={false}>{invalidatedNotifications}</FlexColumn>
</Fragment>
)}
{activeNotifications.length + invalidatedNotifications.length === 0 && (
<NoContent>
<Glyph
name="bell-null"
size={24}
variant="outline"
color={colors.light30}
/>
No Notifications
</NoContent>
)}
</ContextMenu>
);
}
}
export const ConnectedNotificationsTable = connect<
StateFromProps,
DispatchFromProps,
OwnProps,
StoreState
>(
({
notifications: {
activeNotifications,
invalidatedNotifications,
blocklistedPlugins,
blocklistedCategories,
},
plugins: {devicePlugins, clientPlugins},
}) => ({
activeNotifications,
invalidatedNotifications,
blocklistedPlugins,
blocklistedCategories,
devicePlugins,
clientPlugins,
}),
{
updatePluginBlocklist,
updateCategoryBlocklist,
selectPlugin,
},
)(Searchable(NotificationsTable));
const shadow = (
props: {isSelected?: boolean; inactive?: boolean},
_hover?: boolean,
) => {
if (props.inactive) {
return `inset 0 0 0 1px ${colors.light10}`;
}
const shadow = ['1px 1px 5px rgba(0,0,0,0.1)'];
if (props.isSelected) {
shadow.push(`inset 0 0 0 2px ${colors.macOSTitleBarIconSelected}`);
}
return shadow.join(',');
};
const SEVERITY_COLOR_MAP = {
warning: colors.yellow,
error: colors.red,
};
type NotificationBoxProps = {
inactive?: boolean;
isSelected?: boolean;
severity: keyof typeof SEVERITY_COLOR_MAP;
};
const NotificationBox = styled(FlexRow)<NotificationBoxProps>((props) => ({
backgroundColor: props.inactive ? 'transparent' : colors.white,
opacity: props.inactive ? 0.5 : 1,
alignItems: 'flex-start',
borderRadius: 5,
padding: 10,
flexShrink: 0,
overflow: 'hidden',
position: 'relative',
marginBottom: 10,
boxShadow: shadow(props),
'::before': {
content: '""',
display: !props.inactive && !props.isSelected ? 'block' : 'none',
position: 'absolute',
left: 0,
top: 0,
bottom: 0,
width: 3,
backgroundColor: SEVERITY_COLOR_MAP[props.severity] || colors.info,
},
':hover': {
boxShadow: shadow(props, true),
'& > *': {
opacity: 1,
},
},
}));
const Title = styled.div({
minWidth: 150,
color: colors.light80,
flexShrink: 0,
marginBottom: 6,
fontWeight: 500,
lineHeight: 1,
fontSize: '1.1em',
});
const NotificationContent = styled(FlexColumn)<{isSelected?: boolean}>(
(props) => ({
marginLeft: 6,
marginRight: 10,
flexGrow: 1,
overflow: 'hidden',
maxHeight: props.isSelected ? 'none' : 56,
lineHeight: 1.4,
color: props.isSelected ? colors.light50 : colors.light30,
userSelect: 'text',
}),
);
const Actions = styled(FlexRow)({
alignItems: 'center',
justifyContent: 'space-between',
color: colors.light20,
marginTop: 12,
borderTop: `1px solid ${colors.light05}`,
paddingTop: 8,
});
const NotificationButton = styled.div({
border: `1px solid ${colors.light20}`,
color: colors.light50,
borderRadius: 4,
textAlign: 'center',
padding: 4,
width: 80,
marginBottom: 4,
opacity: 0,
transition: '0.15s opacity',
'[data-role="notification"]:hover &': {
opacity: 0.5,
},
':last-child': {
marginBottom: 0,
},
'[data-role="notification"] &:hover': {
opacity: 1,
},
});
type ItemProps = {
onHighlight?: () => any;
onHidePlugin?: () => any;
onHideCategory?: () => any;
onClear?: () => any;
isSelected?: boolean;
inactive?: boolean;
selectPlugin?: typeof selectPlugin;
logger?: Logger;
plugin: PluginDefinition | null | undefined;
};
type ItemState = {
reportedNotHelpful: boolean;
};
class NotificationItem extends Component<
ItemProps & PluginNotification,
ItemState
> {
constructor(props: ItemProps & PluginNotification) {
super(props);
const items: Array<Electron.MenuItemConstructorOptions> = [];
if (props.onHidePlugin && props.plugin) {
items.push({
label: `Hide ${getPluginTitle(props.plugin)} plugin`,
click: this.props.onHidePlugin,
});
}
if (props.onHideCategory) {
items.push({
label: 'Hide Similar',
click: this.props.onHideCategory,
});
}
items.push(
{label: 'Copy', role: 'copy'},
{label: 'Copy All', click: this.copy},
{label: 'Create Paste', click: this.createPaste},
);
this.contextMenuItems = items;
}
state = {reportedNotHelpful: false};
contextMenuItems: Array<Electron.MenuItemConstructorOptions>;
deepLinkButton = React.createRef();
createPaste = () => {
createPaste(this.getContent());
};
copy = () => getFlipperLib().writeTextToClipboard(this.getContent());
getContent = (): string =>
[
this.props.notification.timestamp,
`[${this.props.notification.severity}] ${this.props.notification.title}`,
this.props.notification.action,
this.props.notification.category,
textContent(this.props.notification.message),
]
.filter(Boolean)
.join('\n');
openDeeplink = () => {
const {notification, pluginId, client} = this.props;
if (this.props.selectPlugin && notification.action) {
this.props.selectPlugin({
selectedPlugin: pluginId,
selectedAppId: client,
deepLinkPayload: notification.action,
});
}
};
reportNotUseful = (e: React.MouseEvent<any>) => {
e.preventDefault();
e.stopPropagation();
if (this.props.logger) {
this.props.logger.track(
'usage',
'notification-not-useful',
this.props.notification,
);
}
this.setState({reportedNotHelpful: true});
};
onHide = (e: React.MouseEvent<any>) => {
e.preventDefault();
e.stopPropagation();
if (this.props.onHideCategory) {
this.props.onHideCategory();
} else if (this.props.onHidePlugin) {
this.props.onHidePlugin();
}
};
render() {
const {
notification,
isSelected,
inactive,
onHidePlugin,
onHideCategory,
plugin,
} = this.props;
const {action} = notification;
return (
<ContextMenu<React.ComponentProps<typeof NotificationBox>>
data-role="notification"
component={NotificationBox}
severity={notification.severity}
onClick={this.props.onHighlight}
isSelected={isSelected}
inactive={inactive}
items={this.contextMenuItems}>
<Glyph name={(plugin ? plugin.icon : 'bell') || 'bell'} size={12} />
<NotificationContent isSelected={isSelected}>
<Title>{notification.title}</Title>
{notification.message}
{!inactive &&
isSelected &&
plugin &&
(action || onHidePlugin || onHideCategory) && (
<Actions>
<FlexRow>
{action && (
<Button onClick={this.openDeeplink}>
Open in {getPluginTitle(plugin)}
</Button>
)}
<ButtonGroup>
{onHideCategory && (
<Button onClick={onHideCategory}>Hide similar</Button>
)}
{onHidePlugin && (
<Button onClick={onHidePlugin}>
Hide {getPluginTitle(plugin)}
</Button>
)}
</ButtonGroup>
</FlexRow>
<span>
{notification.timestamp
? new Date(notification.timestamp).toTimeString()
: ''}
</span>
</Actions>
)}
</NotificationContent>
{action && !inactive && !isSelected && (
<FlexColumn style={{alignSelf: 'center'}}>
{action && (
<NotificationButton onClick={this.openDeeplink}>
Open
</NotificationButton>
)}
{this.state.reportedNotHelpful ? (
<NotificationButton onClick={this.onHide}>
Hide
</NotificationButton>
) : (
<NotificationButton onClick={this.reportNotUseful}>
Not helpful
</NotificationButton>
)}
</FlexColumn>
)}
</ContextMenu>
);
}
} | the_stack |
import { expect } from "chai";
import { Util, ICommandActions, ICommandParameters } from "../src/util";
import { AppserviceMock } from "./mocks/appservicemock";
// we are a test file and thus need those
/* tslint:disable:no-unused-expression max-file-line-count no-any */
function CreateMockIntent(members): any {
const as = new AppserviceMock({
roommembers: members.map((member) =>
({
content: {
displayname: member.displayname,
},
membership: member.membership,
stateKey: member.mxid,
}),
),
});
return as.botIntent;
}
describe("Util", () => {
describe("MsgToArgs", () => {
it("parses arguments", () => {
const {command, args} = Util.MsgToArgs("!matrix command arg1 arg2", "!matrix");
expect(command).to.be.eq("command");
expect(args.length).to.be.eq(2);
expect(args[0]).to.be.eq("arg1");
expect(args[1]).to.be.eq("arg2");
});
});
describe("Command Stuff", () => {
const actions: ICommandActions = {
action: {
description: "floof",
help: "Fox goes floof!",
params: ["param1", "param2"],
run: async ({param1, param2}) => {
return `param1: ${param1}\nparam2: ${param2}`;
},
},
};
const parameters: ICommandParameters = {
param1: {
description: "1",
get: async (param: string) => {
return "param1_" + param;
},
},
param2: {
description: "2",
get: async (param: string) => {
return "param2_" + param;
},
},
};
describe("HandleHelpCommand", () => {
it("handles empty commands", async () => {
const {command, args} = Util.MsgToArgs("!fox help", "!fox");
const retStr = await Util.HandleHelpCommand(
"!fox",
{} as any,
{} as any,
args,
);
expect(retStr).to.equal("No commands found");
});
it("parses general help message", async () => {
const {command, args} = Util.MsgToArgs("!fox help", "!fox");
const retStr = await Util.HandleHelpCommand(
"!fox",
actions,
parameters,
args,
);
expect(retStr).to.equal(
`Available Commands:
- \`!fox action <param1> <param2>\`: floof
Parameters:
- \`<param1>\`: 1
- \`<param2>\`: 2
`);
});
it("parses specific help message", async () => {
const {command, args} = Util.MsgToArgs("!fox help action", "!fox");
const retStr = await Util.HandleHelpCommand(
"!fox",
actions,
parameters,
args,
);
expect(retStr).to.equal(
`\`!fox action <param1> <param2>\`: floof
Fox goes floof!`);
});
});
describe("ParseCommand", () => {
it("parses commands", async () => {
const retStr = await Util.ParseCommand(
"!fox",
"!fox action hello world",
actions,
parameters,
);
expect(retStr).equal("param1: param1_hello\nparam2: param2_world");
});
});
});
describe("GetMxidFromName", () => {
it("Finds a single member", async () => {
const mockUsers = [
{
displayname: "GoodBoy",
membership: "join",
mxid: "@123:localhost",
},
];
const intent = CreateMockIntent(mockUsers);
const mxid = await Util.GetMxidFromName(intent, "goodboy", ["abc"]);
expect(mxid).equal("@123:localhost");
});
it("Errors on multiple members", async () => {
const mockRooms = [
{
displayname: "GoodBoy",
membership: "join",
mxid: "@123:localhost",
},
{
displayname: "GoodBoy",
membership: "join",
mxid: "@456:localhost",
},
];
const intent = CreateMockIntent(mockRooms);
try {
await Util.GetMxidFromName(intent, "goodboy", ["abc"]);
throw new Error("didn't fail");
} catch (e) {
expect(e.message).to.not.equal("didn't fail");
}
});
it("Errors on no member", async () => {
const mockRooms = [
{
displayname: "GoodBoy",
membership: "join",
mxid: "@123:localhost",
},
];
const intent = CreateMockIntent(mockRooms);
try {
await Util.GetMxidFromName(intent, "badboy", ["abc"]);
throw new Error("didn't fail");
} catch (e) {
expect(e.message).to.not.equal("didn't fail");
}
});
});
describe("NumberToHTMLColor", () => {
it("Should handle valid colors", () => {
const COLOR = 0xdeadaf;
const reply = Util.NumberToHTMLColor(COLOR);
expect(reply).to.equal("#deadaf");
});
it("Should reject too large colors", () => {
const COLOR = 0xFFFFFFFF;
const reply = Util.NumberToHTMLColor(COLOR);
expect(reply).to.equal("#ffffff");
});
it("Should reject too small colors", () => {
const COLOR = -1;
const reply = Util.NumberToHTMLColor(COLOR);
expect(reply).to.equal("#000000");
});
});
describe("ApplyPatternString", () => {
it("Should apply simple patterns", () => {
const reply = Util.ApplyPatternString(":name likes :animal", {
animal: "Foxies",
name: "Sorunome",
});
expect(reply).to.equal("Sorunome likes Foxies");
});
it("Should ignore unused tags", () => {
const reply = Util.ApplyPatternString(":name is :thing", {
name: "Sorunome",
});
expect(reply).to.equal("Sorunome is :thing");
});
it("Should do multi-replacements", () => {
const reply = Util.ApplyPatternString(":animal, :animal and :animal", {
animal: "fox",
});
expect(reply).to.equal("fox, fox and fox");
});
});
describe("DelayedPromise", () => {
it("delays for some time", async () => {
const DELAY_FOR = 250;
const t = Date.now();
await Util.DelayedPromise(DELAY_FOR);
expect(Date.now()).to.be.greaterThan(t + DELAY_FOR - 1);
});
});
describe("CheckMatrixPermission", () => {
const PERM_LEVEL = 50;
it("should deny", async () => {
const ret = await Util.CheckMatrixPermission(
{
getRoomStateEvent: async () => {
return {
blah: {
blubb: PERM_LEVEL,
},
};
},
} as any,
"@user:localhost",
"",
PERM_LEVEL,
"blah",
"blubb",
);
expect(ret).to.be.false;
});
it("should allow cat/subcat", async () => {
const ret = await Util.CheckMatrixPermission(
{
getRoomStateEvent: async () => {
return {
blah: {
blubb: PERM_LEVEL,
},
users: {
"@user:localhost": PERM_LEVEL,
},
};
},
} as any,
"@user:localhost",
"",
PERM_LEVEL,
"blah",
"blubb",
);
expect(ret).to.be.true;
});
it("should allow cat", async () => {
const ret = await Util.CheckMatrixPermission(
{
getRoomStateEvent: async () => {
return {
blah: PERM_LEVEL,
users: {
"@user:localhost": PERM_LEVEL,
},
};
},
} as any,
"@user:localhost",
"",
PERM_LEVEL,
"blah",
);
expect(ret).to.be.true;
});
it("should allow based on default", async () => {
const ret = await Util.CheckMatrixPermission(
{
getRoomStateEvent: async () => {
return {
blah: PERM_LEVEL,
users_default: PERM_LEVEL,
};
},
} as any,
"@user:localhost",
"",
PERM_LEVEL,
"blah",
);
expect(ret).to.be.true;
});
});
describe("EscapeStringForUserId", () => {
it("should encode a string properly", () => {
expect(Util.EscapeStringForUserId("ThisIsAString")).to
.equal("=54his=49s=41=53tring");
expect(Util.EscapeStringForUserId('1!2"3£4$5%6^7&8*9(0)')).to
.equal("1=212=223=a34=245=256=5e7=268=2a9=280=29");
});
it("should not-reencode a string", () => {
expect(Util.EscapeStringForUserId("=54his=49s=41=53tring")).to
.equal("=54his=49s=41=53tring");
expect(Util.EscapeStringForUserId("1=212=223=a34=245=256=5e7=268=2a9=280=29")).to
.equal("1=212=223=a34=245=256=5e7=268=2a9=280=29");
});
});
}); | the_stack |
import BigNumber from 'bignumber.js';
import { TransactionObject } from 'web3/eth/types';
import { OrderMapper } from '@dydxprotocol/exchange-wrappers';
import { LimitOrders } from '../LimitOrders';
import { StopLimitOrders } from '../StopLimitOrders';
import { CanonicalOrders } from '../CanonicalOrders';
import { Contracts } from '../../lib/Contracts';
import {
AmountReference,
AmountDenomination,
AccountAction,
Deposit,
Withdraw,
ActionType,
ActionArgs,
SendOptions,
TxResult,
Buy,
Sell,
Exchange,
Transfer,
Trade,
Liquidate,
Vaporize,
AccountInfo,
OperationAuthorization,
SetExpiry,
SetExpiryV2,
SetApprovalForExpiryV2,
ExpiryV2CallFunctionType,
Refund,
DaiMigrate,
AccountActionWithOrder,
Call,
Amount,
Decimal,
Integer,
AccountOperationOptions,
ConfirmationType,
address,
LimitOrder,
SignedLimitOrder,
StopLimitOrder,
SignedStopLimitOrder,
CanonicalOrder,
SignedCanonicalOrder,
LimitOrderCallFunctionType,
ProxyType,
Operation,
SignedOperation,
Action,
} from '../../types';
import {
addressesAreEqual,
bytesToHexString,
hexStringToBytes,
toBytes,
} from '../../lib/BytesHelper';
import { toNumber } from '../../lib/Helpers';
import { ADDRESSES, INTEGERS } from '../../lib/Constants';
import expiryConstants from '../../lib/expiry-constants.json';
interface OptionalActionArgs {
actionType: number | string;
primaryMarketId?: number | string;
secondaryMarketId?: number | string;
otherAddress?: string;
otherAccountId?: number;
data?: (string | number[])[];
amount?: Amount;
}
export class AccountOperation {
private contracts: Contracts;
private actions: ActionArgs[];
private committed: boolean;
private orderMapper: OrderMapper;
private limitOrders: LimitOrders;
private stopLimitOrders: StopLimitOrders;
private canonicalOrders: CanonicalOrders;
private accounts: AccountInfo[];
private proxy: ProxyType;
private sendEthTo: address;
private auths: OperationAuthorization[];
private networkId: number;
constructor(
contracts: Contracts,
orderMapper: OrderMapper,
limitOrders: LimitOrders,
stopLimitOrders: StopLimitOrders,
canonicalOrders: CanonicalOrders,
networkId: number,
options: AccountOperationOptions,
) {
// use the passed-in proxy type, but support the old way of passing in `usePayableProxy = true`
const proxy =
options.proxy ||
(options.usePayableProxy ? ProxyType.Payable : null) ||
ProxyType.None;
this.contracts = contracts;
this.actions = [];
this.committed = false;
this.orderMapper = orderMapper;
this.limitOrders = limitOrders;
this.stopLimitOrders = stopLimitOrders;
this.canonicalOrders = canonicalOrders;
this.accounts = [];
this.proxy = proxy;
this.sendEthTo = options.sendEthTo;
this.auths = [];
this.networkId = networkId;
}
public deposit(deposit: Deposit): AccountOperation {
this.addActionArgs(
deposit,
{
actionType: ActionType.Deposit,
amount: deposit.amount,
otherAddress: deposit.from,
primaryMarketId: deposit.marketId.toFixed(0),
},
);
return this;
}
public withdraw(withdraw: Withdraw): AccountOperation {
this.addActionArgs(
withdraw,
{
amount: withdraw.amount,
actionType: ActionType.Withdraw,
otherAddress: withdraw.to,
primaryMarketId: withdraw.marketId.toFixed(0),
},
);
return this;
}
public transfer(transfer: Transfer): AccountOperation {
this.addActionArgs(
transfer,
{
actionType: ActionType.Transfer,
amount: transfer.amount,
primaryMarketId: transfer.marketId.toFixed(0),
otherAccountId: this.getAccountId(transfer.toAccountOwner, transfer.toAccountId),
},
);
return this;
}
public buy(buy: Buy): AccountOperation {
return this.exchange(buy, ActionType.Buy);
}
public sell(sell: Sell): AccountOperation {
return this.exchange(sell, ActionType.Sell);
}
public liquidate(liquidate: Liquidate): AccountOperation {
this.addActionArgs(
liquidate,
{
actionType: ActionType.Liquidate,
amount: liquidate.amount,
primaryMarketId: liquidate.liquidMarketId.toFixed(0),
secondaryMarketId: liquidate.payoutMarketId.toFixed(0),
otherAccountId: this.getAccountId(liquidate.liquidAccountOwner, liquidate.liquidAccountId),
},
);
return this;
}
public vaporize(vaporize: Vaporize): AccountOperation {
this.addActionArgs(
vaporize,
{
actionType: ActionType.Vaporize,
amount: vaporize.amount,
primaryMarketId: vaporize.vaporMarketId.toFixed(0),
secondaryMarketId: vaporize.payoutMarketId.toFixed(0),
otherAccountId: this.getAccountId(vaporize.vaporAccountOwner, vaporize.vaporAccountId),
},
);
return this;
}
public setExpiry(args: SetExpiry): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.expiry.options.address,
data: toBytes(args.marketId, args.expiryTime),
},
);
return this;
}
public setApprovalForExpiryV2(args: SetApprovalForExpiryV2): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.expiryV2.options.address,
data: toBytes(
ExpiryV2CallFunctionType.SetApproval,
args.sender,
args.minTimeDelta,
),
},
);
return this;
}
public setExpiryV2(args: SetExpiryV2): AccountOperation {
const callType = toBytes(ExpiryV2CallFunctionType.SetExpiry);
let callData = callType;
callData = callData.concat(toBytes(new BigNumber(64)));
callData = callData.concat(toBytes(new BigNumber(args.expiryV2Args.length)));
for (let i = 0; i < args.expiryV2Args.length; i += 1) {
const expiryV2Arg = args.expiryV2Args[i];
callData = callData.concat(toBytes(
expiryV2Arg.accountOwner,
expiryV2Arg.accountId,
expiryV2Arg.marketId,
expiryV2Arg.timeDelta,
expiryV2Arg.forceUpdate,
));
}
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.expiryV2.options.address,
data: callData,
},
);
return this;
}
public approveLimitOrder(args: AccountActionWithOrder): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.limitOrders.options.address,
data: toBytes(
LimitOrderCallFunctionType.Approve,
this.limitOrders.unsignedOrderToBytes(args.order as LimitOrder),
),
},
);
return this;
}
public cancelLimitOrder(args: AccountActionWithOrder): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.limitOrders.options.address,
data: toBytes(
LimitOrderCallFunctionType.Cancel,
this.limitOrders.unsignedOrderToBytes(args.order as LimitOrder),
),
},
);
return this;
}
public approveStopLimitOrder(args: AccountActionWithOrder): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.stopLimitOrders.options.address,
data: toBytes(
LimitOrderCallFunctionType.Approve,
this.stopLimitOrders.unsignedOrderToBytes(args.order as StopLimitOrder),
),
},
);
return this;
}
public cancelStopLimitOrder(args: AccountActionWithOrder): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.stopLimitOrders.options.address,
data: toBytes(
LimitOrderCallFunctionType.Cancel,
this.stopLimitOrders.unsignedOrderToBytes(args.order as StopLimitOrder),
),
},
);
return this;
}
public approveCanonicalOrder(args: AccountActionWithOrder): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.canonicalOrders.options.address,
data: toBytes(
LimitOrderCallFunctionType.Approve,
this.canonicalOrders.orderToBytes(args.order as CanonicalOrder),
),
},
);
return this;
}
public cancelCanonicalOrder(args: AccountActionWithOrder): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: this.contracts.canonicalOrders.options.address,
data: toBytes(
LimitOrderCallFunctionType.Cancel,
this.canonicalOrders.orderToBytes(args.order as CanonicalOrder),
),
},
);
return this;
}
public setCanonicalOrderFillArgs(
primaryAccountOwner: address,
primaryAccountId: Integer,
price: Decimal,
fee: Decimal,
): AccountOperation {
this.addActionArgs(
{
primaryAccountOwner,
primaryAccountId,
},
{
actionType: ActionType.Call,
otherAddress: this.contracts.canonicalOrders.options.address,
data: toBytes(
LimitOrderCallFunctionType.SetFillArgs,
this.canonicalOrders.toSolidity(price),
this.canonicalOrders.toSolidity(fee.abs()),
fee.isNegative(),
),
},
);
return this;
}
public call(args: Call): AccountOperation {
this.addActionArgs(
args,
{
actionType: ActionType.Call,
otherAddress: args.callee,
data: args.data,
},
);
return this;
}
public trade(trade: Trade): AccountOperation {
this.addActionArgs(
trade,
{
actionType: ActionType.Trade,
amount: trade.amount,
primaryMarketId: trade.inputMarketId.toFixed(0),
secondaryMarketId: trade.outputMarketId.toFixed(0),
otherAccountId: this.getAccountId(trade.otherAccountOwner, trade.otherAccountId),
otherAddress: trade.autoTrader,
data: trade.data,
},
);
return this;
}
public fillSignedLimitOrder(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: SignedLimitOrder,
weiAmount: Integer,
denotedInMakerAmount: boolean = false,
): AccountOperation {
return this.fillLimitOrderInternal(
primaryAccountOwner,
primaryAccountNumber,
order,
weiAmount,
denotedInMakerAmount,
true,
);
}
public fillPreApprovedLimitOrder(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: LimitOrder,
weiAmount: Integer,
denotedInMakerAmount: boolean = false,
): AccountOperation {
return this.fillLimitOrderInternal(
primaryAccountOwner,
primaryAccountNumber,
order,
weiAmount,
denotedInMakerAmount,
false,
);
}
public fillSignedDecreaseOnlyStopLimitOrder(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: SignedStopLimitOrder,
denotedInMakerAmount: boolean = false,
): AccountOperation {
const amount: Amount = {
denomination: AmountDenomination.Par,
reference: AmountReference.Target,
value: INTEGERS.ZERO,
};
return this.fillStopLimitOrderInternal(
primaryAccountOwner,
primaryAccountNumber,
order,
amount,
denotedInMakerAmount,
true,
);
}
public fillSignedStopLimitOrder(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: SignedStopLimitOrder,
weiAmount: Integer,
denotedInMakerAmount: boolean = false,
): AccountOperation {
const amount: Amount = {
denomination: AmountDenomination.Wei,
reference: AmountReference.Delta,
value: weiAmount.abs().times(denotedInMakerAmount ? -1 : 1),
};
return this.fillStopLimitOrderInternal(
primaryAccountOwner,
primaryAccountNumber,
order,
amount,
denotedInMakerAmount,
true,
);
}
public fillPreApprovedStopLimitOrder(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: StopLimitOrder,
weiAmount: Integer,
denotedInMakerAmount: boolean = false,
): AccountOperation {
const amount: Amount = {
denomination: AmountDenomination.Wei,
reference: AmountReference.Delta,
value: weiAmount.abs().times(denotedInMakerAmount ? -1 : 1),
};
return this.fillStopLimitOrderInternal(
primaryAccountOwner,
primaryAccountNumber,
order,
amount,
denotedInMakerAmount,
false,
);
}
public fillCanonicalOrder(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: CanonicalOrder | SignedCanonicalOrder,
amount: Integer,
price: Decimal,
fee: Decimal,
): AccountOperation {
return this.trade({
primaryAccountOwner,
primaryAccountId: primaryAccountNumber,
autoTrader: this.contracts.canonicalOrders.options.address,
inputMarketId: order.baseMarket,
outputMarketId: order.quoteMarket,
otherAccountOwner: order.makerAccountOwner,
otherAccountId: order.makerAccountNumber,
data: hexStringToBytes(this.canonicalOrders.orderToBytes(order, price, fee)),
amount: {
denomination: AmountDenomination.Wei,
reference: AmountReference.Delta,
value: order.isBuy ? amount : amount.negated(),
},
});
}
public fillDecreaseOnlyCanonicalOrder(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: CanonicalOrder | SignedCanonicalOrder,
price: Decimal,
fee: Decimal,
): AccountOperation {
return this.trade({
primaryAccountOwner,
primaryAccountId: primaryAccountNumber,
autoTrader: this.contracts.canonicalOrders.options.address,
inputMarketId: order.isBuy ? order.baseMarket : order.quoteMarket,
outputMarketId: order.isBuy ? order.quoteMarket : order.baseMarket,
otherAccountOwner: order.makerAccountOwner,
otherAccountId: order.makerAccountNumber,
data: hexStringToBytes(this.canonicalOrders.orderToBytes(order, price, fee)),
amount: {
denomination: AmountDenomination.Par,
reference: AmountReference.Target,
value: INTEGERS.ZERO,
},
});
}
public refund(refundArgs: Refund): AccountOperation {
return this.trade({
primaryAccountOwner: refundArgs.primaryAccountOwner,
primaryAccountId: refundArgs.primaryAccountId,
inputMarketId: refundArgs.refundMarketId,
outputMarketId: refundArgs.otherMarketId,
otherAccountOwner: refundArgs.receiverAccountOwner,
otherAccountId: refundArgs.receiverAccountId,
amount: {
value: refundArgs.wei,
denomination: AmountDenomination.Actual,
reference: AmountReference.Delta,
},
data: [],
autoTrader: this.contracts.refunder.options.address,
});
}
public daiMigrate(migrateArgs: DaiMigrate): AccountOperation {
const saiMarket = new BigNumber(1);
const daiMarket = new BigNumber(3);
return this.trade({
primaryAccountOwner: migrateArgs.primaryAccountOwner,
primaryAccountId: migrateArgs.primaryAccountId,
inputMarketId: saiMarket,
outputMarketId: daiMarket,
otherAccountOwner: migrateArgs.userAccountOwner,
otherAccountId: migrateArgs.userAccountId,
amount: migrateArgs.amount,
data: [],
autoTrader: this.contracts.daiMigrator.options.address,
});
}
public liquidateExpiredAccount(liquidate: Liquidate, maxExpiry?: Integer): AccountOperation {
return this.liquidateExpiredAccountInternal(
liquidate,
maxExpiry || INTEGERS.ONES_31,
this.contracts.expiry.options.address,
);
}
public liquidateExpiredAccountV2(liquidate: Liquidate, maxExpiry?: Integer): AccountOperation {
return this.liquidateExpiredAccountInternal(
liquidate,
maxExpiry || INTEGERS.ONES_31,
this.contracts.expiryV2.options.address,
);
}
private liquidateExpiredAccountInternal(
liquidate: Liquidate,
maxExpiryTimestamp: Integer,
contractAddress: address,
): AccountOperation {
this.addActionArgs(
liquidate,
{
actionType: ActionType.Trade,
amount: liquidate.amount,
primaryMarketId: liquidate.liquidMarketId.toFixed(0),
secondaryMarketId: liquidate.payoutMarketId.toFixed(0),
otherAccountId: this.getAccountId(liquidate.liquidAccountOwner, liquidate.liquidAccountId),
otherAddress: contractAddress,
data: toBytes(liquidate.liquidMarketId, maxExpiryTimestamp),
},
);
return this;
}
public fullyLiquidateExpiredAccount(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
expiredAccountOwner: address,
expiredAccountNumber: Integer,
expiredMarket: Integer,
expiryTimestamp: Integer,
blockTimestamp: Integer,
weis: Integer[],
prices: Integer[],
spreadPremiums: Integer[],
collateralPreferences: Integer[],
): AccountOperation {
return this.fullyLiquidateExpiredAccountInternal(
primaryAccountOwner,
primaryAccountNumber,
expiredAccountOwner,
expiredAccountNumber,
expiredMarket,
expiryTimestamp,
blockTimestamp,
weis,
prices,
spreadPremiums,
collateralPreferences,
this.contracts.expiry.options.address,
);
}
public fullyLiquidateExpiredAccountV2(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
expiredAccountOwner: address,
expiredAccountNumber: Integer,
expiredMarket: Integer,
expiryTimestamp: Integer,
blockTimestamp: Integer,
weis: Integer[],
prices: Integer[],
spreadPremiums: Integer[],
collateralPreferences: Integer[],
): AccountOperation {
return this.fullyLiquidateExpiredAccountInternal(
primaryAccountOwner,
primaryAccountNumber,
expiredAccountOwner,
expiredAccountNumber,
expiredMarket,
expiryTimestamp,
blockTimestamp,
weis,
prices,
spreadPremiums,
collateralPreferences,
this.contracts.expiryV2.options.address,
);
}
private fullyLiquidateExpiredAccountInternal(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
expiredAccountOwner: address,
expiredAccountNumber: Integer,
expiredMarket: Integer,
expiryTimestamp: Integer,
blockTimestamp: Integer,
weis: Integer[],
prices: Integer[],
spreadPremiums: Integer[],
collateralPreferences: Integer[],
contractAddress: address,
): AccountOperation {
// hardcoded values
const networkExpiryConstants = expiryConstants[this.networkId];
const defaultSpread = new BigNumber(networkExpiryConstants.spread);
const expiryRampTime = new BigNumber(networkExpiryConstants.expiryRampTime);
// get info about the expired market
let owedWei = weis[expiredMarket.toNumber()];
const owedPrice = prices[expiredMarket.toNumber()];
const owedSpreadMult = spreadPremiums[expiredMarket.toNumber()].plus(1);
// error checking
if (owedWei.gte(0)) {
throw new Error('Expired account must have negative expired balance');
}
if (blockTimestamp.lt(expiryTimestamp)) {
throw new Error('Expiry timestamp must be larger than blockTimestamp');
}
// loop through each collateral type as long as there is some borrow amount left
for (let i = 0; i < collateralPreferences.length && owedWei.lt(0); i += 1) {
// get info about the next collateral market
const heldMarket = collateralPreferences[i];
const heldWei = weis[heldMarket.toNumber()];
const heldPrice = prices[heldMarket.toNumber()];
const heldSpreadMult = spreadPremiums[heldMarket.toNumber()].plus(1);
// skip this collateral market if the account is not positive in this market
if (heldWei.lte(0)) {
continue;
}
// get the relative value of each market
const rampAdjustment = BigNumber.min(
blockTimestamp.minus(expiryTimestamp).div(expiryRampTime),
INTEGERS.ONE,
);
const spread = defaultSpread.times(heldSpreadMult).times(owedSpreadMult).plus(1);
const heldValue = heldWei.times(heldPrice).abs();
const owedValue = owedWei.times(owedPrice).times(rampAdjustment).times(spread).abs();
// add variables that need to be populated
let primaryMarketId: Integer;
let secondaryMarketId: Integer;
// set remaining owedWei and the marketIds depending on which market will 'bound' the action
if (heldValue.gt(owedValue)) {
// we expect no remaining owedWei
owedWei = INTEGERS.ZERO;
primaryMarketId = expiredMarket;
secondaryMarketId = heldMarket;
} else {
// calculate the expected remaining owedWei
owedWei = owedValue.minus(heldValue).div(owedValue).times(owedWei);
primaryMarketId = heldMarket;
secondaryMarketId = expiredMarket;
}
// add the action to the current actions
this.addActionArgs(
{
primaryAccountOwner,
primaryAccountId: primaryAccountNumber,
},
{
actionType: ActionType.Trade,
amount: {
value: INTEGERS.ZERO,
denomination: AmountDenomination.Principal,
reference: AmountReference.Target,
},
primaryMarketId: primaryMarketId.toFixed(0),
secondaryMarketId: secondaryMarketId.toFixed(0),
otherAccountId: this.getAccountId(
expiredAccountOwner,
expiredAccountNumber,
),
otherAddress: contractAddress,
data: toBytes(expiredMarket, expiryTimestamp),
},
);
}
return this;
}
public finalSettlement(
settlement: Liquidate,
): AccountOperation {
this.addActionArgs(
{
primaryAccountOwner: settlement.primaryAccountOwner,
primaryAccountId: settlement.primaryAccountId,
},
{
actionType: ActionType.Trade,
amount: {
value: INTEGERS.ZERO,
denomination: AmountDenomination.Principal,
reference: AmountReference.Target,
},
primaryMarketId: settlement.liquidMarketId.toFixed(0),
secondaryMarketId: settlement.payoutMarketId.toFixed(0),
otherAccountId: this.getAccountId(
settlement.liquidAccountOwner,
settlement.liquidAccountId,
),
otherAddress: this.contracts.finalSettlement.options.address,
data: toBytes(settlement.liquidMarketId),
},
);
return this;
}
/**
* Adds all actions from a SignedOperation and also adds the authorization object that allows the
* proxy to process the actions.
*/
public addSignedOperation(
signedOperation: SignedOperation,
): AccountOperation {
// throw error if operation is not going to use the signed proxy
if (this.proxy !== ProxyType.Signed) {
throw new Error('Cannot add signed operation if not using signed operation proxy');
}
// store the auth
this.auths.push({
startIndex: new BigNumber(this.actions.length),
numActions: new BigNumber(signedOperation.actions.length),
salt: signedOperation.salt,
expiration: signedOperation.expiration,
sender: signedOperation.sender,
signer: signedOperation.signer,
typedSignature: signedOperation.typedSignature,
});
// store the actions
for (let i = 0; i < signedOperation.actions.length; i += 1) {
const action = signedOperation.actions[i];
const secondaryAccountId = action.secondaryAccountOwner === ADDRESSES.ZERO
? 0
: this.getAccountId(
action.secondaryAccountOwner,
action.secondaryAccountNumber,
);
this.addActionArgs(
{
primaryAccountOwner: action.primaryAccountOwner,
primaryAccountId: action.primaryAccountNumber,
},
{
actionType: action.actionType,
primaryMarketId: action.primaryMarketId.toFixed(0),
secondaryMarketId: action.secondaryMarketId.toFixed(0),
otherAddress: action.otherAddress,
otherAccountId: secondaryAccountId,
data: hexStringToBytes(action.data),
amount: {
reference: action.amount.ref,
denomination: action.amount.denomination,
value: action.amount.value.times(action.amount.sign ? 1 : -1),
},
},
);
}
return this;
}
/**
* Takes all current actions/accounts and creates an Operation struct that can then be signed and
* later used with the SignedOperationProxy.
*/
public createSignableOperation(
options: {
expiration?: Integer,
salt?: Integer,
sender?: address,
signer?: address,
} = {},
): Operation {
if (this.auths.length) {
throw new Error('Cannot create operation out of operation with auths');
}
if (!this.actions.length) {
throw new Error('Cannot create operation out of operation with no actions');
}
function actionArgsToAction(action: ActionArgs): Action {
const secondaryAccount: AccountInfo = (
action.actionType === ActionType.Transfer ||
action.actionType === ActionType.Trade ||
action.actionType === ActionType.Liquidate ||
action.actionType === ActionType.Vaporize
)
? this.accounts[action.otherAccountId]
: { owner: ADDRESSES.ZERO, number: '0' };
return {
actionType: toNumber(action.actionType),
primaryAccountOwner: this.accounts[action.accountId].owner,
primaryAccountNumber: new BigNumber(this.accounts[action.accountId].number),
secondaryAccountOwner: secondaryAccount.owner,
secondaryAccountNumber: new BigNumber(secondaryAccount.number),
primaryMarketId: new BigNumber(action.primaryMarketId),
secondaryMarketId: new BigNumber(action.secondaryMarketId),
amount: {
sign: action.amount.sign,
ref: toNumber(action.amount.ref),
denomination: toNumber(action.amount.denomination),
value: new BigNumber(action.amount.value),
},
otherAddress: action.otherAddress,
data: bytesToHexString(action.data),
};
}
const actions: Action[] = this.actions.map(actionArgsToAction.bind(this));
return {
actions,
expiration: options.expiration || INTEGERS.ZERO,
salt: options.salt || INTEGERS.ZERO,
sender: options.sender || ADDRESSES.ZERO,
signer: options.signer || this.accounts[0].owner,
};
}
/**
* Commits the operation to the chain by sending a transaction.
*/
public async commit(
options?: SendOptions,
): Promise<TxResult> {
if (this.committed) {
throw new Error('Operation already committed');
}
if (this.actions.length === 0) {
throw new Error('No actions have been added to operation');
}
if (options && options.confirmationType !== ConfirmationType.Simulate) {
this.committed = true;
}
try {
let method: TransactionObject<void>;
switch (this.proxy) {
case ProxyType.None:
method = this.contracts.soloMargin.methods.operate(
this.accounts,
this.actions,
);
break;
case ProxyType.Payable:
method = this.contracts.payableProxy.methods.operate(
this.accounts,
this.actions,
this.sendEthTo || (options && options.from) || this.contracts.payableProxy.options.from,
);
break;
case ProxyType.Signed:
method = this.contracts.signedOperationProxy.methods.operate(
this.accounts,
this.actions,
this.generateAuthData(),
);
break;
default:
throw new Error(`Invalid proxy type: ${this.proxy}`);
}
return this.contracts.send(
method,
options,
);
} catch (error) {
this.committed = false;
throw error;
}
}
// ============ Private Helper Functions ============
/**
* Internal logic for filling limit orders (either signed or pre-approved orders)
*/
private fillLimitOrderInternal(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: LimitOrder,
weiAmount: Integer,
denotedInMakerAmount: boolean,
isSignedOrder: boolean,
): AccountOperation {
const dataString = isSignedOrder
? this.limitOrders.signedOrderToBytes(order as SignedLimitOrder)
: this.limitOrders.unsignedOrderToBytes(order);
const amount = weiAmount.abs().times(denotedInMakerAmount ? -1 : 1);
return this.trade({
primaryAccountOwner,
primaryAccountId: primaryAccountNumber,
autoTrader: this.contracts.limitOrders.options.address,
inputMarketId: denotedInMakerAmount ? order.makerMarket : order.takerMarket,
outputMarketId: denotedInMakerAmount ? order.takerMarket : order.makerMarket,
otherAccountOwner: order.makerAccountOwner,
otherAccountId: order.makerAccountNumber,
amount: {
denomination: AmountDenomination.Wei,
reference: AmountReference.Delta,
value: amount,
},
data: hexStringToBytes(dataString),
});
}
/**
* Internal logic for filling stop-limit orders (either signed or pre-approved orders)
*/
private fillStopLimitOrderInternal(
primaryAccountOwner: address,
primaryAccountNumber: Integer,
order: StopLimitOrder,
amount: Amount,
denotedInMakerAmount: boolean,
isSignedOrder: boolean,
): AccountOperation {
const dataString = isSignedOrder
? this.stopLimitOrders.signedOrderToBytes(order as SignedStopLimitOrder)
: this.stopLimitOrders.unsignedOrderToBytes(order);
return this.trade({
amount,
primaryAccountOwner,
primaryAccountId: primaryAccountNumber,
autoTrader: this.contracts.stopLimitOrders.options.address,
inputMarketId: denotedInMakerAmount ? order.makerMarket : order.takerMarket,
outputMarketId: denotedInMakerAmount ? order.takerMarket : order.makerMarket,
otherAccountOwner: order.makerAccountOwner,
otherAccountId: order.makerAccountNumber,
data: hexStringToBytes(dataString),
});
}
private exchange(exchange: Exchange, actionType: ActionType): AccountOperation {
const {
bytes,
exchangeWrapperAddress,
}: {
bytes: number[],
exchangeWrapperAddress: string,
} = this.orderMapper.mapOrder(exchange.order);
const [primaryMarketId, secondaryMarketId] =
actionType === ActionType.Buy ?
[exchange.makerMarketId, exchange.takerMarketId] :
[exchange.takerMarketId, exchange.makerMarketId];
const orderData = bytes.map((a :number): number[] => [a]);
this.addActionArgs(
exchange,
{
actionType,
amount: exchange.amount,
otherAddress: exchangeWrapperAddress,
data: orderData,
primaryMarketId: primaryMarketId.toFixed(0),
secondaryMarketId: secondaryMarketId.toFixed(0),
},
);
return this;
}
private addActionArgs(
action: AccountAction,
args: OptionalActionArgs,
): void {
if (this.committed) {
throw new Error('Operation already committed');
}
const amount = args.amount ? {
sign: !args.amount.value.isNegative(),
denomination: args.amount.denomination,
ref: args.amount.reference,
value: args.amount.value.abs().toFixed(0),
} : {
sign: false,
denomination: 0,
ref: 0,
value: 0,
};
const actionArgs: ActionArgs = {
amount,
accountId: this.getPrimaryAccountId(action),
actionType: args.actionType,
primaryMarketId: args.primaryMarketId || '0',
secondaryMarketId: args.secondaryMarketId || '0',
otherAddress: args.otherAddress || ADDRESSES.ZERO,
otherAccountId: args.otherAccountId || '0',
data: args.data || [],
};
this.actions.push(actionArgs);
}
private getPrimaryAccountId(operation: AccountAction): number {
return this.getAccountId(operation.primaryAccountOwner, operation.primaryAccountId);
}
private getAccountId(accountOwner: string, accountNumber: Integer): number {
const accountInfo: AccountInfo = {
owner: accountOwner,
number: accountNumber.toFixed(0),
};
const correctIndex = (i: AccountInfo) =>
(addressesAreEqual(i.owner, accountInfo.owner) && i.number === accountInfo.number);
const index = this.accounts.findIndex(correctIndex);
if (index >= 0) {
return index;
}
this.accounts.push(accountInfo);
return this.accounts.length - 1;
}
private generateAuthData(): {
numActions: string,
header: {
expiration: string,
salt: string,
sender: string,
signer: string,
},
signature: number[][],
}[] {
let actionIndex: Integer = INTEGERS.ZERO;
const result = [];
const emptyAuth = {
numActions: '0',
header: {
expiration: '0',
salt: '0',
sender: ADDRESSES.ZERO,
signer: ADDRESSES.ZERO,
},
signature: [],
};
// for each signed auth
for (let i = 0; i < this.auths.length; i += 1) {
const auth = this.auths[i];
// if empty auth needed, push it
if (auth.startIndex.gt(actionIndex)) {
result.push({
...emptyAuth,
numActions: auth.startIndex.minus(actionIndex).toFixed(0),
});
}
// push this auth
result.push({
numActions: auth.numActions.toFixed(0),
header: {
expiration: auth.expiration.toFixed(0),
salt: auth.salt.toFixed(0),
sender: auth.sender,
signer: auth.signer,
},
signature: toBytes(auth.typedSignature),
});
// update the action index
actionIndex = auth.startIndex.plus(auth.numActions);
}
// push a final empty auth if necessary
if (actionIndex.lt(this.actions.length)) {
result.push({
...emptyAuth,
numActions: new BigNumber(this.actions.length).minus(actionIndex).toFixed(0),
});
}
return result;
}
} | the_stack |
'use strict';
import * as strings from 'vs/base/common/strings';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { FindMatch, EndOfLinePreference } from 'vs/editor/common/editorCommon';
import { CharCode } from 'vs/base/common/charCode';
import { TextModel } from 'vs/editor/common/model/textModel';
const LIMIT_FIND_COUNT = 999;
export class SearchParams {
public readonly searchString: string;
public readonly isRegex: boolean;
public readonly matchCase: boolean;
public readonly wholeWord: boolean;
constructor(searchString: string, isRegex: boolean, matchCase: boolean, wholeWord: boolean) {
this.searchString = searchString;
this.isRegex = isRegex;
this.matchCase = matchCase;
this.wholeWord = wholeWord;
}
private static _isMultilineRegexSource(searchString: string): boolean {
if (!searchString || searchString.length === 0) {
return false;
}
for (let i = 0, len = searchString.length; i < len; i++) {
const chCode = searchString.charCodeAt(i);
if (chCode === CharCode.Backslash) {
// move to next char
i++;
if (i >= len) {
// string ends with a \
break;
}
const nextChCode = searchString.charCodeAt(i);
if (nextChCode === CharCode.n || nextChCode === CharCode.r) {
return true;
}
}
}
return false;
}
public parseSearchRequest(): SearchData {
if (this.searchString === '') {
return null;
}
// Try to create a RegExp out of the params
let multiline: boolean;
if (this.isRegex) {
multiline = SearchParams._isMultilineRegexSource(this.searchString);
} else {
multiline = (this.searchString.indexOf('\n') >= 0);
}
let regex: RegExp = null;
try {
regex = strings.createRegExp(this.searchString, this.isRegex, {
matchCase: this.matchCase,
wholeWord: this.wholeWord,
multiline,
global: true
});
} catch (err) {
return null;
}
if (!regex) {
return null;
}
let canUseSimpleSearch = (!this.isRegex && !this.wholeWord && !multiline);
if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {
// casing might make a difference
canUseSimpleSearch = this.matchCase;
}
return new SearchData(regex, canUseSimpleSearch ? this.searchString : null);
}
}
export class SearchData {
/**
* The regex to search for. Always defined.
*/
public readonly regex: RegExp;
/**
* The simple string to search for (if possible).
*/
public readonly simpleSearch: string;
constructor(regex: RegExp, simpleSearch: string) {
this.regex = regex;
this.simpleSearch = simpleSearch;
}
}
function createFindMatch(range: Range, rawMatches: RegExpExecArray, captureMatches: boolean): FindMatch {
if (!captureMatches) {
return new FindMatch(range, null);
}
let matches: string[] = [];
for (let i = 0, len = rawMatches.length; i < len; i++) {
matches[i] = rawMatches[i];
}
return new FindMatch(range, matches);
}
export class TextModelSearch {
public static findMatches(model: TextModel, searchParams: SearchParams, searchRange: Range, captureMatches: boolean, limitResultCount: number): FindMatch[] {
const searchData = searchParams.parseSearchRequest();
if (!searchData) {
return [];
}
if (searchData.regex.multiline) {
return this._doFindMatchesMultiline(model, searchRange, searchData.regex, captureMatches, limitResultCount);
}
return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount);
}
/**
* Multiline search always executes on the lines concatenated with \n.
* We must therefore compensate for the count of \n in case the model is CRLF
*/
private static _getMultilineMatchRange(model: TextModel, deltaOffset: number, text: string, matchIndex: number, match0: string): Range {
let startOffset: number;
if (model.getEOL() === '\r\n') {
let lineFeedCountBeforeMatch = 0;
for (let i = 0; i < matchIndex; i++) {
let chCode = text.charCodeAt(i);
if (chCode === CharCode.LineFeed) {
lineFeedCountBeforeMatch++;
}
}
startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */;
} else {
startOffset = deltaOffset + matchIndex;
}
let endOffset: number;
if (model.getEOL() === '\r\n') {
let lineFeedCountInMatch = 0;
for (let i = 0, len = match0.length; i < len; i++) {
let chCode = text.charCodeAt(i + matchIndex);
if (chCode === CharCode.LineFeed) {
lineFeedCountInMatch++;
}
}
endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */;
} else {
endOffset = startOffset + match0.length;
}
const startPosition = model.getPositionAt(startOffset);
const endPosition = model.getPositionAt(endOffset);
return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
}
private static _doFindMatchesMultiline(model: TextModel, searchRange: Range, searchRegex: RegExp, captureMatches: boolean, limitResultCount: number): FindMatch[] {
const deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
// We always execute multiline search over the lines joined with \n
// This makes it that \n will match the EOL for both CRLF and LF models
// We compensate for offset errors in `_getMultilineMatchRange`
const text = model.getValueInRange(searchRange, EndOfLinePreference.LF);
const result: FindMatch[] = [];
let prevStartOffset = 0;
let prevEndOffset = 0;
let counter = 0;
let m: RegExpExecArray;
while ((m = searchRegex.exec(text))) {
const startOffset = deltaOffset + m.index;
const endOffset = startOffset + m[0].length;
if (prevStartOffset === startOffset && prevEndOffset === endOffset) {
// Exit early if the regex matches the same range
return result;
}
result[counter++] = createFindMatch(
this._getMultilineMatchRange(model, deltaOffset, text, m.index, m[0]),
m,
captureMatches
);
if (counter >= limitResultCount) {
return result;
}
prevStartOffset = startOffset;
prevEndOffset = endOffset;
}
return result;
}
private static _doFindMatchesLineByLine(model: TextModel, searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): FindMatch[] {
const result: FindMatch[] = [];
let resultLen = 0;
// Early case for a search range that starts & stops on the same line number
if (searchRange.startLineNumber === searchRange.endLineNumber) {
const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
return result;
}
// Collect results from first line
const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
// Collect results from middle lines
for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);
}
// Collect results from last line
if (resultLen < limitResultCount) {
const text = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
resultLen = this._findMatchesInLine(searchData, text, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);
}
return result;
}
private static _findMatchesInLine(searchData: SearchData, text: string, lineNumber: number, deltaOffset: number, resultLen: number, result: FindMatch[], captureMatches: boolean, limitResultCount: number): number {
if (!captureMatches && searchData.simpleSearch) {
const searchString = searchData.simpleSearch;
const searchStringLen = searchString.length;
let lastMatchIndex = -searchStringLen;
while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
const range = new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset);
result[resultLen++] = new FindMatch(range, null);
if (resultLen >= limitResultCount) {
return resultLen;
}
}
return resultLen;
}
const searchRegex = searchData.regex;
let m: RegExpExecArray;
// Reset regex to search from the beginning
searchRegex.lastIndex = 0;
do {
m = searchRegex.exec(text);
if (m) {
const range = new Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset);
if (result.length > 0 && range.equalsRange(result[result.length - 1].range)) {
// Exit early if the regex matches the same range
return resultLen;
}
result[resultLen++] = createFindMatch(range, m, captureMatches);
if (resultLen >= limitResultCount) {
return resultLen;
}
if (m.index + m[0].length === text.length) {
// Reached the end of the line
return resultLen;
}
}
} while (m);
return resultLen;
}
public static findNextMatch(model: TextModel, searchParams: SearchParams, searchStart: Position, captureMatches: boolean): FindMatch {
const searchData = searchParams.parseSearchRequest();
if (!searchData) {
return null;
}
if (searchData.regex.multiline) {
return this._doFindNextMatchMultiline(model, searchStart, searchData.regex, captureMatches);
}
return this._doFindNextMatchLineByLine(model, searchStart, searchData.regex, captureMatches);
}
private static _doFindNextMatchMultiline(model: TextModel, searchStart: Position, searchRegex: RegExp, captureMatches: boolean): FindMatch {
const searchTextStart = new Position(searchStart.lineNumber, 1);
const deltaOffset = model.getOffsetAt(searchTextStart);
const lineCount = model.getLineCount();
// We always execute multiline search over the lines joined with \n
// This makes it that \n will match the EOL for both CRLF and LF models
// We compensate for offset errors in `_getMultilineMatchRange`
const text = model.getValueInRange(new Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), EndOfLinePreference.LF);
searchRegex.lastIndex = searchStart.column - 1;
let m = searchRegex.exec(text);
if (m) {
return createFindMatch(
this._getMultilineMatchRange(model, deltaOffset, text, m.index, m[0]),
m,
captureMatches
);
}
if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
// Try again from the top
return this._doFindNextMatchMultiline(model, new Position(1, 1), searchRegex, captureMatches);
}
return null;
}
private static _doFindNextMatchLineByLine(model: TextModel, searchStart: Position, searchRegex: RegExp, captureMatches: boolean): FindMatch {
const lineCount = model.getLineCount();
const startLineNumber = searchStart.lineNumber;
// Look in first line
const text = model.getLineContent(startLineNumber);
const r = this._findFirstMatchInLine(searchRegex, text, startLineNumber, searchStart.column, captureMatches);
if (r) {
return r;
}
for (let i = 1; i <= lineCount; i++) {
const lineIndex = (startLineNumber + i - 1) % lineCount;
const text = model.getLineContent(lineIndex + 1);
const r = this._findFirstMatchInLine(searchRegex, text, lineIndex + 1, 1, captureMatches);
if (r) {
return r;
}
}
return null;
}
private static _findFirstMatchInLine(searchRegex: RegExp, text: string, lineNumber: number, fromColumn: number, captureMatches: boolean): FindMatch {
// Set regex to search from column
searchRegex.lastIndex = fromColumn - 1;
const m: RegExpExecArray = searchRegex.exec(text);
if (m) {
return createFindMatch(
new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length),
m,
captureMatches
);
}
return null;
}
public static findPreviousMatch(model: TextModel, searchParams: SearchParams, searchStart: Position, captureMatches: boolean): FindMatch {
const searchData = searchParams.parseSearchRequest();
if (!searchData) {
return null;
}
if (searchData.regex.multiline) {
return this._doFindPreviousMatchMultiline(model, searchStart, searchData.regex, captureMatches);
}
return this._doFindPreviousMatchLineByLine(model, searchStart, searchData.regex, captureMatches);
}
private static _doFindPreviousMatchMultiline(model: TextModel, searchStart: Position, searchRegex: RegExp, captureMatches: boolean): FindMatch {
const matches = this._doFindMatchesMultiline(model, new Range(1, 1, searchStart.lineNumber, searchStart.column), searchRegex, captureMatches, 10 * LIMIT_FIND_COUNT);
if (matches.length > 0) {
return matches[matches.length - 1];
}
const lineCount = model.getLineCount();
if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {
// Try again with all content
return this._doFindPreviousMatchMultiline(model, new Position(lineCount, model.getLineMaxColumn(lineCount)), searchRegex, captureMatches);
}
return null;
}
private static _doFindPreviousMatchLineByLine(model: TextModel, searchStart: Position, searchRegex: RegExp, captureMatches: boolean): FindMatch {
const lineCount = model.getLineCount();
const startLineNumber = searchStart.lineNumber;
// Look in first line
const text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
const r = this._findLastMatchInLine(searchRegex, text, startLineNumber, captureMatches);
if (r) {
return r;
}
for (let i = 1; i <= lineCount; i++) {
const lineIndex = (lineCount + startLineNumber - i - 1) % lineCount;
const text = model.getLineContent(lineIndex + 1);
const r = this._findLastMatchInLine(searchRegex, text, lineIndex + 1, captureMatches);
if (r) {
return r;
}
}
return null;
}
private static _findLastMatchInLine(searchRegex: RegExp, text: string, lineNumber: number, captureMatches: boolean): FindMatch {
let bestResult: FindMatch = null;
let m: RegExpExecArray;
while ((m = searchRegex.exec(text))) {
const result = new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length);
if (bestResult && result.equalsRange(bestResult.range)) {
break;
}
bestResult = createFindMatch(result, m, captureMatches);
if (m.index + m[0].length === text.length) {
// Reached the end of the line
break;
}
}
return bestResult;
}
} | the_stack |
import { RangeNavigator } from '../range-navigator';
import { valueToCoefficient, textElement, firstToLowerCase } from '../../common/utils/helper';
import { PathOption, Rect, measureText, TextOption, SvgRenderer } from '@syncfusion/ej2-svg-base';
import { DateTime } from '../../chart/axis/date-time-axis';
import { IntervalType } from '../../chart/utils/enum';
import { RangeIntervalType } from '../../common/utils/enum';
import { FontModel } from '../../common/model/base-model';
import { Axis, VisibleLabels } from '../../chart/axis/axis';
import { MajorGridLinesModel, VisibleLabelsModel, MajorTickLinesModel } from '../../chart/axis/axis-model';
import { ILabelRenderEventsArgs } from '../model/range-navigator-interface';
/**
* class for axis
*/
export class RangeNavigatorAxis extends DateTime {
constructor(range: RangeNavigator) {
super();
this.rangeNavigator = range;
}
public actualIntervalType: RangeIntervalType;
public rangeNavigator: RangeNavigator;
public firstLevelLabels: VisibleLabels[] = [];
public secondLevelLabels: VisibleLabels[] = [];
public lowerValues: number[];
public gridLines: Element;
/**
* To render grid lines of axis
*/
public renderGridLines(): void {
let pointX: number = 0;
const control: RangeNavigator = this.rangeNavigator;
const majorGridLines: MajorGridLinesModel = control.majorGridLines;
const majorTickLines: MajorTickLinesModel = control.majorTickLines;
let majorGrid: string = '';
let majorTick: string = '';
const rect: Rect = control.bounds;
const chartAxis: Axis = control.chartSeries.xAxis;
const disabledColor: string = (control.disableRangeSelector) ? 'transparent' : null;
this.gridLines = control.renderer.createGroup({ id: control.element.id + '_GridLines' });
const tick: number = (control.tickPosition === 'Outside' || control.series.length === 0) ?
rect.y + rect.height + majorTickLines.height : rect.y + rect.height - majorTickLines.height;
//Gridlines
this.firstLevelLabels = [];
chartAxis.labelStyle = control.labelStyle;
chartAxis.skeleton = control.skeleton;
chartAxis.skeletonType = control.skeletonType;
chartAxis.isChart = false;
if (control.valueType === 'DateTime') {
this.calculateDateTimeNiceInterval(
chartAxis, rect, chartAxis.doubleRange.start,
chartAxis.doubleRange.end, chartAxis.isChart
);
this.actualIntervalType = chartAxis.actualIntervalType;
this.findAxisLabels(chartAxis);
}
this.firstLevelLabels = chartAxis.visibleLabels;
this.lowerValues = [];
const labelLength: number = chartAxis.visibleLabels.length;
for (let i: number = 0; i < labelLength; i++) {
this.lowerValues.push(this.firstLevelLabels[i].value);
pointX = (valueToCoefficient(this.firstLevelLabels[i].value, chartAxis) * rect.width) + rect.x;
if (pointX >= rect.x && (rect.x + rect.width) >= pointX) {
majorGrid = majorGrid.concat('M ' + pointX + ' ' + (control.bounds.y + control.bounds.height) +
' L ' + pointX + ' ' + control.bounds.y + ' ');
majorTick = majorTick.concat('M ' + (pointX) + ' ' + (rect.y + rect.height) +
' L ' + (pointX) + ' ' + tick + ' ');
}
}
let options: PathOption = new PathOption(
control.element.id + '_MajorGridLine', 'transparent',
majorGridLines.width,
control.series.length ? disabledColor || majorGridLines.color || control.themeStyle.gridLineColor : 'transparent',
1, majorGridLines.dashArray, majorGrid
);
this.gridLines.appendChild(control.renderer.drawPath(options) as HTMLElement);
options = new PathOption(
control.element.id + '_MajorTickLine', 'transparent', majorTickLines.width,
disabledColor || majorTickLines.color || control.themeStyle.gridLineColor,
1, majorGridLines.dashArray, majorTick
);
this.gridLines.appendChild(control.renderer.drawPath(options) as HTMLElement);
}
/**
* To render of axis labels
*/
public renderAxisLabels(): void {
const axis: Axis = this.rangeNavigator.chartSeries.xAxis;
const control: RangeNavigator = this.rangeNavigator;
let pointY: number;
const labelElement: Element = control.renderer.createGroup({ id: control.element.id + '_AxisLabels' });
const firstLevelElement: Element = control.renderer.createGroup({ id: control.element.id + '_FirstLevelAxisLabels' });
const secondLevelElement: Element = control.renderer.createGroup({ id: control.element.id + '_SecondLevelAxisLabels' });
const secondaryAxis: Axis = axis;
pointY = this.findLabelY(control, false);
this.placeAxisLabels(axis, pointY, '_AxisLabel_', control, firstLevelElement);
secondaryAxis.intervalType = secondaryAxis.actualIntervalType = (control.groupBy ||
this.getSecondaryLabelType(axis.actualIntervalType)) as IntervalType;
secondaryAxis.labelFormat = '';
if (control.enableGrouping && control.valueType === 'DateTime' && this.actualIntervalType !== 'Years') {
secondaryAxis.visibleRange.interval = 1;
secondaryAxis.visibleLabels = [];
this.findAxisLabels(secondaryAxis);
this.secondLevelLabels = secondaryAxis.visibleLabels;
pointY = this.findLabelY(control, true);
const border: string = this.placeAxisLabels(secondaryAxis, pointY, '_SecondaryLabel_', control, secondLevelElement);
const path: PathOption = new PathOption(
control.element.id + '_SecondaryMajorLines', 'transparent', control.majorTickLines.width,
control.majorTickLines.color || control.themeStyle.gridLineColor, 1, control.majorGridLines.dashArray, border
);
this.gridLines.appendChild(control.renderer.drawPath(path) as HTMLElement);
}
control.chartSeries.xAxis.visibleLabels = control.chartSeries.xAxis.visibleLabels.concat(secondaryAxis.visibleLabels);
(labelElement as HTMLElement).style.cursor = axis.valueType === 'DateTime' ? 'cursor: pointer' : 'cursor: default';
labelElement.appendChild(firstLevelElement);
labelElement.appendChild(secondLevelElement);
//gridlines and axis label append to element
control.svgObject.appendChild(this.gridLines);
control.svgObject.appendChild(labelElement);
}
/**
* To find secondary level label type
*
* @param {RangeIntervalType} type type of range interval
*/
private getSecondaryLabelType(type: RangeIntervalType): RangeIntervalType {
const types: RangeIntervalType[] = ['Years', 'Quarter', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'];
return (type === 'Years' ? 'Years' : types[types.indexOf(type) - 1]);
}
/**
* To find labels for date time axis
*
* @param {Axis} axis range axis
*/
private findAxisLabels(axis: Axis): void {
axis.visibleLabels = [];
let start: Date = new Date(axis.visibleRange.min);
let nextInterval: number;
let text: string;
const interval: number = this.rangeNavigator.interval ? this.rangeNavigator.interval : 1;
switch (axis.actualIntervalType as RangeIntervalType) {
case 'Years':
start = new Date(start.getFullYear(), 0, 1);
break;
case 'Quarter':
if (start.getMonth() <= 2) {
start = new Date(start.getFullYear(), 0, 1);
} else if (start.getMonth() <= 5) {
start = new Date(start.getFullYear(), 3, 1);
} else if (start.getMonth() <= 8) {
start = new Date(start.getFullYear(), 6, 1);
} else {
start = new Date(start.getFullYear(), 9, 1);
}
break;
case 'Months':
start = new Date(start.getFullYear(), start.getMonth());
break;
case 'Weeks':
start = new Date(start.getFullYear(), start.getMonth(), start.getDate() - start.getDay());
break;
case 'Days':
start = new Date(start.getFullYear(), start.getMonth(), start.getDate());
break;
case 'Hours':
start = new Date(start.getFullYear(), start.getMonth(), start.getDate(), start.getHours());
break;
case 'Minutes':
start = new Date(start.getFullYear(), start.getMonth(), start.getDate(), start.getHours(), start.getMinutes());
break;
case 'Seconds':
start = new Date(
start.getFullYear(), start.getMonth(), start.getDate(),
start.getHours(), start.getMinutes(), start.getSeconds()
);
break;
}
nextInterval = start.getTime();
this.rangeNavigator.format = this.rangeNavigator.intl.getDateFormat({
format: axis.labelFormat || '',
type: firstToLowerCase(axis.skeletonType), skeleton: this.getSkeleton(axis, null, null)
});
while (nextInterval <= axis.visibleRange.max) {
text = this.dateFormats(this.rangeNavigator.format(new Date(nextInterval)), axis, axis.visibleLabels.length);
axis.visibleLabels.push(
new VisibleLabels(
text, nextInterval, this.rangeNavigator.labelStyle, text
)
);
nextInterval = this.increaseDateTimeInterval(axis, nextInterval, interval).getTime();
}
}
/**
* To find date time formats for Quarter and week interval type
*
* @param {string} text text
* @param {Axis} axis axis
* @param {number} index index
*/
private dateFormats(text: string, axis: Axis, index: number): string {
let changedText: string = text;
const isFirstLevel: boolean = this.rangeNavigator.enableGrouping && this.firstLevelLabels.length === 0;
switch (axis.actualIntervalType as RangeIntervalType) {
case 'Quarter':
if (text.indexOf('Jan') > -1) {
changedText = !isFirstLevel ? text.replace('Jan', 'Quarter1') : 'Quarter1';
} else if (text.indexOf('Apr') > -1) {
changedText = !isFirstLevel ? text.replace('Apr', 'Quarter2') : 'Quarter2';
} else if (text.indexOf('Jul') > -1) {
changedText = !isFirstLevel ? text.replace('Jul', 'Quarter3') : 'Quarter3';
} else if (text.indexOf('Oct') > -1) {
changedText = !isFirstLevel ? text.replace('Oct', 'Quarter4') : 'Quarter4';
}
break;
case 'Weeks':
changedText = 'Week' + ++index;
break;
default:
changedText = text;
break;
}
return changedText;
}
/**
* To find the y co-ordinate for axis labels
*
* @param {RangeNavigator} control - rangeNavigator
* @param {boolean} isSecondary sets true if the axis is secondary axis
*/
private findLabelY(control: RangeNavigator, isSecondary: boolean): number {
let pointY: number;
const reference: number = control.bounds.y + control.bounds.height;
const tickHeight: number = control.majorTickLines.height;
const textHeight: number = measureText('Quarter1 2011', control.labelStyle).height;
let padding: number = 8;
if ((control.labelPosition === 'Outside' && control.tickPosition === 'Outside') || control.series.length === 0) {
pointY = reference + tickHeight + padding + textHeight * 0.75;
} else if (control.labelPosition === 'Inside' && control.tickPosition === 'Inside') {
pointY = reference - tickHeight - padding;
} else if (control.labelPosition === 'Inside' && control.tickPosition === 'Outside') {
pointY = reference - padding;
} else {
pointY = reference + padding + (textHeight * 0.75);
}
if (isSecondary) {
padding = 15;
if (control.labelPosition === 'Outside' || control.series.length === 0) {
pointY += padding + textHeight * 0.75;
} else {
pointY = (control.tickPosition === 'Outside' || control.series.length === 0) ?
reference + tickHeight + padding + textHeight * 0.75 : reference + padding + textHeight * 0.75;
}
}
return pointY;
}
/**
* It places the axis labels and returns border for secondary axis labels
*
* @param {Axis} axis axis for the lables placed
* @param {number} pointY y co-ordinate for axis labels
* @param {string} id id for the axis elements
* @param {RangeNavigator} control range navigator
* @param {Element} labelElement parent element in which axis labels appended
*/
private placeAxisLabels(axis: Axis, pointY: number, id: string, control: RangeNavigator, labelElement: Element): string {
const maxLabels: number = axis.visibleLabels.length;
let label: VisibleLabels;
let prevLabel: VisibleLabels;
let pointX: number;
const rect: Rect = control.bounds;
let border: string = '';
let pointXGrid: number;
const disabledColor: string = (control.disableRangeSelector) ? 'transparent' : null;
let prevX: number = control.enableRtl ? (rect.x + rect.width) : rect.x;
const intervalType: RangeIntervalType = axis.actualIntervalType as RangeIntervalType;
const intervalInTime: number = control.valueType === 'DateTime' ?
maxLabels > 1 ? (axis.visibleLabels[1].value - axis.visibleLabels[0].value) :
(axis.visibleRange.max - axis.visibleLabels[0].value) / 2 : 0;
if (control.valueType === 'DateTime' && (intervalType === 'Quarter' || intervalType === 'Weeks')) {
this.findSuitableFormat(axis, control);
}
for (let i: number = 0, len: number = maxLabels; i < len; i++) {
label = axis.visibleLabels[i];
label.size = measureText(<string>label.text, axis.labelStyle);
if (control.secondaryLabelAlignment === 'Middle') {
pointX = (valueToCoefficient((label.value + intervalInTime / 2), axis) * rect.width) + rect.x;
} else if ((id.indexOf('Secondary') > -1)) {
pointX = this.findAlignment(axis, i);
}
pointXGrid = (valueToCoefficient((label.value), axis) * rect.width) + rect.x;
//edgelabelPlacements
if ((i === 0 || (i === axis.visibleLabels.length - 1 && control.enableRtl)) && pointX < rect.x) {
pointX = rect.x + label.size.width / 2;
}
if (
(i === axis.visibleLabels.length - 1 || (i === 0 && control.enableRtl)) &&
((pointX + label.size.width) > (rect.x + rect.width))
) {
pointX = rect.x + rect.width - label.size.width / 2;
}
//secondary axis grid lines
if (id.indexOf('_SecondaryLabel_') > -1) {
if (pointX >= rect.x && (rect.x + rect.width) >= pointX) {
border = border.concat('M ' + pointXGrid + ' ' + pointY +
' L ' + pointXGrid + ' ' + (pointY - label.size.height));
}
}
//smart axis label position,
if (
control.labelIntersectAction === 'Hide' &&
i !== 0 && this.isIntersect(axis, pointX, label.size.width, prevX, prevLabel.size.width)) {
continue;
}
//label alignment for single visible label
if (control.secondaryLabelAlignment === 'Middle' && axis.visibleLabels.length === 1) {
pointX = valueToCoefficient(label.value, axis) + (rect.x + (rect.width / 2));
}
//labelrender event
const labelStyle: FontModel = control.labelStyle;
const style: FontModel = {
size: labelStyle.size, color: disabledColor || labelStyle.color || control.themeStyle.labelFontColor,
fontFamily: labelStyle.fontFamily,
fontStyle: labelStyle.fontStyle || control.labelStyle.fontStyle,
fontWeight: labelStyle.fontWeight || control.labelStyle.fontWeight,
opacity: labelStyle.opacity || control.labelStyle.opacity,
textAlignment: labelStyle.textAlignment || control.labelStyle.textAlignment,
textOverflow: labelStyle.textOverflow || control.labelStyle.textOverflow
};
const argsData: ILabelRenderEventsArgs = {
cancel: false, name: 'labelRender',
text: <string>label.text, value: label.value, labelStyle: style,
region: new Rect(pointX, pointY, label.size.width, label.size.height)
};
control.trigger('labelRender', argsData);
if (!argsData.cancel) {
control.labels.push(argsData);
} else {
continue;
}
(textElement(
this.rangeNavigator.renderer as unknown as SvgRenderer,
new TextOption(
this.rangeNavigator.element.id + id + i, pointX, pointY, 'middle', argsData.text),
argsData.labelStyle, argsData.labelStyle.color || control.themeStyle.labelFontColor,
labelElement) as HTMLElement).style.cursor = axis.valueType === 'DateTime' ? 'cursor: pointer' : 'cursor: default';
prevX = pointX;
prevLabel = label;
}
return border;
}
/**
* To check label is intersected with successive label or not
*/
private isIntersect(axis: Axis, currentX: number, currentWidth: number, prevX: number, prevWidth: number): boolean {
return (axis.isInversed) ? (currentX + currentWidth / 2 > prevX - prevWidth / 2) :
(currentX - currentWidth / 2 < prevX + prevWidth / 2);
}
/**
* To find suitable label format for Quarter and week Interval types
*
* @param {Axis} axis RangeNavigator axis
* @param {RangeNavigator} control RangeNavigator instance
*/
private findSuitableFormat(axis: Axis, control: RangeNavigator): void {
const labels: VisibleLabels[] = axis.visibleLabels;
const labelLength: number = labels.length;
const bounds: Rect = control.bounds;
let prevX: number;
let currentX: number;
const interval: number = control.valueType === 'DateTime' ?
labelLength > 1 ? (labels[1].value - labels[0].value) : axis.visibleRange.interval
: 0;
for (let i: number = 0; i < labelLength; i++) {
currentX = (valueToCoefficient((labels[i].value + interval / 2), axis) * bounds.width) + bounds.x;
labels[i].size = measureText(<string>labels[i].text, axis.labelStyle);
//edgelabelPlacements
if (i === 0 && currentX < bounds.x) {
currentX = bounds.x + labels[i].size.width / 2;
}
if ((axis.actualIntervalType as RangeIntervalType) === 'Quarter') {
if (i !== 0) {
if ((labels[i].text.indexOf('Quarter') > -1) &&
(this.isIntersect(axis, currentX, labels[i].size.width, prevX, labels[i - 1].size.width))) {
labels.every((label: VisibleLabels) => {
label.text = label.text.toString().replace('Quarter', 'QTR'); return true;
});
axis.visibleLabels = labels;
this.findSuitableFormat(axis, control);
} else {
if (this.isIntersect(axis, currentX, labels[i].size.width, prevX, labels[i - 1].size.width)) {
labels.every((label: VisibleLabels) => {
label.text = label.text.toString().replace('QTR', 'Q'); return true;
});
axis.visibleLabels = labels;
}
}
}
} else if ((axis.actualIntervalType as RangeIntervalType) === 'Weeks') {
if ((i !== 0) && ((labels[i].text.indexOf('Week') > -1) &&
(this.isIntersect(axis, currentX, labels[i].size.width, prevX, labels[i - 1].size.width)))) {
labels.every((label: VisibleLabels) => {
label.text = label.text.toString().replace('Week', 'W'); return true;
});
axis.visibleLabels = labels;
}
}
prevX = currentX;
}
}
/**
* Alignment position for secondary level labels in date time axis
*
* @param {Axis} axis axis
* @param {number} index label index
*/
private findAlignment(axis: Axis, index: number): number {
const label: VisibleLabels = axis.visibleLabels[index];
const nextLabel: VisibleLabels = axis.visibleLabels[index + 1];
const bounds: Rect = this.rangeNavigator.bounds;
return (this.rangeNavigator.secondaryLabelAlignment === 'Near' ?
(valueToCoefficient((label.value), axis) * bounds.width) + bounds.x + label.size.width / 2 :
(valueToCoefficient((nextLabel ? nextLabel.value : axis.visibleRange.max), axis) * bounds.width) + bounds.x - label.size.width);
}
} | the_stack |
import * as widgets from '@jupyter-widgets/base';
import * as d3 from 'd3';
import { ColorScale, GeoScale, LinearScale, OrdinalScale } from 'bqscales';
import { MessageLoop } from '@lumino/messaging';
import { Widget } from '@lumino/widgets';
import { d3GetEvent } from './utils';
import * as _ from 'underscore';
import { MarkModel } from './MarkModel';
import { Figure } from './Figure';
import { applyStyles } from './utils';
// Check that value is defined and not null
function is_defined(value) {
return value !== null && value !== undefined;
}
interface MarkScales {
x: LinearScale | OrdinalScale;
y: LinearScale | OrdinalScale;
width: LinearScale | OrdinalScale;
color: ColorScale;
link_color: ColorScale;
row: LinearScale | OrdinalScale;
column: LinearScale | OrdinalScale;
size: LinearScale | OrdinalScale;
opacity: LinearScale | OrdinalScale;
rotation: LinearScale | OrdinalScale;
skew: LinearScale | OrdinalScale;
sample: LinearScale | OrdinalScale;
count: LinearScale | OrdinalScale;
projection: GeoScale;
}
export abstract class Mark extends widgets.WidgetView {
initialize() {
this.display_el_classes = ['mark']; //classes on the element which
//trigger the tooltip to be displayed when they are hovered over
this.setElement(
document.createElementNS(d3.namespaces.svg, 'g') as HTMLElement
);
this.d3el = d3.select(this.el);
super.initialize.apply(this, arguments);
}
render(): PromiseLike<any> {
this.xPadding = 0;
this.yPadding = 0;
this.parent = this.options.parent;
this.uuid = widgets.uuid();
const scale_creation_promise = this.set_scale_views();
this.listenTo(this.model, 'scales_updated', () => {
this.set_scale_views().then(_.bind(this.draw, this));
});
if (this.options.clip_id && this.model.get('apply_clip')) {
this.d3el.attr('clip-path', 'url(#' + this.options.clip_id + ')');
}
this.tooltip_div = d3
.select(document.createElement('div'))
.attr('class', 'mark_tooltip')
.attr('id', 'tooltip_' + this.uuid)
.style('display', 'none')
.style('opacity', 0);
this.bisect = d3.bisector((d) => {
return d;
}).left;
this.d3el.style('display', this.model.get('visible') ? 'inline' : 'none');
this.display_el_classes = [];
this.event_metadata = {
mouse_over: {
msg_name: 'hover',
lookup_data: true,
hit_test: true,
},
legend_clicked: {
msg_name: 'legend_click',
hit_test: true,
},
element_clicked: {
msg_name: 'element_click',
lookup_data: true,
hit_test: true,
},
parent_clicked: {
msg_name: 'background_click',
hit_test: false,
},
legend_mouse_over: {
msg_name: 'legend_hover',
hit_test: true,
},
};
return scale_creation_promise;
}
abstract draw(animate?);
abstract set_ranges();
set_scale_views() {
// first, if this.scales was already defined, unregister from the
// old ones.
for (const key in this.scales) {
this.stopListening(this.scales[key]);
}
const scale_models = this.model.getScales();
const that = this;
const scale_promises = {};
_.each(scale_models, (model: widgets.WidgetModel, key) => {
scale_promises[key] = that.create_child_view(model);
});
return (
widgets
.resolvePromisesDict(scale_promises)
// @ts-ignore: TODO Should find a proper type for scale_promises
.then((scales: MarkScales) => {
that.scales = scales;
that.set_positional_scales();
that.initialize_additional_scales();
that.set_ranges();
that.trigger('mark_scales_updated');
})
);
}
set_positional_scales() {
// Positional scales are special in that they trigger a full redraw
// when their domain is changed.
// This should be overloaded in specific mark implementation.
}
initialize_additional_scales() {
// This function is for the extra scales that are required for
// rendering mark. The scale listeners are set up in this function.
// This should be overloaded in the specific mark implementation.
}
set_internal_scales() {
// Some marks such as Bars need to create additional scales
// to draw themselves. In this case, the set_internal_scales
// is overloaded.
}
create_listeners() {
this.listenTo(this.model, 'change:visible', this.update_visibility);
this.listenTo(
this.model,
'change:selected_style',
this.selected_style_updated
);
this.listenTo(
this.model,
'change:unselected_style',
this.unselected_style_updated
);
this.listenTo(this.parent, 'margin_updated', this.relayout);
this.model.on_some_change(
['labels', 'display_legend'],
function () {
this.model.trigger('redraw_legend');
},
this
);
}
remove() {
this.model.off(null, null, this);
this.d3el.transition('remove').duration(0).remove();
this.tooltip_div.remove();
super.remove();
}
draw_legend(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) {
elem.selectAll('.legend' + this.uuid).remove();
elem
.append('g')
.attr('transform', 'translate(' + x_disp + ', ' + y_disp + ')')
.attr('class', 'legend' + this.uuid)
.on('mouseover', _.bind(this.highlight_axes, this))
.on('mouseout', _.bind(this.unhighlight_axes, this))
.append('text')
.text(this.model.get('labels')[0]);
return [1, 1];
}
highlight_axes() {
_.each(this.model.getScales(), (model: any) => {
model.trigger('highlight_axis');
});
}
unhighlight_axes() {
_.each(this.model.getScales(), (model: any) => {
model.trigger('unhighlight_axis');
});
}
invert_range(start_pxl, end_pxl) {
return [start_pxl, end_pxl];
}
invert_point(pxl) {}
// TODO: is the following function really required?
invert_multi_range(array_pixels) {
return array_pixels;
}
update_visibility(model, visible) {
this.d3el.style('display', visible ? 'inline' : 'none');
}
get_colors(index): string {
// cycles over the list of colors when too many items
const colors = this.model.get('colors');
return colors[index % colors.length];
}
get_mark_color(data, index): string {
const colorScale = this.scales.color;
if (colorScale && data.color !== undefined && data.color !== null) {
return colorScale.scale(data.color);
}
return this.get_colors(index);
}
get_mark_opacity(data, index) {
const opacityScale = this.scales.opacity;
const defaultOpacities = this.model.get('opacities');
if (opacityScale && data.opacity !== undefined && data.opacity !== null) {
return opacityScale.scale(data.opacity);
}
return defaultOpacities[index % defaultOpacities.length];
}
// Style related functions
selected_style_updated(model, style) {
this.selected_style = style;
this.clear_style(model.previous('selected_style'), this.selected_indices);
this.style_updated(style, this.selected_indices);
}
unselected_style_updated(model, style) {
this.unselected_style = style;
const sel_indices = this.selected_indices;
const unselected_indices = sel_indices
? _.range(this.model.mark_data.length).filter((index) => {
return sel_indices.indexOf(index) === -1;
})
: [];
this.clear_style(model.previous('unselected_style'), unselected_indices);
this.style_updated(style, unselected_indices);
}
style_updated(new_style, indices, elements?) {
// reset the style of the elements and apply the new style
this.set_default_style(indices);
this.set_style_on_elements(new_style, indices);
}
apply_styles(style_arr?) {
if (style_arr === undefined || style_arr == null) {
style_arr = [this.selected_style, this.unselected_style];
}
const all_indices = _.range(this.model.mark_data.length);
for (let i = 0; i < style_arr.length; i++) {
this.clear_style(style_arr[i]);
}
this.set_default_style(all_indices);
this.set_style_on_elements(
this.selected_style,
Array.from(this.selected_indices || [])
);
const unselected_indices = !this.selected_indices
? []
: _.difference(all_indices, Array.from(this.selected_indices));
this.set_style_on_elements(this.unselected_style, unselected_indices);
}
// Abstract functions which have to be overridden by the specific mark
abstract clear_style(style_dict, indices?, elements?);
abstract set_default_style(indices, elements?);
abstract set_style_on_elements(style, indices, elements?);
// Called when the figure margins are updated.
abstract relayout();
/**
* This function sets the x and y view paddings for the mark using the
* variables xPadding and yPadding
*/
abstract compute_view_padding();
show_tooltip(mouse_events?) {
//this function displays the tooltip at the location of the mouse
//event is the d3 event for the data.
//mouse_events is a boolean to enable mouse_events or not.
//If this property has never been set, it will default to false.
if (this.tooltip_view) {
if (
mouse_events === undefined ||
mouse_events === null ||
!mouse_events
) {
this.tooltip_div.style('pointer-events', 'none');
} else {
this.tooltip_div.style('pointer-events', 'all');
}
applyStyles(this.tooltip_div, this.model.get('tooltip_style')).style(
'display',
null
);
MessageLoop.sendMessage(this.tooltip_view.pWidget, Widget.Msg.AfterShow);
this.parent.popper.enableEventListeners();
this.move_tooltip();
}
}
move_tooltip(mouse_events?) {
if (this.tooltip_view) {
(this.parent.popper_reference as any).x = d3GetEvent().clientX;
(this.parent.popper_reference as any).y = d3GetEvent().clientY;
this.parent.popper.scheduleUpdate();
}
}
hide_tooltip() {
//this function hides the tooltip. But the location of the tooltip
//is the last location set by a call to show_tooltip.
this.parent.popper.disableEventListeners();
this.tooltip_div.style('pointer-events', 'none');
this.tooltip_div.style('opacity', 0).style('display', 'none');
}
refresh_tooltip(tooltip_interactions = false) {
//the argument controls pointer interactions with the tooltip. a
//true value enables pointer interactions while a false value
//disables them
const el = d3.select(d3GetEvent().target);
if (this.is_hover_element(el)) {
const data: any = el.data()[0];
const clicked_data = this.model.get_data_dict(data, data.index);
this.trigger('update_tooltip', clicked_data);
this.show_tooltip(tooltip_interactions);
}
}
create_tooltip() {
//create tooltip widget. To be called after mark has been displayed
//and whenever the tooltip object changes
const tooltip_model = this.model.get('tooltip');
//remove previous tooltip
if (this.tooltip_view) {
this.tooltip_view.remove();
this.tooltip_view = null;
}
if (tooltip_model) {
this.create_child_view(tooltip_model).then((view) => {
this.tooltip_view = view;
MessageLoop.sendMessage(view.pWidget, Widget.Msg.BeforeAttach);
this.tooltip_div.node().appendChild(view.el);
MessageLoop.sendMessage(view.pWidget, Widget.Msg.AfterAttach);
});
}
}
event_dispatcher(event_name, data?) {
if (this.event_listeners[event_name] !== undefined) {
_.bind(this.event_listeners[event_name], this, data)();
}
// Sends a custom mssg to the python side if required
// This must be done after calling the event_listeners so that needed
// properties (like "selected") are updated
this.custom_msg_sender(event_name);
}
custom_msg_sender(event_name) {
const event_data = this.event_metadata[event_name];
if (event_data !== undefined) {
let data = null;
if (event_data.hit_test) {
//do a hit test to check valid element
const el = d3.select(d3GetEvent().target);
if (this.is_hover_element(el)) {
data = el.data()[0];
if (event_data.lookup_data) {
data = this.model.get_data_dict(data, data.index);
}
} else {
//do not send mssg if hit test fails
return;
}
}
this.send({ event: event_data.msg_name, data: data });
}
}
reset_click() {
this.event_listeners.element_clicked = function () {};
this.event_listeners.parent_clicked = function () {};
}
private reset_hover() {
this.event_listeners.mouse_over = function () {};
this.event_listeners.mouse_move = function () {};
this.event_listeners.mouse_out = function () {};
}
private reset_legend_click() {
this.event_listeners.legend_clicked = function () {};
}
private reset_legend_hover() {
this.event_listeners.legend_mouse_over = function () {};
this.event_listeners.legend_mouse_out = function () {};
}
process_click(interaction) {
const that = this;
if (interaction === 'tooltip') {
this.event_listeners.element_clicked = function () {
return that.refresh_tooltip(true);
};
this.event_listeners.parent_clicked = this.hide_tooltip;
}
}
process_hover(interaction) {
if (interaction === 'tooltip') {
this.event_listeners.mouse_over = this.refresh_tooltip;
this.event_listeners.mouse_move = this.move_tooltip;
this.event_listeners.mouse_out = this.hide_tooltip;
}
}
process_legend_click(interaction) {
const that = this;
if (interaction === 'tooltip') {
this.event_listeners.legend_clicked = function () {
return that.refresh_tooltip(true);
};
this.event_listeners.parent_clicked = this.hide_tooltip;
}
}
process_legend_hover(interaction) {
if (interaction === 'highlight_axes') {
this.event_listeners.legend_mouse_over = _.bind(
this.highlight_axes,
this
);
this.event_listeners.legend_mouse_out = _.bind(
this.unhighlight_axes,
this
);
}
}
process_interactions() {
//configure default interactions
const interactions = this.model.get('interactions');
if (is_defined(interactions.click)) {
this.process_click(interactions.click);
} else {
this.reset_click();
}
if (is_defined(interactions.hover)) {
this.process_hover(interactions.hover);
} else {
this.reset_hover();
}
if (is_defined(interactions.legend_click)) {
this.process_legend_click(interactions.legend_click);
} else {
this.reset_legend_click();
}
if (is_defined(interactions.legend_hover)) {
this.process_legend_hover(interactions.legend_hover);
} else {
this.reset_legend_hover();
}
}
mouse_over() {
if (this.model.get('enable_hover')) {
const el = d3.select(d3GetEvent().target);
if (this.is_hover_element(el)) {
const data: any = el.data()[0];
//make tooltip visible
const hovered_data = this.model.get_data_dict(data, data.index);
this.trigger('update_tooltip', hovered_data);
this.show_tooltip();
this.send({
event: 'hover',
point: hovered_data,
});
}
}
}
mouse_out() {
if (this.model.get('enable_hover')) {
const el = d3.select(d3GetEvent().target);
if (this.is_hover_element(el)) {
const data: any = el.data()[0];
const hovered_data = this.model.get_data_dict(data, data.index);
// make tooltip invisible
this.hide_tooltip();
this.send({
event: 'hover',
point: hovered_data,
});
}
}
}
mouse_move() {
if (
this.model.get('enable_hover') &&
this.is_hover_element(d3.select(d3GetEvent().target))
) {
this.move_tooltip();
}
}
//TODO: Rename function
is_hover_element(elem) {
const hit_check = this.display_el_classes.map((class_name) => {
return elem.classed(class_name);
});
return _.compact(hit_check).length > 0;
}
// For backward-compatibility with bqplot plugins
// TODO Remove it when we make a backward-incompatible release
set x_padding(value: number) {
this.xPadding = value;
}
get x_padding(): number {
return this.xPadding;
}
set y_padding(value: number) {
this.yPadding = value;
}
get y_padding(): number {
return this.yPadding;
}
bisect: (x: number[], y: number) => number;
d3el: d3.Selection<HTMLElement, any, any, any>;
display_el_classes: string[];
event_listeners: {
element_clicked?: (args) => void;
parent_clicked?: (args) => void;
legend_mouse_out?: (args) => void;
legend_mouse_over?: (args) => void;
legend_clicked?: (args) => void;
mouse_out?: (args) => void;
mouse_move?: (args) => void;
mouse_over?: (args) => void;
};
event_metadata: { [key: string]: { [key: string]: any } };
parent: Figure;
scales: MarkScales;
selected_indices: (number | [number, number])[];
selected_style: { [key: string]: string };
tooltip_div: d3.Selection<any, any, any, any>;
tooltip_view: widgets.DOMWidgetView;
unselected_style: { [key: string]: string };
uuid: string;
xPadding: number;
yPadding: number;
// Overriding super class
model: MarkModel;
} | the_stack |
import {action} from '@storybook/addon-actions';
import AlignCenter from '@spectrum-icons/workflow/AlignCenter';
import AlignLeft from '@spectrum-icons/workflow/AlignLeft';
import AlignRight from '@spectrum-icons/workflow/AlignRight';
import Blower from '@spectrum-icons/workflow/Blower';
import Book from '@spectrum-icons/workflow/Book';
import {Button, Flex} from '@adobe/react-spectrum';
import Copy from '@spectrum-icons/workflow/Copy';
import Cut from '@spectrum-icons/workflow/Cut';
import {Item, ListBox, Section} from '../';
import {Label} from '@react-spectrum/label';
import Paste from '@spectrum-icons/workflow/Paste';
import React, {useState} from 'react';
import {storiesOf} from '@storybook/react';
import {Text} from '@react-spectrum/text';
import {useAsyncList} from '@react-stately/data';
let iconMap = {
AlignCenter,
AlignLeft,
AlignRight,
Blower,
Book,
Copy,
Cut,
Paste
};
let hardModeProgrammatic = [
{name: 'Section 1', children: [
{name: 'Copy', icon: 'Copy'},
{name: 'Cut', icon: 'Cut'},
{name: 'Paste', icon: 'Paste'}
]},
{name: 'Section 2', children: [
{name: 'Puppy', icon: 'AlignLeft'},
{name: 'Doggo', icon: 'AlignCenter'},
{name: 'Floof', icon: 'AlignRight'}
]}
];
let flatOptions = [
{name: 'Aardvark'},
{name: 'Kangaroo'},
{name: 'Snake'},
{name: 'Danni'},
{name: 'Devon'},
{name: 'Ross'},
{name: 'Puppy'},
{name: 'Doggo'},
{name: 'Floof'}
];
let withSection = [
{name: 'Animals', children: [
{name: 'Aardvark'},
{name: 'Kangaroo'},
{name: 'Snake'}
]},
{name: 'People', children: [
{name: 'Danni'},
{name: 'Devon'},
{name: 'Ross'}
]}
];
let lotsOfSections: any[] = [];
for (let i = 0; i < 50; i++) {
let children = [];
for (let j = 0; j < 50; j++) {
children.push({name: `Section ${i}, Item ${j}`});
}
lotsOfSections.push({name: 'Section ' + i, children});
}
storiesOf('ListBox', module)
.addDecorator(story => (
<div style={{display: 'flex', flexDirection: 'column'}}>
<Label id="label">Choose an item</Label>
<div style={{display: 'flex', minWidth: '200px', background: 'var(--spectrum-global-color-gray-50)', border: '1px solid lightgray', maxHeight: 300}}>
{story()}
</div>
</div>
))
.add(
'Default ListBox',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={flatOptions}>
{item => <Item key={item.name}>{item.name}</Item>}
</ListBox>
)
)
.add(
'ListBox w/ sections',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'ListBox w/ many sections and selection',
() => (
<ListBox flexGrow={1} aria-labelledby="label" selectionMode="multiple" items={lotsOfSections} onSelectionChange={action('onSelectionChange')}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{(item: any) => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'ListBox w/ sections and no title',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection}>
{item => (
<Section key={item.name} items={item.children} aria-label={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'Static',
() => (
<ListBox flexGrow={1} aria-labelledby="label">
<Item>One</Item>
<Item>Two</Item>
<Item>Three</Item>
</ListBox>
)
)
.add(
'Static with sections and selection',
() => (
<ListBox flexGrow={1} aria-labelledby="label" selectionMode="multiple">
<Section title="Section 1">
<Item>One</Item>
<Item>Two</Item>
<Item>Three</Item>
</Section>
<Section title="Section 2">
<Item>One</Item>
<Item>Two</Item>
<Item>Three</Item>
</Section>
</ListBox>
)
)
.add(
'Static with sections and no title',
() => (
<ListBox flexGrow={1} aria-labelledby="label">
<Section aria-label="Section 1">
<Item>One</Item>
<Item>Two</Item>
<Item>Three</Item>
</Section>
<Section aria-label="Section 2">
<Item>One</Item>
<Item>Two</Item>
<Item>Three</Item>
</Section>
</ListBox>
)
)
.add(
'with default selected option',
() => (
<ListBox flexGrow={1} aria-labelledby="label" selectionMode="multiple" onSelectionChange={action('onSelectionChange')} items={withSection} defaultSelectedKeys={['Kangaroo']}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'single selection with default selected option',
() => (
<ListBox flexGrow={1} selectionMode="single" onSelectionChange={action('onSelectionChange')} aria-labelledby="label" items={flatOptions} defaultSelectedKeys={['Kangaroo']}>
{item => <Item key={item.name}>{item.name}</Item>}
</ListBox>
)
)
.add(
'static with default selected options',
() => (
<ListBox flexGrow={1} aria-labelledby="label" selectionMode="multiple" onSelectionChange={action('onSelectionChange')} defaultSelectedKeys={['2', '3']}>
<Section title="Section 1">
<Item key="1">
One
</Item>
<Item key="2">
Two
</Item>
<Item key="3">
Three
</Item>
</Section>
<Section title="Section 2">
<Item key="4">
Four
</Item>
<Item key="5">
Five
</Item>
<Item key="6">
Six
</Item>
<Item key="7">
Seven
</Item>
</Section>
</ListBox>
)
)
.add(
'with selected options (controlled)',
() => (
<ListBox flexGrow={1} aria-labelledby="label" selectionMode="multiple" onSelectionChange={action('onSelectionChange')} items={withSection} selectedKeys={['Kangaroo']}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'static with selected options (controlled)',
() => (
<ListBox flexGrow={1} aria-labelledby="label" selectionMode="multiple" onSelectionChange={action('onSelectionChange')} selectedKeys={['2']}>
<Section title="Section 1">
<Item key="1">
One
</Item>
<Item key="2">
Two
</Item>
<Item key="3">
Three
</Item>
</Section>
<Section title="Section 2">
<Item key="4">
Four
</Item>
<Item key="5">
Five
</Item>
<Item key="6">
Six
</Item>
<Item key="7">
Seven
</Item>
</Section>
</ListBox>
)
)
.add(
'with disabled options',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection} disabledKeys={['Kangaroo', 'Ross']}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'static with disabled options',
() => (
<ListBox flexGrow={1} aria-labelledby="label" disabledKeys={['3', '5']}>
<Section title="Section 1">
<Item key="1">
One
</Item>
<Item key="2">
Two
</Item>
<Item key="3">
Three
</Item>
</Section>
<Section title="Section 2">
<Item key="4">
Four
</Item>
<Item key="5">
Five
</Item>
<Item key="6">
Six
</Item>
<Item key="7">
Seven
</Item>
</Section>
</ListBox>
)
)
.add(
'Multiple selection',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection} onSelectionChange={action('onSelectionChange')} selectionMode="multiple" defaultSelectedKeys={['Aardvark', 'Snake']} disabledKeys={['Kangaroo', 'Ross']}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'Multiple selection, static',
() => (
<ListBox flexGrow={1} aria-labelledby="label" onSelectionChange={action('onSelectionChange')} selectionMode="multiple" defaultSelectedKeys={['2', '5']} disabledKeys={['1', '3']}>
<Section title="Section 1">
<Item key="1">
One
</Item>
<Item key="2">
Two
</Item>
<Item key="3">
Three
</Item>
</Section>
<Section title="Section 2">
<Item key="4">
Four
</Item>
<Item key="5">
Five
</Item>
<Item key="6">
Six
</Item>
</Section>
</ListBox>
)
)
.add(
'No selection allowed',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'No selection allowed, static',
() => (
<ListBox flexGrow={1} aria-labelledby="label">
<Section title="Section 1">
<Item>One</Item>
<Item>Two</Item>
<Item>Three</Item>
</Section>
<Section title="Section 2">
<Item>Four</Item>
<Item>Five</Item>
<Item>Six</Item>
</Section>
</ListBox>
)
)
.add(
'ListBox with autoFocus=true',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection} autoFocus>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'ListBox with autoFocus=true, selectionMode=single, default selected key (uncontrolled)',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection} autoFocus defaultSelectedKeys={['Snake']} selectionMode="single">
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'ListBox with autoFocus="first"',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection} selectionMode="multiple" onSelectionChange={action('onSelectionChange')} autoFocus="first">
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'ListBox with autoFocus="last"',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection} selectionMode="multiple" onSelectionChange={action('onSelectionChange')} autoFocus="last">
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'ListBox with keyboard selection wrapping',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={withSection} selectionMode="multiple" onSelectionChange={action('onSelectionChange')} shouldFocusWrap>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name}>{item.name}</Item>}
</Section>
)}
</ListBox>
)
)
.add(
'with semantic elements (static)',
() => (
<ListBox flexGrow={1} aria-labelledby="label" selectionMode="multiple" onSelectionChange={action('onSelectionChange')}>
<Section title="Section 1">
<Item textValue="Copy">
<Copy size="S" />
<Text>Copy</Text>
</Item>
<Item textValue="Cut">
<Cut size="S" />
<Text>Cut</Text>
</Item>
<Item textValue="Paste">
<Paste size="S" />
<Text>Paste</Text>
</Item>
</Section>
<Section title="Section 2">
<Item textValue="Puppy">
<AlignLeft size="S" />
<Text>Puppy</Text>
<Text slot="description">Puppy description super long as well geez</Text>
</Item>
<Item textValue="Doggo with really really really long long long text">
<AlignCenter size="S" />
<Text>Doggo with really really really long long long text</Text>
</Item>
<Item textValue="Floof">
<AlignRight size="S" />
<Text>Floof</Text>
</Item>
<Item>
Basic Item
</Item>
</Section>
</ListBox>
)
)
.add(
'with semantic elements (generative), multiple selection',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={hardModeProgrammatic} onSelectionChange={action('onSelectionChange')} selectionMode="multiple">
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => customOption(item)}
</Section>
)}
</ListBox>
)
)
.add(
'isLoading',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={[]} isLoading>
{item => <Item>{item.name}</Item>}
</ListBox>
)
)
.add(
'isLoading more',
() => (
<ListBox flexGrow={1} aria-labelledby="label" items={flatOptions} isLoading>
{item => <Item key={item.name}>{item.name}</Item>}
</ListBox>
)
)
.add(
'async loading',
() => (
<AsyncLoadingExample />
)
);
storiesOf('ListBox', module)
.addDecorator(story => (
<div style={{display: 'flex', flexDirection: 'column'}}>
<Label id="label">Choose an item</Label>
<div style={{display: 'flex', minWidth: '200px', background: 'var(--spectrum-global-color-gray-50)', border: '1px solid lightgray'}}>
{story()}
</div>
</div>
))
.add(
'async loading, resizable',
() => (
// need display flex or set a height on the listbox so it doesn't keep getting more elements
<div style={{display: 'flex', height: '200px', flexGrow: 1, minWidth: '200px', padding: '10px', resize: 'both', overflow: 'auto'}}>
<AsyncLoadingExample />
</div>
)
);
storiesOf('ListBox', module)
.add(
'listbox containers',
() => (
<App />
)
);
let customOption = (item) => {
let Icon = iconMap[item.icon];
return (
<Item textValue={item.name} key={item.name}>
{item.icon && <Icon size="S" />}
<Text>{item.name}</Text>
</Item>
);
};
function AsyncLoadingExample() {
interface Pokemon {
name: string,
url: string
}
let list = useAsyncList<Pokemon>({
async load({signal, cursor}) {
let res = await fetch(cursor || 'https://pokeapi.co/api/v2/pokemon', {signal});
let json = await res.json();
return {
items: json.results,
cursor: json.next
};
}
});
return (
<ListBox flexGrow={1} aria-labelledby="label" items={list.items} isLoading={list.isLoading} onLoadMore={list.loadMore}>
{item => <Item key={item.name}>{item.name}</Item>}
</ListBox>
);
}
let itemsForDemo = Array.from(new Array(100)).map((val, index) => ({val, index}));
function App() {
let [size, setSize] = useState('700px');
const toggleSize = () => {
if (size === '700px') {
setSize('300px');
} else {
setSize('700px');
}
};
return (
<>
<Button variant="primary" onPress={toggleSize}> Toggle Size</Button>
<div style={{display: 'flex', height: size, overflow: 'hidden'}}>
<Flex maxHeight="300px">
<Text>Max-Height: 300px</Text>
<ListBox width="150px" items={itemsForDemo}>
{ item => (
<Item textValue={String(item.index)} key={item.index}>
<Text>IDX: {item.index}</Text>
</Item>
)}
</ListBox>
</Flex>
<Flex>
<Text>None</Text>
<ListBox width="150px" items={itemsForDemo}>
{ item => (
<Item textValue={String(item.index)} key={item.index}>
<Text>IDX: {item.index}</Text>
</Item>
)}
</ListBox>
</Flex>
<Flex maxHeight="700px">
<Text>Max-Height: 700px</Text>
<ListBox width="150px" items={itemsForDemo}>
{ item => (
<Item textValue={String(item.index)} key={item.index}>
<Text>IDX: {item.index}</Text>
</Item>
)}
</ListBox>
</Flex>
<Flex maxHeight="100%">
<Text>MaxHeight: 100%</Text>
<ListBox width="150px" items={itemsForDemo}>
{ item => (
<Item textValue={String(item.index)} key={item.index}>
<Text>IDX: {item.index}</Text>
</Item>
)}
</ListBox>
</Flex>
<Flex maxHeight="50%">
<Text>MaxHeight: 50%</Text>
<ListBox width="150px" items={itemsForDemo}>
{ item => (
<Item textValue={String(item.index)} key={item.index}>
<Text>IDX: {item.index}</Text>
</Item>
)}
</ListBox>
</Flex>
<Flex height="700px">
<Text>Height: 700px</Text>
<ListBox width="150px" items={itemsForDemo}>
{ item => (
<Item textValue={String(item.index)} key={item.index}>
<Text>IDX: {item.index}</Text>
</Item>
)}
</ListBox>
</Flex>
<Flex height="100%">
<Text>Height: 100%</Text>
<ListBox width="150px" items={itemsForDemo}>
{ item => (
<Item textValue={String(item.index)} key={item.index}>
<Text>IDX: {item.index}</Text>
</Item>
)}
</ListBox>
</Flex>
</div>
</>
);
} | the_stack |
import { Component, OnInit, ComponentFactoryResolver, ReflectiveInjector, ElementRef, EventEmitter, Output, Inject, Input, ViewChild } from '@angular/core';
import { Filter } from '../../secondary-components/jazz-table/jazz-filter';
import { Sort } from '../../secondary-components/jazz-table/jazz-table-sort';
import { ToasterService } from 'angular2-toaster';
import { RequestService, MessageService } from '../../core/services/index';
import { FilterTagsComponent } from '../../secondary-components/filter-tags/filter-tags.component';
import { AfterViewInit } from '@angular/core';
import { AuthenticationService } from '../../core/services/index';
import { DataCacheService } from '../../core/services/index';
import { AdvancedFiltersComponent } from './../../secondary-components/advanced-filters/internal/advanced-filters.component';
import { AdvancedFilterService } from './../../advanced-filter.service';
import { AdvFilters } from './../../adv-filter.directive';
import { environment as env_internal } from './../../../environments/environment.internal';
import { environment as env_oss } from './../../../environments/environment.oss';
import * as _ from 'lodash';
declare let Promise;
@Component({
selector: 'service-logs',
templateUrl: './service-logs.component.html',
styleUrls: ['./service-logs.component.scss']
})
export class ServiceLogsComponent implements OnInit {
constructor(@Inject(ElementRef) elementRef: ElementRef, @Inject(ComponentFactoryResolver) componentFactoryResolver, private advancedFilters: AdvancedFilterService, private cache: DataCacheService, private authenticationservice: AuthenticationService, private request: RequestService, private toasterService: ToasterService, private messageservice: MessageService) {
var el: HTMLElement = elementRef.nativeElement;
this.root = el;
this.toasterService = toasterService;
this.http = request;
this.toastmessage = messageservice;
this.componentFactoryResolver = componentFactoryResolver;
var comp = this;
setTimeout(function () {
comp.getFilter(advancedFilters);
this.filter_loaded = true;
document.getElementById('hidethis').classList.add('hide')
}, 10);
}
filter_loaded: boolean = false;
@Input() service: any = {};
@Output() onAssetSelected: EventEmitter<any> = new EventEmitter<any>();
@ViewChild('filtertags') FilterTags: FilterTagsComponent;
@ViewChild(AdvFilters) advFilters: AdvFilters;
componentFactoryResolver: ComponentFactoryResolver;
advanced_filter_input: any = {
time_range: {
show: true,
},
slider: {
show: true,
},
period: {
show: false,
},
statistics: {
show: false,
},
path: {
show: false,
},
environment: {
show: true,
},
method: {
show: false,
},
account: {
show: false,
},
region: {
show: false,
},
asset: {
show: true,
},
sls_resource:{
show: false
}
}
selectFilter: any = {};
public assetWithDefaultValue: any = [];
public assetType: any;
fromlogs: boolean = true;
payload: any = {};
private http: any;
root: any;
errBody: any;
parsedErrBody: any;
errMessage: any;
public assetList: any = [];
public assetSelected: any;
public resourceSelected: any;
private toastmessage: any;
loadingState: string = 'default';
private subscription: any;
filterloglevel: string = 'ERROR';
environment: string = 'prod';
pageSelected: number = 1;
expandText: string = 'Expand all';
ReqId = [];
errorTime: any;
errorURL: any;
errorAPI: any;
selectedAssetName: any;
assetsNameArray:any = [];
allAssetsNameArray: any = [];
errorRequest: any = {};
errorResponse: any = {};
errorUser: any;
errorChecked: boolean = true;
errorInclude: any = "";
json: any = {};
model: any = {
userFeedback: ''
};
logsData: any;
tableHeader = [
{
label: 'Time',
key: 'timestamp',
sort: true,
filter: {
type: 'dateRange'
}
}, {
label: 'Message',
key: 'message',
sort: true,
filter: {
type: 'input'
}
}, {
label: 'Request ID',
key: 'request_id',
sort: true,
filter: {
type: ''
}
}, {
label: 'Log Level',
key: 'type',
sort: true,
filter: {
type: 'dropdown',
data: ['ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE']
}
}
]
logs = [];
backupLogs = [];
filterSelectedValue: any;
filtersList = ['ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE'];
selected = ['ERROR'];
slider: any;
sliderFrom = 1;
sliderPercentFrom;
sliderMax: number = 7;
rangeList: Array<string> = ['Day', 'Week', 'Month', 'Year'];
selectedTimeRange: string = this.rangeList[0];
assetEvent: string;
filterSelected: Boolean = false;
searchActive: Boolean = false;
searchbar: string = '';
filter: any;
sort: any;
paginationSelected: Boolean = true;
totalPagesTable: number = 7;
prevActivePage: number = 1;
limitValue: number = 20;
offsetValue: number = 0;
lambdaResourceNameArr;
selectedEnv: any;
lambdaResource;
responseArray: any = [];
envList = ['prod', 'stg'];
accList = env_internal.urls.accounts;
regList = env_internal.urls.regions;
accSelected: string = this.accList[0];
regSelected: string = this.regList[0];
instance_yes;
assetNameFilterWhiteList = [
'all',
'lambda',
'apigateway'
];
getFilter(filterServ){
this.service['islogs']=false;
this.service['isServicelogs']=true;
if(this.assetList){
this.service['assetList']=this.assetList;
}
this.service['allAssetsNameArray'] = this.allAssetsNameArray;
this.advanced_filter_input.sls_resource.show = true;
let filtertypeObj = filterServ.addDynamicComponent({ "service": this.service, "advanced_filter_input": this.advanced_filter_input });
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(filtertypeObj.component);
var comp = this;
let viewContainerRef = this.advFilters.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
this.instance_yes = (<AdvancedFiltersComponent>componentRef.instance);
(<AdvancedFiltersComponent>componentRef.instance).data = { "service": this.service, "advanced_filter_input": this.advanced_filter_input };
(<AdvancedFiltersComponent>componentRef.instance).onFilterSelect.subscribe(event => {
comp.onFilterSelect(event);
});
this.instance_yes.onAssetSelect.subscribe(event => {
comp.onAssetSelect(event);
if(event !== 'all'){
this.service['lambdaResourceNameArr'] = this.lambdaResourceNameArr;
this.advanced_filter_input.sls_resource.show = true;
(<AdvancedFiltersComponent>componentRef.instance).data = { "service": this.service, "advanced_filter_input": this.advanced_filter_input };
}
});
this.instance_yes.onResourceSelect.subscribe(event => {
comp.onResourceSelect(event);
});
this.instance_yes.onEnvSelected.subscribe(event => {
comp.onEnvSelected(event);
this.service['assetSelectedValue'] = this.assetSelected;
if(this.assetSelected === 'all') {
this.service['allAssetsNameArray'] = this.allAssetsNameArray;
this.advanced_filter_input.sls_resource.show = true;
}
else {
this.service['lambdaResourceNameArr'] = this.lambdaResourceNameArr;
this.advanced_filter_input.sls_resource.show = true;
}
(<AdvancedFiltersComponent>componentRef.instance).data = { "service": this.service, "advanced_filter_input": this.advanced_filter_input };
});
this.instance_yes.onFilterClick.subscribe(event => {
this.filterSelectedValue = event
})
}
onAssetSelect(event) {
this.assetEvent = event
this.FilterTags.notify('filter-Asset', event);
this.assetSelected = event;
if (event !== 'all' && this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1){
this.setAssetName(this.responseArray, this.assetSelected);
this.onResourceSelect('all');
}
}
onResourceSelect(event){
this.FilterTags.notifyLogs('filter-Asset-Name', event);
this.resourceSelected = event;
}
refresh() {
this.callLogsFunc();
}
refresh_env() {
this.refresh();
}
onaccSelected(event) {
this.FilterTags.notify('filter-Account', event);
this.accSelected = event;
}
onregSelected(event) {
this.FilterTags.notify('filter-Region', event);
this.regSelected = event;
}
fetchAssetName(type, name) {
let assetName;
let tokens;
switch(type) {
case 'lambda':
case 'sqs':
case 'iam_role':
tokens = name.split(':');
assetName = tokens[tokens.length - 1];
break;
case 'dynamodb':
case 'cloudfront':
case 'kinesis':
tokens = name.split('/');
assetName = tokens[tokens.length - 1];
break;
case 's3':
tokens = name.split(':::');
assetName = tokens[tokens.length - 1].split('/')[0];
break;
case 'apigateway':
case 'apigee_proxy':
tokens = name.split(this.selectedEnv + '/');
assetName = tokens[tokens.length - 1];
break;
}
return assetName;
}
setAssetName(val, selected) {
let assetObj = [];
this.lambdaResourceNameArr = [];
val.map((item) => {
assetObj.push({ type:item.asset_type, name: item.provider_id, env: item.environment });
})
if (selected === 'all') {
assetObj.map((item) => {
if(item.env === this.selectedEnv) {
this.selectedAssetName = this.fetchAssetName(item.type, item.name);
if (this.selectedAssetName) {
this.allAssetsNameArray.push(this.selectedAssetName);
}
}})
this.allAssetsNameArray.map((item,index)=>{
if(item === 'all'){
this.allAssetsNameArray.splice(index,1)
}
})
this.allAssetsNameArray.sort();
this.allAssetsNameArray.splice(0,0,'all');
}
else {
assetObj.map((item) => {
if (item.type === selected && item.env === this.selectedEnv) {
this.selectedAssetName = this.fetchAssetName(item.type, item.name);
if (this.selectedAssetName) {
this.lambdaResourceNameArr.push(this.selectedAssetName);
}
}
})
this.lambdaResourceNameArr.map((item,index)=>{
if(item === 'all'){
this.lambdaResourceNameArr.splice(index,1)
}
})
this.lambdaResourceNameArr.sort();
this.lambdaResourceNameArr.splice(0,0,'all');
}
}
getAssetType(data?) {
let self = this;
return this.http.get('/jazz/assets', {
domain: self.service.domain,
service: self.service.name,
status: "active",
limit: 1e3, // TODO: Address design shortcomings
offset: 0,
}, self.service.id).toPromise().then((response: any) => {
if (response && response.data && response.data.assets) {
this.assetsNameArray.push(response);
let assets = _(response.data.assets).map('asset_type').uniq().value();
const filterWhitelist = [
'lambda',
'apigateway'
];
assets = assets.filter(item => filterWhitelist.includes(item));
let validAssetList = assets.filter(asset => (env_oss.assetTypeList.indexOf(asset) > -1));
validAssetList.splice(0,0,'all');
this.responseArray = this.assetsNameArray[0].data.assets.filter(asset => (validAssetList.indexOf(asset.asset_type) > -1));
self.assetWithDefaultValue = validAssetList;
for (var i = 0; i < self.assetWithDefaultValue.length; i++) {
self.assetList[i] = self.assetWithDefaultValue[i].replace(/_/g, " ");
}
if (!data) {
self.assetSelected = validAssetList[0].replace(/_/g, " ");
}
self.assetSelected = validAssetList[0].replace(/_/g, " ");
if (this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1) {
self.setAssetName(self.responseArray, self.assetSelected);
}
self.getFilter(self.advancedFilters);
}
})
.catch((error) => {
return Promise.reject(error);
})
}
onEnvSelected(envt) {
this.FilterTags.notify('filter-Environment', envt);
// this.logsSearch.environment = env;
if (env === 'prod') {
env = 'prod'
}
var env_list = this.cache.get('envList');
var fName = env_list.friendly_name;
var index = fName.indexOf(envt);
var env = env_list.env[index];
this.environment = envt;
this.selectedEnv = envt;
if (this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1) {
this.setAssetName(this.responseArray,this.assetSelected)
}
this.payload.environment=env;
this.resetPayload();
}
onFilterSelect(event) {
switch (event.key) {
case 'slider': {
this.getRange(event.value);
break;
}
case 'range': {
this.sendDefaults(event.value);
this.FilterTags.notifyLogs('filter-TimeRange', event.value);
this.sliderFrom = 1;
this.FilterTags.notifyLogs('filter-TimeRangeSlider', this.sliderFrom);
var resetdate = this.getStartDate(event.value, this.sliderFrom);
this.selectedTimeRange = event.value;
this.payload.start_time = resetdate;
this.resetPayload();
break;
}
case 'account': {
this.FilterTags.notify('filter-Account', event.value);
this.accSelected = event.value;
break;
}
case 'region': {
this.FilterTags.notify('filter-Region', event.value);
this.regSelected = event.value;
break;
}
case "environment": {
this.FilterTags.notifyLogs('filter-Environment', event.value);
this.environment = event.value;
this.payload.environment = event.value;
this.selectAllAssetsData();
this.resetPayload();
break;
}
case "asset": {
this.FilterTags.notifyLogs('filter-Asset', event.value);
this.assetSelected = event.value;
if (this.assetSelected !== 'all') {
this.payload.asset_type = this.assetSelected.replace(/ /g, "_");
var value = (<HTMLInputElement>document.getElementById('Allidentifier'))
if(value != null) {
var inputValue = value.checked = true;
}
delete this.payload['asset_identifier']
}
else {
delete this.payload['asset_type'];
}
this.resetPayload();
break;
}
case "resource" : {
this.FilterTags.notifyLogs('filter-Asset-Name', event.value);
this.resourceSelected = event.value;
this.payload.asset_identifier = this.resourceSelected;
if(this.resourceSelected.toLowerCase() === 'all'){
delete this.payload['asset_identifier'];
}
this.resetPayload();
break;
}
}
}
getRange(e) {
this.sliderFrom = e.from;
this.sliderPercentFrom = e.from_percent;
var resetdate = this.getStartDate(this.selectedTimeRange, this.sliderFrom);
this.payload.start_time = resetdate;
this.resetPayload();
}
resetPayload() {
this.payload.offset = 0;
$(".pagination.justify-content-center li:nth-child(2)")[0].click();
this.callLogsFunc();
}
selectAllAssetsData(){
var value = (<HTMLInputElement>document.getElementById('allasset'))
var resValue = (<HTMLInputElement>document.getElementById('Allidentifier'))
if(value != null) {
value.checked = true;
}
if(resValue != null) {
resValue.checked = true;
}
delete this.payload['asset_identifier'];
delete this.payload['asset_type'];
}
getRangefunc(e) {
this.sliderFrom = e;
this.sliderPercentFrom = e;
var resetdate = this.getStartDate(this.selectedTimeRange, this.sliderFrom);
this.payload.start_time = resetdate;
this.resetPayload();
}
cancelFilter(event) {
switch (event) {
case 'time-range': {
this.instance_yes.onRangeListSelected('Day');
break;
}
case 'time-range-slider': {
this.instance_yes.onTimePeriodSelected(1);
break;
}
case 'period': {
this.instance_yes.onPeriodSelected('15 Minutes');
break;
}
case 'statistic': {
this.instance_yes.onStatisticSelected('Average');
break;
}
case 'account': {
this.instance_yes.onaccSelected('Acc 1');
break;
}
case 'region': {
this.instance_yes.onregSelected('reg 1');
break;
}
case 'env': {
this.instance_yes.onEnvSelect('prod');
break;
}
case 'method': {
this.instance_yes.onMethodListSelected('POST');
break;
}
case 'asset': {
this.instance_yes.getAssetType('all');
break;
}
case 'asset-iden':{
this.instance_yes.getResourceType('all');
break;
}
case 'all': {
this.instance_yes.onRangeListSelected('Day');
this.instance_yes.onPeriodSelected('15 Minutes');
this.instance_yes.onTimePeriodSelected(1);
this.instance_yes.onStatisticSelected('Average');
this.instance_yes.onaccSelected('Acc 1');
this.instance_yes.onregSelected('reg 1');
this.instance_yes.onEnvSelect('prod');
this.instance_yes.onMethodListSelected('POST');
this.instance_yes.getAssetType('all');
this.instance_yes.getResourceType('all');
break;
}
}
this.getRangefunc(1);
}
sendDefaults(range) {
switch (range) {
case 'Day': {
this.FilterTags.notify('filter-Period', '15 Minutes')
break;
}
case 'Week': {
this.FilterTags.notify('filter-Period', '1 Hour')
break;
}
case 'Month': {
this.FilterTags.notify('filter-Period', '6 Hours')
break;
}
case 'Year': {
this.FilterTags.notify('filter-Period', '7 Days')
break;
}
}
}
onRangeListSelected(range) {
this.sendDefaults(range);
this.FilterTags.notifyLogs('filter-TimeRange', range);
this.sliderFrom = 1;
this.FilterTags.notifyLogs('filter-TimeRangeSlider', this.sliderFrom);
var resetdate = this.getStartDate(range, this.sliderFrom);
// this.resetPeriodList(range);
this.selectedTimeRange = range;
this.payload.start_time = resetdate;
this.resetPayload();
}
navigateTo(event) {
var url = "http://search-cloud-api-es-services-smbsxcvtorusqpcygtvtlmzuzq.us-west-2.es.amazonaws.com/_plugin/kibana/app/kibana#/discover?_g=(refreshInterval:(display:Off,pause:!f,value:0),time:(from:now-7d,mode:quick,to:now))&_a=(columns:!(_source),filters:!(('$$hashKey':'object:705','$state':(store:appState),meta:(alias:!n,disabled:!f,index:applicationlogs,key:domain,negate:!f,value:" + this.service.domain + "),query:(match:(domain:(query:" + this.service.domain + ",type:phrase)))),('$$hashKey':'object:100','$state':(store:appState),meta:(alias:!n,disabled:!f,index:applicationlogs,key:servicename,negate:!f,value:" + this.service.domain + "_" + this.service.name + "-prod),query:(match:(servicename:(query:" + this.service.domain + "_" + this.service.name + "-prod,type:phrase))))),index:applicationlogs,interval:auto,query:(query_string:(analyze_wildcard:!t,query:'*')),sort:!(timestamp,desc),uiState:(spy:(mode:(fill:!f,name:!n))))"
window.open(url);
}
expandall() {
for (var i = 0; i < this.logs.length; i++) {
var rowData = this.logs[i];
rowData['expanded'] = true;
}
this.expandText = 'Collapse all';
}
collapseall() {
for (var i = 0; i < this.logs.length; i++) {
var rowData = this.logs[i];
rowData['expanded'] = false;
}
this.expandText = 'Expand all';
}
onRowClicked(row, index) {
var rowData = this.logs[index];
if (rowData) {
rowData['expanded'] = !rowData['expanded'];
this.expandText = 'Collapse all';
for (var i = 0; i < this.logs.length; i++) {
var rowData = this.logs[i];
if (rowData['expanded'] == false) {
this.expandText = 'Expand all';
break;
}
}
}
}
getStartDate(filter, sliderFrom) {
var todayDate = new Date();
switch (filter) {
case "Day":
this.sliderMax = 7;
var resetdate = new Date(todayDate.setDate(todayDate.getDate() - sliderFrom)).toISOString();
break;
case "Week":
this.sliderMax = 5;
var resetdate = new Date(todayDate.setDate(todayDate.getDate() - (sliderFrom * 7))).toISOString();
break;
case "Month":
this.sliderMax = 12;
var currentMonth = new Date((todayDate).toISOString()).getMonth();
var currentDay = new Date((todayDate).toISOString()).getDate();
currentMonth++;
var currentYear = new Date((todayDate).toISOString()).getFullYear();
var diffMonth = currentMonth - sliderFrom;
if (diffMonth > 0) {
var resetYear = currentYear;
var resetMonth = diffMonth;
} else if (diffMonth === 0) {
var resetYear = currentYear - 1;
var resetMonth = 12;
} else if (diffMonth < 0) {
var resetYear = currentYear - 1;
// var resetMonth = sliderFrom - currentMonth;
var resetMonth = 12 + diffMonth;
}
if (currentDay == 31) currentDay = 30;
var newStartDateString = resetYear + "-" + resetMonth + "-" + currentDay + " 00:00:00"
var newStartDate = new Date(newStartDateString);
var resetdate = newStartDate.toISOString();
break;
case "Year":
this.sliderMax = 6;
var currentYear = new Date((todayDate).toISOString()).getFullYear();
var newStartDateString = (currentYear - 6).toString() + "/" + "1" + "/" + "1";
var newStartDate = new Date(newStartDateString);
var resetdate = newStartDate.toISOString();
break;
}
return resetdate;
}
onFilter(column) {
//this.logs = this.logsData
for (var i = 0; i < this.tableHeader.length; i++) {
var col = this.tableHeader[i]
if (col.filter != undefined && col.filter['_value'] != undefined) {
if (col.filter['type'] == 'dateRange') {
// code...
} else {
this.logs = this.filter.filterFunction(col.key, col.filter['_value'], this.logs);
}
}
}
};
onSort(sortData) {
var col = sortData.key;
var reverse = false;
if (sortData.reverse == true) {
reverse = true
}
this.logs = this.sort.sortByColumn(col, reverse, function (x: any) { return x; }, this.logs);
};
callLogsFunc() {
this.loadingState = 'loading';
if (this.subscription) {
this.subscription.unsubscribe();
}
this.subscription = this.http.post('/jazz/logs', this.payload, this.service.id).subscribe(
response => {
if(response.data.logs !== undefined) {
this.logs = response.data.logs || response.data.data.logs;
if (this.logs != undefined)
if (this.logs.length != 0) {
var pageCount = response.data.count;
this.totalPagesTable = 0;
if (pageCount) {
this.totalPagesTable = Math.ceil(pageCount / this.limitValue);
if (this.totalPagesTable === 1) {
this.paginationSelected = false;
}
}
else {
this.totalPagesTable = 0;
}
this.backupLogs = this.logs;
this.sort = new Sort(this.logs);
this.loadingState = 'default'
} else {
this.loadingState = 'empty';
}
this.trim_Message();
}
},
err => {
this.loadingState = 'error';
this.errBody = err._body;
this.errMessage = this.toastmessage.errorMessage(err, "serviceLogs");
try {
this.parsedErrBody = this.errBody;
if (this.parsedErrBody.message != undefined && this.parsedErrBody.message != '') {
this.errMessage = this.errMessage || this.parsedErrBody.message;
}
} catch (e) {
console.log('JSON Parse Error', e);
}
this.getTime();
this.errorURL = window.location.href;
this.errorAPI = env_internal.baseurl + "/jazz/logs";
this.errorRequest = this.payload;
this.errorUser = this.authenticationservice.getUserId();
try {
this.errorResponse = err._body;
}
catch (e) {
console.log('error while parsing json', e);
}
this.cache.set('feedback', this.model.userFeedback)
this.cache.set('api', this.errorAPI)
this.cache.set('request', this.errorRequest)
this.cache.set('resoponse', this.errorResponse)
this.cache.set('url', this.errorURL)
this.cache.set('time', this.errorTime)
this.cache.set('user', this.errorUser)
})
};
getTime() {
var now = new Date();
this.errorTime = ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now.getSeconds()) : (now.getSeconds())));
}
refreshData(event) {
this.loadingState = 'default';
this.resetPayload();
}
paginatePage(currentlyActivePage) {
this.expandText = 'Expand all';
if (this.prevActivePage != currentlyActivePage) {
this.prevActivePage = currentlyActivePage;
this.logs = [];
this.offsetValue = (this.limitValue * (currentlyActivePage - 1));
this.payload.offset = this.offsetValue;
this.callLogsFunc();
// ** call service
/*
* Required:- we need the total number of records from the api, which will be equal to totalPagesTable.
* We should be able to pass start number, size/number of records on each page to the api, where,
* start = (size * currentlyActivePage) + 1
*/
}
else {
}
}
onFilterSelected(filters) {
this.loadingState = 'loading';
var filter;
if (filters[0]) {
filter = filters[0];
}
this.filterloglevel = filter;
this.payload.type = this.filterloglevel;
this.resetPayload();
}
trim_Message() {
if (this.logs != undefined)
for (var i = 0; i < this.logs.length; i++) {
var reg = new RegExp(this.logs[i].timestamp, "g");
this.logs[i].message = this.logs[i].message.replace(reg, '');
this.logs[i].request_id = this.logs[i].request_id.substring(0, this.logs[i].request_id.length - 1);
this.logs[i].message = this.logs[i].message.replace(this.logs[i].request_id, '')
}
}
getenvData() {
let self = this;
if (this.service == undefined) {
return
}
this.http.get('/jazz/environments?domain=' + this.service.domain + '&service=' + this.service.name, null, this.service.id).subscribe(
response => {
response.data.environment.map((item) => {
if (item.physical_id !== "master" && item.status === "deployment_completed") {
self.logsData = item.logical_id;
self.getFilter(self.advancedFilters)
if (this.filterSelectedValue) {
self.instance_yes.filterSelected = true;
}
self.instance_yes.showEnvironment = true;
}
})
},
err => {
console.log("error here: ", err);
}
)
};
fetchEnvlist() {
var env_list = this.cache.get('envList');
if (env_list != undefined) {
this.envList = env_list.friendly_name;
}
}
ngOnChanges(x: any) {
if (x.service.currentValue.domain) {
this.getAssetType();
this.getenvData();
}
this.fetchEnvlist();
}
ngOnInit() {
var todayDate = new Date();
this.payload = {
"service": this.service.name,//"logs", //
"domain": this.service.domain,//"jazz", //
"environment": this.environment, //"dev"
"category": this.service.serviceType === "custom" ? "sls-app" : this.service.serviceType,//"api",//
"size": this.limitValue,
"offset": this.offsetValue,
"type": this.filterloglevel || "ERROR",
"end_time": (new Date().toISOString()).toString(),
"start_time": new Date(todayDate.setDate(todayDate.getDate() - this.sliderFrom)).toISOString()
}
this.selectedEnv = this.environment;
this.callLogsFunc();
}
} | the_stack |
import { AppState } from '../../app.reducer';
import eventManager from '@joplin/lib/eventManager';
import NoteListUtils from '../utils/NoteListUtils';
import { _ } from '@joplin/lib/locale';
import time from '@joplin/lib/time';
import BaseModel from '@joplin/lib/BaseModel';
import bridge from '../../services/bridge';
import Setting from '@joplin/lib/models/Setting';
import NoteListItem from '../NoteListItem';
import CommandService from '@joplin/lib/services/CommandService';
import shim from '@joplin/lib/shim';
import styled from 'styled-components';
import { themeStyle } from '@joplin/lib/theme';
const React = require('react');
const { ItemList } = require('../ItemList.min.js');
const { connect } = require('react-redux');
import Note from '@joplin/lib/models/Note';
import Folder from '@joplin/lib/models/Folder';
const commands = [
require('./commands/focusElementNoteList'),
];
const StyledRoot = styled.div`
width: 100%;
height: 100%;
background-color: ${(props: any) => props.theme.backgroundColor3};
border-right: 1px solid ${(props: any) => props.theme.dividerColor};
`;
class NoteListComponent extends React.Component {
constructor() {
super();
CommandService.instance().componentRegisterCommands(this, commands);
this.itemHeight = 34;
this.state = {
dragOverTargetNoteIndex: null,
width: 0,
height: 0,
};
this.noteListRef = React.createRef();
this.itemListRef = React.createRef();
this.itemAnchorRefs_ = {};
this.renderItem = this.renderItem.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
this.noteItem_titleClick = this.noteItem_titleClick.bind(this);
this.noteItem_noteDragOver = this.noteItem_noteDragOver.bind(this);
this.noteItem_noteDrop = this.noteItem_noteDrop.bind(this);
this.noteItem_checkboxClick = this.noteItem_checkboxClick.bind(this);
this.noteItem_dragStart = this.noteItem_dragStart.bind(this);
this.onGlobalDrop_ = this.onGlobalDrop_.bind(this);
this.registerGlobalDragEndEvent_ = this.registerGlobalDragEndEvent_.bind(this);
this.unregisterGlobalDragEndEvent_ = this.unregisterGlobalDragEndEvent_.bind(this);
this.itemContextMenu = this.itemContextMenu.bind(this);
this.resizableLayout_resize = this.resizableLayout_resize.bind(this);
}
style() {
if (this.styleCache_ && this.styleCache_[this.props.themeId]) return this.styleCache_[this.props.themeId];
const theme = themeStyle(this.props.themeId);
const style = {
root: {
backgroundColor: theme.backgroundColor,
},
listItem: {
maxWidth: '100%',
height: this.itemHeight,
boxSizing: 'border-box',
display: 'flex',
alignItems: 'stretch',
backgroundColor: theme.backgroundColor,
borderBottom: `1px solid ${theme.dividerColor}`,
},
listItemSelected: {
backgroundColor: theme.selectedColor,
},
listItemTitle: {
fontFamily: theme.fontFamily,
fontSize: theme.fontSize,
textDecoration: 'none',
color: theme.color,
cursor: 'default',
whiteSpace: 'nowrap',
flex: 1,
display: 'flex',
alignItems: 'center',
overflow: 'hidden',
},
listItemTitleCompleted: {
opacity: 0.5,
textDecoration: 'line-through',
},
};
this.styleCache_ = {};
this.styleCache_[this.props.themeId] = style;
return style;
}
itemContextMenu(event: any) {
const currentItemId = event.currentTarget.getAttribute('data-id');
if (!currentItemId) return;
let noteIds = [];
if (this.props.selectedNoteIds.indexOf(currentItemId) < 0) {
noteIds = [currentItemId];
} else {
noteIds = this.props.selectedNoteIds;
}
if (!noteIds.length) return;
const menu = NoteListUtils.makeContextMenu(noteIds, {
notes: this.props.notes,
dispatch: this.props.dispatch,
watchedNoteFiles: this.props.watchedNoteFiles,
plugins: this.props.plugins,
inConflictFolder: this.props.selectedFolderId === Folder.conflictFolderId(),
customCss: this.props.customCss,
});
menu.popup(bridge().window());
}
onGlobalDrop_() {
this.unregisterGlobalDragEndEvent_();
this.setState({ dragOverTargetNoteIndex: null });
}
registerGlobalDragEndEvent_() {
if (this.globalDragEndEventRegistered_) return;
this.globalDragEndEventRegistered_ = true;
document.addEventListener('dragend', this.onGlobalDrop_);
}
unregisterGlobalDragEndEvent_() {
this.globalDragEndEventRegistered_ = false;
document.removeEventListener('dragend', this.onGlobalDrop_);
}
dragTargetNoteIndex_(event: any) {
return Math.abs(Math.round((event.clientY - this.itemListRef.current.offsetTop() + this.itemListRef.current.offsetScroll()) / this.itemHeight));
}
noteItem_noteDragOver(event: any) {
if (this.props.notesParentType !== 'Folder') return;
const dt = event.dataTransfer;
if (dt.types.indexOf('text/x-jop-note-ids') >= 0) {
event.preventDefault();
const newIndex = this.dragTargetNoteIndex_(event);
if (this.state.dragOverTargetNoteIndex === newIndex) return;
this.registerGlobalDragEndEvent_();
this.setState({ dragOverTargetNoteIndex: newIndex });
}
}
async noteItem_noteDrop(event: any) {
if (this.props.notesParentType !== 'Folder') return;
if (this.props.noteSortOrder !== 'order') {
const doIt = await bridge().showConfirmMessageBox(_('To manually sort the notes, the sort order must be changed to "%s" in the menu "%s" > "%s"', _('Custom order'), _('View'), _('Sort notes by')), {
buttons: [_('Do it now'), _('Cancel')],
});
if (!doIt) return;
Setting.setValue('notes.sortOrder.field', 'order');
return;
}
// TODO: check that parent type is folder
const dt = event.dataTransfer;
this.unregisterGlobalDragEndEvent_();
this.setState({ dragOverTargetNoteIndex: null });
const targetNoteIndex = this.dragTargetNoteIndex_(event);
const noteIds = JSON.parse(dt.getData('text/x-jop-note-ids'));
void Note.insertNotesAt(this.props.selectedFolderId, noteIds, targetNoteIndex);
}
async noteItem_checkboxClick(event: any, item: any) {
const checked = event.target.checked;
const newNote = {
id: item.id,
todo_completed: checked ? time.unixMs() : 0,
};
await Note.save(newNote, { userSideValidation: true });
eventManager.emit('todoToggle', { noteId: item.id, note: newNote });
}
async noteItem_titleClick(event: any, item: any) {
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
this.props.dispatch({
type: 'NOTE_SELECT_TOGGLE',
id: item.id,
});
} else if (event.shiftKey) {
event.preventDefault();
this.props.dispatch({
type: 'NOTE_SELECT_EXTEND',
id: item.id,
});
} else {
this.props.dispatch({
type: 'NOTE_SELECT',
id: item.id,
});
}
}
noteItem_dragStart(event: any) {
let noteIds = [];
// Here there is two cases:
// - If multiple notes are selected, we drag the group
// - If only one note is selected, we drag the note that was clicked on (which might be different from the currently selected note)
if (this.props.selectedNoteIds.length >= 2) {
noteIds = this.props.selectedNoteIds;
} else {
const clickedNoteId = event.currentTarget.getAttribute('data-id');
if (clickedNoteId) noteIds.push(clickedNoteId);
}
if (!noteIds.length) return;
event.dataTransfer.setDragImage(new Image(), 1, 1);
event.dataTransfer.clearData();
event.dataTransfer.setData('text/x-jop-note-ids', JSON.stringify(noteIds));
}
renderItem(item: any, index: number) {
const highlightedWords = () => {
if (this.props.notesParentType === 'Search') {
const query = BaseModel.byId(this.props.searches, this.props.selectedSearchId);
if (query) {
return this.props.highlightedWords;
}
}
return [];
};
if (!this.itemAnchorRefs_[item.id]) this.itemAnchorRefs_[item.id] = React.createRef();
const ref = this.itemAnchorRefs_[item.id];
return <NoteListItem
ref={ref}
key={item.id}
style={this.style()}
item={item}
index={index}
themeId={this.props.themeId}
width={this.state.width}
height={this.itemHeight}
dragItemIndex={this.state.dragOverTargetNoteIndex}
highlightedWords={highlightedWords()}
isProvisional={this.props.provisionalNoteIds.includes(item.id)}
isSelected={this.props.selectedNoteIds.indexOf(item.id) >= 0}
isWatched={this.props.watchedNoteFiles.indexOf(item.id) < 0}
itemCount={this.props.notes.length}
onCheckboxClick={this.noteItem_checkboxClick}
onDragStart={this.noteItem_dragStart}
onNoteDragOver={this.noteItem_noteDragOver}
onNoteDrop={this.noteItem_noteDrop}
onTitleClick={this.noteItem_titleClick}
onContextMenu={this.itemContextMenu}
/>;
}
itemAnchorRef(itemId: string) {
if (this.itemAnchorRefs_[itemId] && this.itemAnchorRefs_[itemId].current) return this.itemAnchorRefs_[itemId].current;
return null;
}
componentDidUpdate(prevProps: any) {
if (prevProps.selectedNoteIds !== this.props.selectedNoteIds && this.props.selectedNoteIds.length === 1) {
const id = this.props.selectedNoteIds[0];
const doRefocus = this.props.notes.length < prevProps.notes.length;
for (let i = 0; i < this.props.notes.length; i++) {
if (this.props.notes[i].id === id) {
this.itemListRef.current.makeItemIndexVisible(i);
if (doRefocus) {
const ref = this.itemAnchorRef(id);
if (ref) ref.focus();
}
break;
}
}
}
if (prevProps.visible !== this.props.visible) {
this.updateSizeState();
}
}
scrollNoteIndex_(keyCode: any, ctrlKey: any, metaKey: any, noteIndex: any) {
if (keyCode === 33) {
// Page Up
noteIndex -= (this.itemListRef.current.visibleItemCount() - 1);
} else if (keyCode === 34) {
// Page Down
noteIndex += (this.itemListRef.current.visibleItemCount() - 1);
} else if ((keyCode === 35 && ctrlKey) || (keyCode === 40 && metaKey)) {
// CTRL+End, CMD+Down
noteIndex = this.props.notes.length - 1;
} else if ((keyCode === 36 && ctrlKey) || (keyCode === 38 && metaKey)) {
// CTRL+Home, CMD+Up
noteIndex = 0;
} else if (keyCode === 38 && !metaKey) {
// Up
noteIndex -= 1;
} else if (keyCode === 40 && !metaKey) {
// Down
noteIndex += 1;
}
if (noteIndex < 0) noteIndex = 0;
if (noteIndex > this.props.notes.length - 1) noteIndex = this.props.notes.length - 1;
return noteIndex;
}
async onKeyDown(event: any) {
const keyCode = event.keyCode;
const noteIds = this.props.selectedNoteIds;
if (noteIds.length > 0 && (keyCode === 40 || keyCode === 38 || keyCode === 33 || keyCode === 34 || keyCode === 35 || keyCode == 36)) {
// DOWN / UP / PAGEDOWN / PAGEUP / END / HOME
const noteId = noteIds[0];
let noteIndex = BaseModel.modelIndexById(this.props.notes, noteId);
noteIndex = this.scrollNoteIndex_(keyCode, event.ctrlKey, event.metaKey, noteIndex);
const newSelectedNote = this.props.notes[noteIndex];
this.props.dispatch({
type: 'NOTE_SELECT',
id: newSelectedNote.id,
});
this.itemListRef.current.makeItemIndexVisible(noteIndex);
this.focusNoteId_(newSelectedNote.id);
event.preventDefault();
}
if (noteIds.length && (keyCode === 46 || (keyCode === 8 && event.metaKey))) {
// DELETE / CMD+Backspace
event.preventDefault();
await NoteListUtils.confirmDeleteNotes(noteIds);
}
if (noteIds.length && keyCode === 32) {
// SPACE
event.preventDefault();
const notes = BaseModel.modelsByIds(this.props.notes, noteIds);
const todos = notes.filter((n: any) => !!n.is_todo);
if (!todos.length) return;
for (let i = 0; i < todos.length; i++) {
const toggledTodo = Note.toggleTodoCompleted(todos[i]);
await Note.save(toggledTodo);
}
this.focusNoteId_(todos[0].id);
}
if (keyCode === 9) {
// TAB
event.preventDefault();
if (event.shiftKey) {
void CommandService.instance().execute('focusElement', 'sideBar');
} else {
void CommandService.instance().execute('focusElement', 'noteTitle');
}
}
if (event.keyCode === 65 && (event.ctrlKey || event.metaKey)) {
// Ctrl+A key
event.preventDefault();
this.props.dispatch({
type: 'NOTE_SELECT_ALL',
});
}
}
focusNoteId_(noteId: string) {
// - We need to focus the item manually otherwise focus might be lost when the
// list is scrolled and items within it are being rebuilt.
// - We need to use an interval because when leaving the arrow pressed, the rendering
// of items might lag behind and so the ref is not yet available at this point.
if (!this.itemAnchorRef(noteId)) {
if (this.focusItemIID_) shim.clearInterval(this.focusItemIID_);
this.focusItemIID_ = shim.setInterval(() => {
if (this.itemAnchorRef(noteId)) {
this.itemAnchorRef(noteId).focus();
shim.clearInterval(this.focusItemIID_);
this.focusItemIID_ = null;
}
}, 10);
} else {
this.itemAnchorRef(noteId).focus();
}
}
updateSizeState() {
this.setState({
width: this.noteListRef.current.clientWidth,
height: this.noteListRef.current.clientHeight,
});
}
resizableLayout_resize() {
this.updateSizeState();
}
componentDidMount() {
this.props.resizableLayoutEventEmitter.on('resize', this.resizableLayout_resize);
this.updateSizeState();
}
componentWillUnmount() {
if (this.focusItemIID_) {
shim.clearInterval(this.focusItemIID_);
this.focusItemIID_ = null;
}
this.props.resizableLayoutEventEmitter.off('resize', this.resizableLayout_resize);
CommandService.instance().componentUnregisterCommands(commands);
}
renderEmptyList() {
if (this.props.notes.length) return null;
const theme = themeStyle(this.props.themeId);
const padding = 10;
const emptyDivStyle = {
padding: `${padding}px`,
fontSize: theme.fontSize,
color: theme.color,
backgroundColor: theme.backgroundColor,
fontFamily: theme.fontFamily,
};
// emptyDivStyle.width = emptyDivStyle.width - padding * 2;
// emptyDivStyle.height = emptyDivStyle.height - padding * 2;
return <div style={emptyDivStyle}>{this.props.folders.length ? _('No notes in here. Create one by clicking on "New note".') : _('There is currently no notebook. Create one by clicking on "New notebook".')}</div>;
}
renderItemList(style: any) {
if (!this.props.notes.length) return null;
return (
<ItemList
ref={this.itemListRef}
disabled={this.props.isInsertingNotes}
itemHeight={this.style().listItem.height}
className={'note-list'}
items={this.props.notes}
style={style}
itemRenderer={this.renderItem}
onKeyDown={this.onKeyDown}
/>
);
}
render() {
if (!this.props.size) throw new Error('props.size is required');
return (
<StyledRoot ref={this.noteListRef}>
{this.renderEmptyList()}
{this.renderItemList(this.props.size)}
</StyledRoot>
);
}
}
const mapStateToProps = (state: AppState) => {
return {
notes: state.notes,
folders: state.folders,
selectedNoteIds: state.selectedNoteIds,
selectedFolderId: state.selectedFolderId,
themeId: state.settings.theme,
notesParentType: state.notesParentType,
searches: state.searches,
selectedSearchId: state.selectedSearchId,
watchedNoteFiles: state.watchedNoteFiles,
provisionalNoteIds: state.provisionalNoteIds,
isInsertingNotes: state.isInsertingNotes,
noteSortOrder: state.settings['notes.sortOrder.field'],
highlightedWords: state.highlightedWords,
plugins: state.pluginService.plugins,
customCss: state.customCss,
};
};
export default connect(mapStateToProps)(NoteListComponent); | the_stack |
import { Components, getFragment, registerComponent } from '../../lib/vulcan-lib';
import React, { useState } from 'react';
import times from 'lodash/times';
import groupBy from 'lodash/groupBy';
import maxBy from 'lodash/maxBy';
import { useMutation, useQuery, gql } from '@apollo/client';
import { useCurrentUser } from '../common/withUser';
import classNames from 'classnames';
import { randomId } from '../../lib/random';
import { elicitSourceId, elicitSourceURL } from '../../lib/publicSettings';
import { useDialog } from '../common/withDialog';
import sortBy from 'lodash/sortBy';
import some from 'lodash/some';
import withErrorBoundary from '../common/withErrorBoundary';
const elicitDataFragment = `
_id
title
notes
resolvesBy
resolution
predictions {
_id,
predictionId,
prediction,
createdAt,
notes,
sourceUrl,
sourceId,
binaryQuestionId
creator {
_id,
displayName,
sourceUserId
lwUser {
...UsersMinimumInfo
}
}
}
`
const elicitQuery = gql`
query ElicitBlockData($questionId: String) {
ElicitBlockData(questionId: $questionId) {
${elicitDataFragment}
}
}
${getFragment("UsersMinimumInfo")}
`;
const rootHeight = 50
const rootPaddingTop = 12
const styles = (theme: ThemeType): JssStyles => ({
root: {
position: 'relative',
paddingTop: rootPaddingTop,
marginBottom: 0
},
histogramRoot: {
height: rootHeight,
display: 'flex'
},
histogramBucket: {
display: 'flex',
flexGrow: 1,
justifyContent: 'flex-end',
'&:hover $sliceColoredArea': {
backgroundColor: theme.palette.panelBackground.darken15,
},
'&:hover $usersInBucket': {
display: 'block'
}
},
histogramSlice: {
flexGrow: 1,
marginTop: 'auto',
width: '10%',
height: '100%',
cursor: 'pointer',
position: 'relative',
display: 'flex',
flexDirection: 'column',
'&:hover': {
'& $additionalVoteArea': {
backgroundColor: theme.palette.panelBackground.darken05,
},
'& $sliceColoredArea': {
backgroundColor: theme.palette.panelBackground.darken20,
},
'& $sliceNumber': {
opacity: 1,
}
}
},
histogramBucketCurrentUser: {
'& $sliceColoredArea': {
backgroundColor: theme.palette.primary.main
},
'&:hover $sliceColoredArea': {
backgroundColor: theme.palette.primary.main
},
'&:hover $histogramSliceCurrentUser $sliceColoredArea': {
backgroundColor: theme.palette.primary.dark
},
'& $sliceColoredArea:hover': {
backgroundColor: theme.palette.primary.dark
},
'&:hover $additionalVoteArea': {
backgroundColor: 'transparent',
height: '0% !important'
}
},
histogramSliceCurrentUser: {
'& $sliceColoredArea': {
backgroundColor: theme.palette.primary.dark
},
'&:hover': {
'& $additionalVoteArea': {
backgroundColor: 'transparent'
},
'& $sliceColoredArea': {
backgroundColor: theme.palette.primary.dark
}
}
},
sliceNumber: {
opacity: 0,
whiteSpace: 'nowrap',
position: 'absolute',
top: -20
},
invertedSliceNumber: {
// This number is right-aligned in the slice (and so overflows left) because
// if it were left-aligned or centered, it would escape the widget's bounding
// box on the right side, causing horizontal scrolling
right: 0
},
sliceColoredArea: {
backgroundColor: theme.palette.panelBackground.darken10,
},
additionalVoteArea: {
marginTop: 'auto',
position: 'relative'
},
titleSection: {
textAlign: 'center',
width: '100%',
color: theme.palette.text.dim60,
marginTop: 4,
paddingBottom: 4,
display: 'flex',
justifyContent: 'space-between'
},
hiddenTitleSection: {
opacity: 0
},
startPercentage: {
whiteSpace: 'nowrap',
},
endPercentage: {
whiteSpace: 'nowrap'
},
title: {
padding: '0px 10px'
},
usersInBucket: {
position: 'absolute',
bottom: 0,
left: 0,
display: 'none',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
width: '100%',
color: theme.palette.text.dim60,
height: `calc(100% - ${rootHeight + rootPaddingTop}px)`,
paddingTop: 4,
zIndex: 1 // Ensure that the users are displayed on top of the title element
},
name: {
marginRight: 4
}
})
const ElicitBlock = ({ classes, questionId = "IyWNjzc5P" }: {
classes: ClassesType,
questionId: String
}) => {
const currentUser = useCurrentUser();
const [hideTitle, setHideTitle] = useState(false);
const {openDialog} = useDialog();
const { UsersName, ContentStyles } = Components;
const { data, loading } = useQuery(elicitQuery, { ssr: true, variables: { questionId } })
const [makeElicitPrediction] = useMutation(gql`
mutation ElicitPrediction($questionId:String, $prediction: Int) {
MakeElicitPrediction(questionId:$questionId, prediction: $prediction) {
${elicitDataFragment}
}
}
${getFragment("UsersMinimumInfo")}
`);
const sortedPredictions = sortBy(data?.ElicitBlockData?.predictions || [], ({prediction}) => prediction)
const roughlyGroupedData = groupBy(sortedPredictions, ({prediction}) => Math.floor(prediction / 10) * 10)
const finelyGroupedData = groupBy(sortedPredictions, ({prediction}) => Math.floor(prediction))
const userHasPredicted = currentUser && some(
sortedPredictions,
(prediction: any) => prediction?.creator?.lwUser?._id === currentUser._id
);
const [revealed, setRevealed] = useState(false);
const predictionsHidden = currentUser?.hideElicitPredictions && !userHasPredicted && !revealed;
const maxSize = (maxBy(Object.values(roughlyGroupedData), arr => arr.length) || []).length
return <ContentStyles contentType="comment" className={classes.root}>
<div className={classes.histogramRoot}>
{times(10, (bucket) => <div key={bucket}
className={classNames(classes.histogramBucket, {
[classes.histogramBucketCurrentUser]: roughlyGroupedData[`${bucket*10}`]?.some(({creator}) => currentUser && creator?.sourceUserId === currentUser._id)
})}
onMouseEnter={() => roughlyGroupedData[`${bucket*10}`]?.length && setHideTitle(true)}
onMouseLeave={() => setHideTitle(false)}
>
{times(10, offset => {
const prob = (bucket*10) + offset;
const isCurrentUserSlice = finelyGroupedData[`${prob}`]?.some(({creator}) => currentUser && creator?.sourceUserId === currentUser._id)
if (prob === 0) return null
return <div
className={classNames(classes.histogramSlice, {
[classes.histogramSliceCurrentUser]: isCurrentUserSlice
})}
key={prob}
data-num-largebucket={roughlyGroupedData[`${bucket*10}`]?.length || 0}
data-num-smallbucket={finelyGroupedData[`${prob}`]?.length || 0}
onClick={() => {
if (currentUser) {
const predictions = data?.ElicitBlockData?.predictions || []
const filteredPredictions = predictions.filter(prediction => prediction?.creator?.sourceUserId !== currentUser._id)
// When you click on the slice that corresponds to your current prediction, you cancel it (i.e. double-clicking cancels any current predictions)
const newPredictions = isCurrentUserSlice ? filteredPredictions : [createNewElicitPrediction(data?.ElicitBlockData?._id, prob, currentUser), ...filteredPredictions]
setRevealed(true);
void makeElicitPrediction({
variables: { questionId, prediction: !isCurrentUserSlice ? prob : null },
optimisticResponse: {
__typename: "Mutation",
MakeElicitPrediction: {
...data?.ElicitBlockData,
__typename: "ElicitBlockData",
predictions: newPredictions
}
}
})
} else {
openDialog({
componentName: "LoginPopup",
componentProps: {}
});
}
}}
>
<div
className={classes.additionalVoteArea}
style={{height: `${(1 / (maxSize+1))*100 || 0}%`}}
>
<div className={classNames(classes.sliceNumber, {[classes.invertedSliceNumber]: prob > 94})}>{prob}%</div>
</div>
{!predictionsHidden && <div
className={classes.sliceColoredArea}
style={{height: `${(roughlyGroupedData[`${bucket*10}`]?.length / (maxSize+1))*100 || 0}%`}}
/>}
</div>
})}
{!predictionsHidden && roughlyGroupedData[`${bucket*10}`] && <div className={classes.usersInBucket}>
{roughlyGroupedData[`${bucket*10}`]?.map(({creator, prediction}, i) => <span key={creator?._id} className={classes.name}>
{creator?.lwUser ? <UsersName user={creator?.lwUser} tooltipPlacement={"bottom"} /> : creator?.displayName} ({prediction}%){i !== (roughlyGroupedData[`${bucket*10}`].length - 1) && ","}
</span>)}
</div>}
</div>)}
</div>
<div className={classNames(classes.titleSection, {[classes.hiddenTitleSection]: hideTitle})}>
<div className={classes.startPercentage}>1%</div>
<div className={classes.title}>
{data?.ElicitBlockData?.title || (loading ? null : "Can't find Question Title on Elicit")}
{!loading && predictionsHidden && <a onClick={()=>setRevealed(true)}>
{" "}(Reveal)
</a>}
</div>
<div className={classes.endPercentage}>99%</div>
</div>
</ContentStyles>
}
const ElicitBlockComponent = registerComponent('ElicitBlock', ElicitBlock, {
styles,
hocs: [withErrorBoundary],
});
declare global {
interface ComponentTypes {
ElicitBlock: typeof ElicitBlockComponent
}
}
function createNewElicitPrediction(questionId: string, prediction: number, currentUser: UsersMinimumInfo) {
return {
__typename: "ElicitPrediction",
_id: randomId(),
predictionId: randomId(),
prediction: prediction,
createdAt: new Date(),
notes: "",
sourceUrl: elicitSourceURL.get(),
sourceId: elicitSourceId.get(),
binaryQuestionId: questionId,
creator: {
__typename: "ElicitUser",
_id: randomId(),
displayName: currentUser.displayName,
sourceUserId: currentUser._id,
lwUser: currentUser
}
}
} | the_stack |
// Mocha discourages using arrow functions, see https://mochajs.org/#arrow-functions
import {
assertRejected,
getTestResourceUrl,
silenceLoggingAroundFunction,
stubGlobalConstructor
} from "@here/harp-test-utils";
import * as chai from "chai";
import * as chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
const { expect, assert } = chai;
import * as sinon from "sinon";
import { WorkerLoader } from "../lib/workers/WorkerLoader";
import { FakeWebWorker, willExecuteWorkerScript } from "./FakeWebWorker";
declare const global: any;
const workerDefined = typeof Worker !== "undefined" && typeof Blob !== "undefined";
const describeWithWorker = workerDefined ? describe : xdescribe;
const testWorkerUrl = getTestResourceUrl("@here/harp-mapview", "test/resources/testWorker.js");
describeWithWorker("Web Worker API", function () {
it("Worker is able to load worker from blob", done => {
// note, for this test to work, CSP (Content Security Policy)
// must allow for executing workers from blob:
// example:
// child-src blob: (legacy)
// worker-src: blob: (new, but not yet recognized by browsers)
const script = `
self.postMessage({ hello: 'world' });
`;
assert.isDefined(Blob);
const blob = new Blob([script], { type: "application/javascript" });
assert.isTrue(blob.size > 0);
const worker = new Worker(URL.createObjectURL(blob));
worker.addEventListener("message", event => {
assert.isDefined(event.data);
assert.equal(event.data.hello, "world");
done();
});
worker.addEventListener("error", msg => {
done(new Error("received error event"));
});
});
it("Worker is able to load worker from URL", done => {
const worker = new Worker(testWorkerUrl);
worker.addEventListener("message", event => {
assert.isDefined(event.data);
assert.equal(event.data.hello, "world");
done();
});
worker.addEventListener("error", msg => {
done(new Error("received error event"));
});
});
});
describe("WorkerLoader", function () {
let sandbox: sinon.SinonSandbox;
beforeEach(function () {
sandbox = sinon.createSandbox();
if (typeof window === "undefined") {
// fake Worker constructor for node environment
global.Worker = FakeWebWorker;
}
});
afterEach(function () {
sandbox.restore();
if (typeof window === "undefined") {
delete global.Worker;
}
WorkerLoader.directlyFallbackToBlobBasedLoading = false;
});
describe("works in mocked environment", function () {
it("#startWorker starts worker not swalling first message", async function () {
const workerConstructorStub = stubGlobalConstructor(sandbox, "Worker");
willExecuteWorkerScript(workerConstructorStub, (self, scriptUrl) => {
self.postMessage({ hello: "world" });
});
const worker = await WorkerLoader.startWorker(testWorkerUrl);
await new Promise<void>((resolve, reject) => {
worker.addEventListener("message", event => {
assert.isDefined(event.data);
assert.equal(event.data.hello, "world");
resolve();
});
worker.addEventListener("error", msg => {
reject(new Error("received error event"));
});
});
assert.equal(workerConstructorStub.callCount, 1);
assert.equal(workerConstructorStub.firstCall.args[0], testWorkerUrl);
});
it("#startWorker fails on timeout", async function () {
const workerConstructorStub = stubGlobalConstructor(sandbox, "Worker");
willExecuteWorkerScript(workerConstructorStub, () => {
// We intentionally do not send anything, so waitForWorkerInitialized
// should raise timeout error.
// self.postMessage({ hello: "world" });
});
await assertRejected(WorkerLoader.startWorker(testWorkerUrl, 10), /timeout/i);
});
it("#startWorker fails on error in script", async function () {
const workerConstructorStub = stubGlobalConstructor(sandbox, "Worker");
willExecuteWorkerScript(workerConstructorStub, () => {
// We intentionally throw error in global context to see if it is caught by
// workerLoader.
(null as any).foo = "aa";
});
await assertRejected(
WorkerLoader.startWorker(testWorkerUrl, 50),
/Error during worker initialization/i
);
});
});
describeWithWorker("real Workers integration", function () {
describe("basic operations", function () {
it("#startWorker starts worker not swalling first message", async function () {
const script = `
self.postMessage({ hello: 'world' });
`;
assert.isDefined(Blob);
const blob = new Blob([script], { type: "application/javascript" });
const worker = await WorkerLoader.startWorker(URL.createObjectURL(blob));
await new Promise<void>((resolve, reject) => {
worker.addEventListener("message", event => {
assert.isDefined(event.data);
assert.equal(event.data.hello, "world");
resolve();
});
worker.addEventListener("error", msg => {
reject(new Error("received error event"));
});
});
});
it("#startWorker fails on timeout", async function () {
const script = `
// We intentionally throw error in global context to see if it is caught by
// workerLoader.
//self.postMessage({ hello: 'world' });
`;
assert.isDefined(Blob);
const blob = new Blob([script], { type: "application/javascript" });
await assertRejected(
WorkerLoader.startWorker(URL.createObjectURL(blob), 10),
/timeout/i
);
});
it("#startWorker catches error in worker global context", function () {
const script = `
// We intentionally do not send anything, so waitForWorkerInitialized
// should raise timeout error.
null.foo = "aa";
`;
assert.isDefined(Blob);
const blob = new Blob([script], { type: "application/javascript" });
const listener = () => {
(Mocha as any).process.removeListener("uncaughtException", listener);
};
(Mocha as any).process.on("uncaughtException", listener);
return expect(
WorkerLoader.startWorker(URL.createObjectURL(blob))
).to.be.rejectedWith(Error);
});
});
describe("loading of cross-origin scripts", function () {
const cspTestScriptUrl = "https://example.com/foo.js";
it("#startWorker falls back to blob in case of sync error", async function () {
// setup an environment in which any attempt to load worker from from non-blob,
// cross-origin URL which fails, so we check if WorkerLoader will attempt to
// load using blob: fallback
//
// sync version - mimics Chrome, which in case of CSP violation throws error
// immediately from Worker constructor
const originalWorkerConstructor = Worker;
const workerConstructorStub = stubGlobalConstructor(sandbox, "Worker") as any;
workerConstructorStub.callsFake(function (this: Worker, scriptUrl: string) {
if (!scriptUrl.startsWith("blob:")) {
throw new Error("content policy violated, ouch");
} else {
return new originalWorkerConstructor(scriptUrl);
}
});
const originalFetch = fetch;
const fetchStub = sandbox.stub(window, "fetch");
fetchStub.callsFake(async (url: RequestInfo) => {
assert.equal(url, cspTestScriptUrl);
return await originalFetch(testWorkerUrl);
});
await silenceLoggingAroundFunction("WorkerLoader", async () => {
const worker = await WorkerLoader.startWorker(cspTestScriptUrl);
await new Promise<void>((resolve, reject) => {
worker.addEventListener("message", event => {
assert.isDefined(event.data);
assert.equal(event.data.hello, "world");
resolve();
});
worker.addEventListener("error", msg => {
reject(new Error("received error event"));
});
});
assert.isTrue(fetchStub.calledOnce);
assert.equal(workerConstructorStub.callCount, 2);
assert.equal(workerConstructorStub.firstCall.args[0], cspTestScriptUrl);
assert(workerConstructorStub.secondCall.args[0].startsWith, "blob:");
});
});
it("#startWorker falls back to blob in case of async error", async function () {
// setup an environment in which any attempt to load worker from from non-blob,
// cross-origin URL which fails, so we check if WorkerLoader will attempt to
// load using blob: fallback
//
// async version - mimics Firefox, which in case of CSP violation signals error
// asynchronously with 'error' event
const originalWorkerConstructor = Worker;
const workerConstructorStub = stubGlobalConstructor(sandbox, "Worker") as any;
workerConstructorStub.callsFake(function (this: Worker, scriptUrl: string) {
const actualWorker = new originalWorkerConstructor(scriptUrl);
if (!scriptUrl.startsWith("blob:")) {
setTimeout(() => {
actualWorker.dispatchEvent(new ErrorEvent("error"));
}, 0);
}
return actualWorker;
});
const originalFetch = fetch;
const fetchStub = sandbox.stub(window, "fetch");
fetchStub.callsFake(async (url: RequestInfo) => {
assert.equal(url, cspTestScriptUrl);
return await originalFetch(testWorkerUrl);
});
await silenceLoggingAroundFunction("WorkerLoader", async () => {
const worker = await WorkerLoader.startWorker(cspTestScriptUrl);
await new Promise<void>((resolve, reject) => {
worker.addEventListener("message", event => {
assert.isDefined(event.data);
assert.equal(event.data.hello, "world");
resolve();
});
worker.addEventListener("error", msg => {
reject(new Error("received error event"));
});
});
assert.isTrue(fetchStub.calledOnce);
assert.equal(workerConstructorStub.callCount, 2);
assert.equal(workerConstructorStub.firstCall.args[0], cspTestScriptUrl);
assert(workerConstructorStub.secondCall.args[0].startsWith, "blob:");
});
});
});
});
}); | the_stack |
import React, { SyntheticEvent, Fragment } from "react";
import ReactDOM from "react-dom";
import _ from "lodash";
import {
Player, BigPlayButton, ControlBar, CurrentTimeDisplay,
TimeDivider, PlaybackRateMenuButton, VolumeMenuButton,
} from "video-react";
import { IAssetProps } from "./assetPreview";
import { IAsset, AssetType, AssetState } from "../../../../models/applicationState";
import { AssetService } from "../../../../services/assetService";
import { CustomVideoPlayerButton } from "../../common/videoPlayer/customVideoPlayerButton";
import { strings } from "../../../../common/strings";
/**
* VideoAsset component properties
*/
export interface IVideoAssetProps extends IAssetProps, React.Props<VideoAsset> {
/** Whether or not the video asset should start playing automatically */
autoPlay?: boolean;
/** The timestamp that the video should seek to upon loading */
timestamp?: number;
/** The event handler that is fired when a child video frame is selected (ex. paused, seeked) */
onChildAssetSelected?: (asset: IAsset) => void;
}
/** VideoAsset internal component state */
export interface IVideoAssetState {
loaded: boolean;
}
/**
* VideoPlayer internal video state
*/
export interface IVideoPlayerState {
readyState: number;
paused: boolean;
seeking: boolean;
currentTime: number;
duration: number;
}
/**
* VideoAsset component used to display video based assets
*/
export class VideoAsset extends React.Component<IVideoAssetProps> {
/** Default properties for the VideoAsset if not defined */
public static defaultProps: IVideoAssetProps = {
autoPlay: true,
controlsEnabled: true,
timestamp: null,
asset: null,
childAssets: [],
};
public state: IVideoAssetState = {
loaded: false,
};
private videoPlayer: React.RefObject<Player> = React.createRef<Player>();
private timelineElement: Element = null;
public render() {
const { autoPlay, asset } = this.props;
let videoPath = asset.path;
if (!autoPlay) {
videoPath = `${asset.path}#t=5.0`;
}
return (
<Player ref={this.videoPlayer}
fluid={false}
width="100%"
height="100%"
autoPlay={autoPlay}
src={videoPath}
onError={this.props.onError}
crossOrigin="anonymous">
<BigPlayButton position="center" />
{autoPlay &&
<ControlBar autoHide={false}>
{!this.props.controlsEnabled &&
<Fragment>
<div className="video-react-control-bar-disabled"></div>
</Fragment>
}
<CustomVideoPlayerButton order={1.1}
accelerators={["ArrowLeft", "A", "a"]}
tooltip={strings.editorPage.videoPlayer.previousExpectedFrame.tooltip}
onClick={this.movePreviousExpectedFrame}
icon={"fa-caret-left fa-lg"}
>
<i className="fas fa-caret-left fa-lg" />
</CustomVideoPlayerButton>
<CustomVideoPlayerButton order={1.2}
accelerators={["ArrowRight", "D", "d"]}
tooltip={strings.editorPage.videoPlayer.nextExpectedFrame.tooltip}
onClick={this.moveNextExpectedFrame}
icon={"fa-caret-right fa-lg"}
>
<i className="fas fa-caret-right fa-lg" />
</CustomVideoPlayerButton>
<CurrentTimeDisplay order={1.3} />
<TimeDivider order={1.4} />
<PlaybackRateMenuButton rates={[5, 2, 1, 0.5, 0.25]} order={7.1} />
<VolumeMenuButton enabled order={7.2} />
<CustomVideoPlayerButton order={8.1}
accelerators={["Q", "q"]}
tooltip={strings.editorPage.videoPlayer.previousTaggedFrame.tooltip}
onClick={this.movePreviousTaggedFrame}
icon={"fas fa-step-backward"}
>
<i className="fas fa-step-backward"></i>
</CustomVideoPlayerButton>
<CustomVideoPlayerButton order={8.2}
accelerators={["E", "e"]}
tooltip={strings.editorPage.videoPlayer.nextTaggedFrame.tooltip}
onClick={this.moveNextTaggedFrame}
icon={"fa-step-forward"}
>
<i className="fas fa-step-forward"></i>
</CustomVideoPlayerButton>
</ControlBar>
}
</Player >
);
}
public componentDidMount() {
if (this.props.autoPlay) {
// We only need to subscribe to state change notificeations if autoPlay
// is true, otherwise the video is simply a preview on the side bar that
// doesn't change
this.videoPlayer.current.subscribeToStateChange(this.onVideoStateChange);
}
}
public componentDidUpdate(prevProps: Readonly<IVideoAssetProps>) {
if (this.props.asset.id !== prevProps.asset.id) {
this.setState({ loaded: false });
}
if (this.props.childAssets !== prevProps.childAssets) {
this.addAssetTimelineTags(this.props.childAssets, this.getVideoPlayerState().duration);
}
if (this.props.timestamp !== prevProps.timestamp) {
this.seekToTime(this.props.timestamp);
}
}
/**
* Bound to the "Previous Tagged Frame" button
* Seeks the user to the previous tagged video frame
*/
private movePreviousTaggedFrame = () => {
const currentTime = this.getVideoPlayerState().currentTime;
const previousFrame = _
.reverse(this.props.childAssets)
.find((asset) => asset.state === AssetState.Tagged && asset.timestamp < currentTime);
if (previousFrame) {
this.seekToTime(previousFrame.timestamp);
}
}
/**
* Bound to the "Next Tagged Frame" button
* Seeks the user to the next tagged video frame
*/
private moveNextTaggedFrame = () => {
const currentTime = this.getVideoPlayerState().currentTime;
const nextFrame = this.props.childAssets
.find((asset) => asset.state === AssetState.Tagged && asset.timestamp > currentTime);
if (nextFrame) {
this.seekToTime(nextFrame.timestamp);
}
}
/**
* Moves the videos current position forward one frame based on the current
* project settings for frame rate extraction
*/
private moveNextExpectedFrame = () => {
const currentTime = this.getVideoPlayerState().currentTime;
// Seek forward from the current time to the next logical frame based on project settings
const frameSkipTime: number = (1 / this.props.additionalSettings.videoSettings.frameExtractionRate);
const seekTime: number = (currentTime + frameSkipTime);
this.seekToTime(seekTime);
}
/**
* Moves the videos current position backward one frame based on the current
* project settings for frame rate extraction
*/
private movePreviousExpectedFrame = () => {
const currentTime = this.getVideoPlayerState().currentTime;
// Seek backwards from the current time to the next logical frame based on project settings
const frameSkipTime: number = (1 / this.props.additionalSettings.videoSettings.frameExtractionRate);
const seekTime: number = (currentTime - frameSkipTime);
this.seekToTime(seekTime);
}
/**
* Seeks the current video to the passed in time stamp, pausing the video before hand
* @param seekTime - Time (in seconds) in the video to seek to
*/
private seekToTime = (seekTime: number) => {
const playerState = this.getVideoPlayerState();
if (seekTime >= 0 && playerState.currentTime !== seekTime) {
// Verifies if the seek operation should continue
if (this.props.onBeforeAssetChanged) {
if (!this.props.onBeforeAssetChanged()) {
return;
}
}
// Before seeking, pause the video
if (!playerState.paused) {
this.videoPlayer.current.pause();
}
this.videoPlayer.current.seek(seekTime);
}
}
private onVideoStateChange = (state: Readonly<IVideoPlayerState>, prev: Readonly<IVideoPlayerState>) => {
if (!this.state.loaded && state.readyState === 4 && state.readyState !== prev.readyState) {
// Video initial load complete
this.raiseLoaded();
this.raiseActivated();
if (this.props.autoPlay) {
this.videoPlayer.current.play();
}
} else if (state.paused && (state.currentTime !== prev.currentTime || state.seeking !== prev.seeking)) {
// Video is paused, make sure we are on a key frame, and if we are not, seek to that
// before raising the child selected event
if (this.isValidKeyFrame()) {
this.raiseChildAssetSelected(state);
this.raiseDeactivated();
}
} else if (!state.paused && state.paused !== prev.paused) {
// Video has resumed playing
this.raiseActivated();
}
}
/**
* Raises the "loaded" event if available
*/
private raiseLoaded = () => {
this.setState({
loaded: true,
}, () => {
if (this.props.onLoaded) {
this.props.onLoaded(this.videoPlayer.current.video.video);
}
// Once the video is loaded, add any asset timeline tags
this.addAssetTimelineTags(this.props.childAssets, this.getVideoPlayerState().duration);
});
}
/**
* Raises the "childAssetSelected" event if available
*/
private raiseChildAssetSelected = (state: Readonly<IVideoPlayerState>) => {
if (this.props.onChildAssetSelected) {
const rootAsset = this.props.asset.parent || this.props.asset;
const childPath = `${rootAsset.path}#t=${state.currentTime}`;
const childAsset = AssetService.createAssetFromFilePath(childPath);
childAsset.state = AssetState.NotVisited;
childAsset.type = AssetType.VideoFrame;
childAsset.parent = rootAsset;
childAsset.timestamp = state.currentTime;
childAsset.size = { ...this.props.asset.size };
this.props.onChildAssetSelected(childAsset);
}
}
/**
* Raises the "activated" event if available
*/
private raiseActivated = () => {
if (this.props.onActivated) {
this.props.onActivated(this.videoPlayer.current.video.video);
}
}
/**
* Raises the "deactivated event if available"
*/
private raiseDeactivated = () => {
if (this.props.onDeactivated) {
this.props.onDeactivated(this.videoPlayer.current.video.video);
}
}
/**
* Move to the nearest key frame from where the video's current
* position is
* @returns true if moved to a new position; false otherwise
*/
private isValidKeyFrame = (): boolean => {
if (!this.props.additionalSettings) {
return false;
}
const keyFrameTime = (1 / this.props.additionalSettings.videoSettings.frameExtractionRate);
const timestamp = this.getVideoPlayerState().currentTime;
// Calculate the nearest key frame
const numberKeyFrames = Math.round(timestamp / keyFrameTime);
const seekTime = +(numberKeyFrames * keyFrameTime).toFixed(6);
if (seekTime !== timestamp) {
this.seekToTime(seekTime);
}
return seekTime === timestamp;
}
/**
* Draws small lines to show where visited and tagged frames are on
* the video line
* @param childAssets - Array of child assets in the video
* @param videoDuration - Length (in seconds) of the video
*/
private addAssetTimelineTags = (childAssets: any[], videoDuration: number) => {
if (!this.props.autoPlay) {
return;
}
const assetTimelineTagLines = this.renderTimeline(childAssets, videoDuration);
const timelineSelector = ".editor-page-content-main-body .video-react-progress-control .video-timeline-root";
this.timelineElement = document.querySelector(timelineSelector);
if (!this.timelineElement) {
const progressControlSelector = ".editor-page-content-main-body .video-react-progress-control";
const progressHolderElement = document.querySelector(progressControlSelector);
// If we found an element to hold the tags, add them to it
if (progressHolderElement) {
this.timelineElement = document.createElement("div");
this.timelineElement.className = "video-timeline-root";
progressHolderElement.appendChild(this.timelineElement);
}
}
if (this.timelineElement) {
// Render the child asset elements to the dom
ReactDOM.render(assetTimelineTagLines, this.timelineElement);
}
}
/**
* Renders the timeline markers for the specified child assets
* @param childAssets - Array of child assets in the video
* @param videoDuration - Length (in seconds) of the video
*/
private renderTimeline = (childAssets: IAsset[], videoDuration: number) => {
return (
<div className={"video-timeline-container"}>
{childAssets.map((childAsset) => this.renderChildAssetMarker(childAsset, videoDuration))}
</div>
);
}
/**
* Renders a timeline marker for the specified child asset
* @param childAsset The child asset to render
* @param videoDuration The total video duration
*/
private renderChildAssetMarker = (childAsset: IAsset, videoDuration: number) => {
const className = childAsset.state === AssetState.Tagged ? "video-timeline-tagged" : "video-timeline-visited";
const childPosition: number = (childAsset.timestamp / videoDuration);
const style = { left: `${childPosition * 100}%` };
return (
<div key={childAsset.timestamp}
onClick={() => this.seekToTime(childAsset.timestamp)}
className={className}
style={style} />
);
}
/**
* Gets the current video player state
*/
private getVideoPlayerState = (): Readonly<IVideoPlayerState> => {
return this.videoPlayer.current.getState().player;
}
} | the_stack |
import {
AfterViewInit,
Directive,
EventEmitter,
Inject,
InjectFlags,
Injector,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges
} from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormControl, NgControl, Validator } from '@angular/forms';
import { Subscription } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { InputBoolean } from '../../../decorators';
import { convertToBoolean, isTypeof } from '../../../utils/util';
import { requiredFailed } from '../validators';
import { PoLookupAdvancedFilter } from './interfaces/po-lookup-advanced-filter.interface';
import { PoLookupColumn } from './interfaces/po-lookup-column.interface';
import { PoLookupFilter } from './interfaces/po-lookup-filter.interface';
import { PoLookupLiterals } from './interfaces/po-lookup-literals.interface';
import { PoLookupFilterService } from './services/po-lookup-filter.service';
/**
* @description
*
* Componente utilizado para abrir uma janela de busca com uma tabela que lista dados de um serviço. Nesta janela é possível buscar e
* selecionar um ou mais registros que serão enviados para o campo. O `po-lookup` permite que o usuário digite um valor e pressione a tecla *TAB* para
* buscar um registro.
*
* > Caso o campo seja iniciado ou preenchido com um valor inexistente na busca, o mesmo será limpado.
* No segundo caso ocorrerá após este perder o foco; ambos os casos o campo ficará inválido quando requerido.
*
* > Enquanto o componente realiza a requisição ao servidor, o componente ficará desabilitado e com o status interno do
* [modelo](https://angular.io/guide/form-validation#creating-asynchronous-validators) como `pending`.
*
* Este componente não é recomendado quando a busca dos dados possuir poucas informações, para isso utilize outros componentes como o
* `po-select` ou o `po-combo`.
*/
@Directive()
export abstract class PoLookupBaseComponent
implements ControlValueAccessor, OnDestroy, OnInit, Validator, AfterViewInit, OnChanges {
/**
* @optional
*
* @description
*
* Aplica foco no elemento ao ser iniciado.
*
* > Caso mais de um elemento seja configurado com essa propriedade, apenas o último elemento declarado com ela terá o foco.
*
* @default `false`
*/
@Input('p-auto-focus') @InputBoolean() autoFocus: boolean = false;
/**
* Label do campo.
*
* > Quando utilizar esta propriedade o seu valor será utilizado como título da modal do componente caso não tenha
* sido definido um `modalTitle` na propriedade `p-literals`.
*/
@Input('p-label') label?: string;
/**
* @description
*
* Objeto com as literais usadas no `po-lookup`.
*
* Existem duas maneiras de customizar o componente, passando um objeto com todas as literais disponíveis:
*
* ```
* const customLiterals: PoLookupLiterals = {
* modalPrimaryActionLabel: 'Select',
* modalSecondaryActionLabel: 'Cancel',
* modalPlaceholder: 'Search Value',
* modalTableNoColumns: 'No columns',
* modalTableNoData: 'No data',
* modalTableLoadingData: 'Loading data',
* modalTableLoadMoreData: 'Load more',
* modalTitle: 'Select a user',
* modalAdvancedSearch: 'Advanced search',
* modalAdvancedSearchTitle: 'Advanced search',
* modalAdvancedSearchPrimaryActionLabel: 'Filter',
* modalAdvancedSearchSecondaryActionLabel: 'Return',
* modalDisclaimerGroupTitle: 'Presenting results filtered by:'
* };
* ```
*
* Ou passando apenas as literais que deseja customizar:
*
* ```
* const customLiterals: PoLookupLiterals = {
* modalPrimaryActionLabel: 'Select'
* };
* ```
*
* E para carregar as literais customizadas, basta apenas passar o objeto para o componente.
*
* ```
* <po-lookup
* [p-literals]="customLiterals">
* </po-lookup>
* ```
*
* > O objeto padrão de literais será traduzido de acordo com o idioma do
* [`PoI18nService`](/documentation/po-i18n) ou do browser.
*/
@Input('p-literals') literals?: PoLookupLiterals;
/** Texto de apoio do campo. */
@Input('p-help') help?: string;
/** Mensagem que aparecerá enquanto o campo não estiver preenchido. */
@Input('p-placeholder') set placeholder(value: string) {
this._placeholder = value || '';
}
get placeholder() {
return this._placeholder;
}
/** Nome e Id do componente. */
@Input('name') name: string;
/**
* @description
*
* Indica a coluna que será utilizada como valor do campo.
*
* > Atenção: Caso não seja passada ou tenha o conteúdo incorreto, não irá atualizar o model do formulário.
*/
@Input('p-field-value') fieldValue: string;
/** Indica a coluna que será utilizada como descrição do campo e como filtro dentro da janela. */
@Input('p-field-label') set fieldLabel(value: string) {
this._fieldLabel = value;
this.keysDescription = [this.fieldLabel];
}
get fieldLabel() {
return this._fieldLabel;
}
/** Valor que será repassado como parâmetro para a URL ou aos métodos do serviço que implementam a interface `PoLookupFilter`. */
@Input('p-filter-params') filterParams?: any;
/**
* @optional
*
* @description
*
* Formato de exibição do campo.
*
* Recebe uma função que deve retornar uma *string* com o/os valores do objeto formatados para exibição, por exemplo:
*
* ```
* fieldFormat(obj) {
* return `${obj.id} - ${obj.name}`;
* }
* ```
* > Esta propriedade sobrepõe o valor da propriedade `p-field-label` na descrição do campo.
*
* Pode-se informar uma lista de propriedades que deseja exibir como descrição do campo, Por exemplo:
* ```
* <po-lookup
* ...
* [p-field-format]="['id','nickname']"
* ...
* >
*
* Objeto retornado:
* {
* id:123,
* name: 'Kakaroto',
* nickname: 'Goku',
* }
* Apresentação no campo: 123 - Goku
* ```
*
* > Será utilizado ` - ` como separador.
*/
@Input('p-field-format') fieldFormat?: ((value) => string) | Array<string>;
/**
* Lista das colunas da tabela.
* Essa propriedade deve receber um array de objetos que implementam a interface PoLookupColumn.
*/
@Input('p-columns') columns?: Array<PoLookupColumn>;
/**
* @optional
*
* @description
*
* Define se a indicação de campo opcional será exibida.
*
* > Não será exibida a indicação se:
* - O campo conter `p-required`;
* - Não possuir `p-help` e/ou `p-label`.
*
* @default `false`
*/
@Input('p-optional') optional: boolean;
/**
*
* @optional
*
* @description
*
* Lista de objetos dos campos que serão criados na busca avançada.
*
* > Caso não seja passado um objeto ou então ele esteja em branco o link de busca avançada ficará escondido.
*
* Exemplo de URL com busca avançada:
*
* ```
* url + ?page=1&pageSize=20&name=Tony%20Stark&nickname=Homem%20de%20Ferro
* ```
*
* Caso algum parâmetro seja uma lista, a concatenação é feita utilizando vírgula.
* Exemplo:
*
* ```
* url + ?page=1&pageSize=20&name=Tony%20Stark,Peter%20Parker,Gohan
* ```
*
*/
@Input('p-advanced-filters') advancedFilters: Array<PoLookupAdvancedFilter>;
/**
* @optional
*
* @description
*
* Ativa a funcionalidade de scroll infinito para a tabela exibida no retorno da consulta.
*
* @default `false`
*/
@Input('p-infinite-scroll') @InputBoolean() infiniteScroll: boolean = false;
/** Exibe um ícone que permite limpar o campo. */
@Input('p-clean') @InputBoolean() clean: boolean = false;
/**
* @optional
*
* @description
*
* Permite a seleção de múltiplos itens.
*
* > Quando habilitado o valor do campo passará a ser uma lista de valores, por exemplo: `[ 12345, 67890 ]`
*
* @default `false`
*/
@Input('p-multiple') @InputBoolean() multiple: boolean = false;
/**
* @optional
*
* @description
*
* Define que a altura do componente será auto ajustável, possuindo uma altura minima porém a altura máxima será de acordo
* com o número de itens selecionados e a extensão dos mesmos, mantendo-os sempre visíveis.
*
* @default `false`
*/
@Input('p-auto-height') @InputBoolean() autoHeight: boolean = false;
/**
* Evento será disparado quando ocorrer algum erro na requisição de busca do item.
* Será passado por parâmetro o objeto de erro retornado.
*/
@Output('p-error') onError: EventEmitter<any> = new EventEmitter<any>();
/**
* @optional
*
* @description
*
* Evento será disparado quando ocorrer alguma seleção.
* Será passado por parâmetro o objeto com o valor selecionado.
*/
@Output('p-selected') selected: EventEmitter<any> = new EventEmitter<any>();
/**
* @optional
*
* @description
*
* Evento que será disparado ao alterar o model.
* Por parâmetro será passado o novo valor.
*/
@Output('p-change') change: EventEmitter<any> = new EventEmitter<any>();
service: any;
protected selectedOptions = [];
protected getSubscription: Subscription;
protected keysDescription: Array<any>;
protected oldValue: string = '';
protected valueToModel;
protected oldValueToModel = null;
// eslint-disable-next-line
protected onTouched: any = null;
protected resizeListener: () => void;
private _disabled?: boolean = false;
private _fieldLabel: string;
private _filterService: PoLookupFilter | string;
private _noAutocomplete: boolean;
private _placeholder: string = '';
private _required?: boolean = false;
private _autoHeight: boolean = false;
private autoHeightInitialValue: boolean;
private onChangePropagate: any = null;
private validatorChange: any;
private control!: AbstractControl;
/**
* Serviço responsável por buscar os dados da tabela na janela. Pode ser informado um serviço que implemente a interface
* `PoLookupFilter` ou uma URL.
*
* Quando utilizada uma URL de um serviço, será concatenada nesta URL o valor que deseja-se filtrar, por exemplo:
*
* ```
* url + ?page=1&pageSize=20&filter=Peter
* ```
*
* Caso utilizar ordenação, a coluna ordenada será enviada através do parâmetro `order`, por exemplo:
* - Coluna decrescente:
* ```
* url + ?page=1&pageSize=20&filter=Peter&order=-name
* ```
*
* - Coluna ascendente:
* ```
* url + ?page=1&pageSize=20&filter=Peter&order=name
* ```
*
* Se for definido a propriedade `p-filter-params`, o mesmo também será concatenado. Por exemplo, para o
* parâmetro `{ age: 23 }` a URL ficaria:
*
* ```
* url + ?page=1&pageSize=20&age=23&filter=Peter
* ```
*
* Ao iniciar o campo com valor, os registros serão buscados da seguinte forma:
* ```
* model = 1234;
*
* GET url/1234
* ```
*
* Caso estiver com múltipla seleção habilitada:
* ```
* model = [1234, 5678]
*
* GET url?${fieldValue}=1234,5678
* ```
*
* > Esta URL deve retornar e receber os dados no padrão de [API do PO UI](https://po-ui.io/guides/api) e utiliza os valores
* definidos nas propriedades `p-field-label` e `p-field-value` para a construção do `po-lookup`.
*
* Caso o usuário digite um valor e pressione a tecla *TAB* para realizar a busca de um registro específico, o valor que se
* deseja filtrar será codificado utilizando a função [encodeURIComponent](https://tc39.es/ecma262/#sec-encodeuricomponent-uricomponent)
* e concatenado na URL da seguinte forma:
*
* ```
* url/valor%20que%20se%20deseja%20filtrar
* ```
*
* > Quando informado um serviço que implemente a interface `PoLookupFilter` o tratamento de encoding do valor a ser filtrado ficará a cargo do desenvolvedor.
*
*/
@Input('p-filter-service') set filterService(filterService: PoLookupFilter | string) {
this._filterService = filterService;
this.setService(this.filterService);
}
get filterService() {
return this._filterService;
}
/**
* @optional
*
* @description
*
* Define a propriedade nativa `autocomplete` do campo como `off`.
*
* @default `false`
*/
@Input('p-no-autocomplete') set noAutocomplete(value: boolean) {
this._noAutocomplete = convertToBoolean(value);
}
get noAutocomplete() {
return this._noAutocomplete;
}
/**
* @optional
* @description
*
* Indica que o campo será obrigatório. Esta propriedade é desconsiderada quando o campo está desabilitado (p-disabled).
*
* @default `false`
*/
@Input('p-required') set required(required: boolean) {
this._required = convertToBoolean(required);
this.validateModel(this.valueToModel);
}
get required(): boolean {
return this._required;
}
/**
* @description
*
* Indica que o campo será desabilitado.
*
* @default false
* @optional
*/
@Input('p-disabled') set disabled(disabled: boolean) {
this._disabled = <any>disabled === '' ? true : convertToBoolean(disabled);
}
get disabled(): boolean {
return this._disabled;
}
constructor(private defaultService: PoLookupFilterService, @Inject(Injector) private injector: Injector) {}
ngOnDestroy() {
if (this.getSubscription) {
this.getSubscription.unsubscribe();
}
}
ngOnInit(): void {
this.initializeColumn();
}
ngAfterViewInit(): void {
this.setControl();
}
cleanModel() {
this.cleanViewValue();
this.callOnChange(undefined);
}
ngOnChanges(changes: SimpleChanges) {
if (changes.multiple && isTypeof(this.filterService, 'string')) {
this.service.setConfig(this.filterService, this.fieldValue, this.multiple);
}
}
// Função implementada do ControlValueAccessor
// Usada para interceptar os estados de habilitado via forms api
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
registerOnValidatorChange(fn: () => void) {
this.validatorChange = fn;
}
// Função implementada do ControlValueAccessor.
// Usada para interceptar as mudanças e não atualizar automaticamente o Model.
registerOnChange(func: any): void {
this.onChangePropagate = func;
}
// Função implementada do ControlValueAccessor.
// Usada para interceptar as mudanças e não atualizar automaticamente o Model.
registerOnTouched(func: any): void {
this.onTouched = func;
}
// Seleciona o valor do model.
selectValue(valueSelected: any) {
this.valueToModel = valueSelected;
this.callOnChange(this.valueToModel);
this.selected.emit(valueSelected);
}
callOnChange(value: any) {
// Quando o input não possui um formulário, então esta função não é registrada.
if (this.onChangePropagate) {
this.onChangePropagate(value);
}
if (this.oldValueToModel !== this.valueToModel) {
this.change.emit(this.valueToModel);
}
// Armazenar o valor antigo do model
this.oldValueToModel = this.valueToModel;
}
searchById(value) {
let checkedValue = value;
if (typeof checkedValue === 'string') {
checkedValue = checkedValue.trim();
}
if (checkedValue !== '') {
const oldDisable = this.disabled;
this.disabled = true;
if (this.control) {
// :TODO: Retirar no futuro pois esse setTimeout foi feito
// pois quando o campo é acionado pelos métodos setValue ou patchValue
// a mudança não é detectada
setTimeout(() => this.control.markAsPending());
}
this.getSubscription = this.service
.getObjectByValue(value, this.filterParams)
.pipe(
finalize(() => {
this.disabled = oldDisable;
if (this.control) {
this.control.updateValueAndValidity();
}
})
)
.subscribe(
element => {
if (element?.length || (!Array.isArray(element) && element)) {
if (Array.isArray(element) && element.length > 1) {
this.setDisclaimers(element);
this.updateVisibleItems();
}
this.selectModel(this.multiple ? element : [element]);
} else {
this.cleanModel();
}
},
error => {
this.cleanModel();
this.onError.emit(error);
}
);
} else {
this.cleanModel();
}
}
validate(abstractControl: AbstractControl): { [key: string]: any } {
if (requiredFailed(this.required, this.disabled, abstractControl.value)) {
return {
required: {
valid: false
}
};
}
}
writeValue(value: any): void {
if (value?.length || (!Array.isArray(value) && value)) {
// Esta condição é executada somente quando é passado o ID para realizar a busca pelo ID.
this.searchById(value);
} else {
this.cleanViewValue();
}
}
protected cleanViewValue() {
this.setViewValue('', {});
this.oldValue = '';
this.valueToModel = null;
}
// Formata a label do campo.
protected getFormattedLabel(value: any): string {
return value ? this.keysDescription.map(column => value[column]).join(' - ') : '';
}
// Chama o método writeValue e preenche o model.
protected selectModel(options: Array<any>) {
if (options.length) {
this.selectedOptions = [...options];
const newModel = this.multiple ? options.map(option => option[this.fieldValue]) : options[0][this.fieldValue];
this.selectValue(newModel);
if (options.length === 1) {
this.oldValue = options[0][this.fieldLabel];
this.setViewValue(this.getFormattedLabel(options[0]), options[0]);
}
} else {
this.selectValue(undefined);
this.cleanViewValue();
}
}
protected validateModel(model: any) {
if (this.validatorChange) {
this.validatorChange(model);
}
}
private setService(service: PoLookupFilter | string) {
if (isTypeof(service, 'object')) {
this.service = <PoLookupFilterService>service;
}
if (service && isTypeof(service, 'string')) {
this.service = this.defaultService;
this.service.setConfig(service, this.fieldValue, this.multiple);
}
}
private setControl() {
const ngControl: NgControl = this.injector.get(NgControl, null, InjectFlags.Self);
if (ngControl) {
this.control = ngControl.control as FormControl;
}
}
private initializeColumn(): void {
if (this.fieldLabel) {
this.keysDescription = [this.fieldLabel];
} else {
this.keysDescription = [];
this.keysDescription = this.columns.filter(element => element.fieldLabel).map(element => element.property);
}
}
// Atribui um ou mais valores ao campo.
abstract setViewValue(value: any, object: any): void;
// Método com a implementação para abrir o lookup.
abstract openLookup(): void;
abstract setDisclaimers(a);
abstract updateVisibleItems();
} | the_stack |
import { PureComponent } from 'react'
import { connect } from 'redaction'
import { BigNumber } from 'bignumber.js'
import { FormattedMessage } from 'react-intl'
import CSSModules from 'react-css-modules'
import getCoinInfo from 'common/coins/getCoinInfo'
import utils from 'common/utils'
import erc20Like from 'common/erc20Like'
import { EVM_COIN_ADDRESS, ZERO_ADDRESS } from 'common/helpers/constants/ADDRESSES'
import {
apiLooper,
externalConfig,
constants,
localStorage,
metamask,
links,
user,
cacheStorageGet,
cacheStorageSet,
} from 'helpers'
import { localisedUrl } from 'helpers/locale'
import actions from 'redux/actions'
import Link from 'local_modules/sw-valuelink'
import Button from 'components/controls/Button/Button'
import {
ComponentState,
Direction,
BlockReasons,
Sections,
Actions,
CurrencyMenuItem,
} from './types'
import {
API_NAME,
GWEI_DECIMALS,
COIN_DECIMALS,
API_GAS_LIMITS,
MAX_PERCENT,
LIQUIDITY_SOURCE_DATA,
} from './constants'
import styles from './index.scss'
import TokenInstruction from './TokenInstruction'
import Header from './Header'
import InputForm from './InputForm'
import SourceActions from './SourceActions'
import UserInfo from './UserInfo'
import Settings from './Settings'
import Feedback from './Feedback'
import Footer from './Footer'
const QuickswapModes = {
aggregator: 'aggregator',
source: 'source',
only_aggregator: 'only_aggregator',
only_source: 'only_source',
}
const CURRENCY_PLUG = {
blockchain: '-',
fullTitle: '-',
name: '-',
notExist: true,
}
class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
constructor(props) {
super(props)
const { match, activeFiat, allCurrencies, history } = props
const { params, path } = match
const mode = QuickswapModes[window.quickswapMode]
let onlyAggregator = false
let onlySource = false
let activeSection
switch (mode) {
case QuickswapModes.only_aggregator:
activeSection = Sections.Aggregator
onlyAggregator = true
break
case QuickswapModes.only_source:
activeSection = Sections.Source
onlySource = true
break
case QuickswapModes.aggregator:
activeSection = Sections.Aggregator
break
case QuickswapModes.source:
activeSection = Sections.Source
break
default:
activeSection = Sections.Aggregator
}
// for testnets API isn't available
if (externalConfig.entry === 'testnet') {
activeSection = Sections.Source
onlySource = true
}
const isSourceMode = activeSection === Sections.Source
let {
currentCurrencies,
receivedList,
spendedCurrency,
receivedCurrency,
wrongNetwork,
} = this.returnCurrentAssetState(allCurrencies, activeSection)
if (externalConfig.opts.defaultQuickSell) {
const defaultSellCurrency = allCurrencies.filter((curData) => curData.value.toUpperCase() === externalConfig.opts.defaultQuickSell.toUpperCase())
if (defaultSellCurrency.length) {
[spendedCurrency] = defaultSellCurrency
receivedList = this.returnReceivedList(allCurrencies, spendedCurrency)
}
}
if (externalConfig.opts.defaultQuickBuy) {
const defaultBuyCurrency = allCurrencies.filter((curData) => curData.value.toUpperCase() === externalConfig.opts.defaultQuickBuy.toUpperCase())
if (defaultBuyCurrency.length) [receivedCurrency] = defaultBuyCurrency
}
// if we have url parameters then show it as default values
if (!wrongNetwork && path.match(/\/quick/) && params.sell && params.buy) {
const urlSpendedCurrency = currentCurrencies.find(
(item) => item.value.toLowerCase() === params.sell.toLowerCase(),
)
if (!urlSpendedCurrency) history.push(localisedUrl('', `${links.quickSwap}`))
const urlReceivedList = this.returnReceivedList(currentCurrencies, urlSpendedCurrency)
const urlReceivedCurrency = urlReceivedList.find(
(item) => item.value.toLowerCase() === params.buy.toLowerCase(),
)
if (!urlReceivedCurrency) history.push(localisedUrl('', `${links.quickSwap}`))
// reassigning these variables only if url is correct
if (urlSpendedCurrency && urlReceivedList && urlReceivedCurrency) {
spendedCurrency = urlSpendedCurrency
receivedList = urlReceivedList
receivedCurrency = urlReceivedCurrency
}
}
const baseChainWallet = actions.core.getWallet({
currency: spendedCurrency.blockchain || spendedCurrency.value,
})
const fromWallet = actions.core.getWallet({
currency: spendedCurrency.value,
})
const toWallet = actions.core.getWallet({
currency: receivedCurrency.value,
})
this.state = {
error: null,
liquidityErrorMessage: '',
isPending: false,
isSourceMode,
onlyAggregator,
onlySource,
activeSection,
needApproveA: false,
needApproveB: false,
externalExchangeReference: null,
externalWindowTimer: null,
currentLiquidityPair: null,
fiat: window.DEFAULT_FIAT || activeFiat,
currencies: currentCurrencies,
receivedList,
baseChainWallet,
spendedCurrency,
spendedAmount: '',
fromWallet: fromWallet || {},
receivedCurrency,
receivedAmount: '',
toWallet: toWallet || {},
sourceAction: Actions.Swap,
slippage: 0.5,
userDeadline: 20,
slippageMaxRange: 100,
wrongNetwork,
network:
externalConfig.evmNetworks[
spendedCurrency.blockchain || spendedCurrency.value.toUpperCase()
],
swapData: undefined,
swapFee: '',
gasPrice: '',
gasLimit: '',
blockReason: undefined,
serviceFee: false,
}
}
componentDidMount() {
this.updateNetwork()
this.updateServiceFeeData()
}
componentDidUpdate(prevProps, prevState) {
const { metamaskData, availableBlockchains } = this.props
const { metamaskData: prevMetamaskData } = prevProps
const { wrongNetwork: prevWrongNetwork, activeSection: prevActiveSection } = prevState
const { blockReason, currencies, spendedCurrency, activeSection } = this.state
const chainId = metamask.getChainId()
const isCurrentNetworkAvailable = !!availableBlockchains[chainId]
const isSpendedCurrencyNetworkAvailable = metamask.isAvailableNetworkByCurrency(spendedCurrency.value)
const switchToCorrectNetwork = prevWrongNetwork
&& (isSpendedCurrencyNetworkAvailable || isCurrentNetworkAvailable)
const switchToWrongNetwork = !prevWrongNetwork && !isSpendedCurrencyNetworkAvailable
const disconnect = prevMetamaskData.isConnected && !metamaskData.isConnected
let needFullUpdate = (
disconnect
|| (
metamaskData.isConnected
&& (
switchToCorrectNetwork
|| switchToWrongNetwork
|| prevMetamaskData.address !== metamaskData.address
)
)
)
const changeSection = activeSection !== prevActiveSection
if (changeSection) {
const {
currentCurrencies,
spendedCurrency: newSpendedCurrency,
wrongNetwork,
} = this.returnCurrentAssetState(currencies, activeSection)
const haveSpendedCurrencyInList = currentCurrencies.filter(currency => currency.value === spendedCurrency.value).length === 1
const needCurrenciesListsUpdate = (
newSpendedCurrency.value === spendedCurrency.value
|| haveSpendedCurrencyInList && !blockReason
)
if (needCurrenciesListsUpdate) {
this.setState(() => ({
wrongNetwork,
currencies: currentCurrencies,
}), this.updateReceivedList)
} else if (!haveSpendedCurrencyInList) {
needFullUpdate = true
}
}
if (needFullUpdate) {
const {
currentCurrencies,
receivedList,
spendedCurrency,
receivedCurrency,
wrongNetwork,
} = this.returnCurrentAssetState(currencies, activeSection)
this.updateBaseChainWallet(spendedCurrency)
const fromWallet = actions.core.getWallet({
currency: spendedCurrency.value,
})
const toWallet = actions.core.getWallet({
currency: receivedCurrency.value,
})
this.setState(() => ({
wrongNetwork,
currencies: currentCurrencies,
spendedCurrency,
receivedList,
receivedCurrency,
network:
externalConfig.evmNetworks[
spendedCurrency.blockchain || spendedCurrency.value.toUpperCase()
],
fromWallet,
toWallet,
}))
}
}
componentWillUnmount() {
this.clearWindowTimer()
this.saveOptionsInStorage()
}
returnCurrentAssetState = (currentCurrencies, activeSection: Sections) => {
const { allCurrencies } = this.props
let { currencies: filteredCurrencies, wrongNetwork } = actions.oneinch.filterCurrencies({
currencies: allCurrencies,
})
let currencies: any[] = []
if (wrongNetwork) {
filteredCurrencies = currentCurrencies
}
if (activeSection === Sections.Aggregator) {
currencies = filteredCurrencies.filter(currency => {
const { coin, blockchain } = getCoinInfo(currency.value)
const network = externalConfig.evmNetworks[blockchain || coin]
return !!API_NAME[network?.networkVersion]
})
}
if (!currencies.length) {
currencies = filteredCurrencies.length ? filteredCurrencies : [ CURRENCY_PLUG ]
}
const spendedCurrency = currencies[0]
let receivedList = this.returnReceivedList(currencies, spendedCurrency)
// user doesn't have enough tokens in the wallet. Show a notice about it
if (!receivedList.length) {
receivedList = [CURRENCY_PLUG]
}
const receivedCurrency = receivedList[0]
return {
wrongNetwork,
currentCurrencies: currencies,
receivedList,
spendedCurrency,
receivedCurrency,
}
}
updateServiceFeeData = () => {
const { fromWallet } = this.state
const feeOptsKey = fromWallet?.standard || fromWallet?.currency
const currentFeeOpts = externalConfig.opts.fee[feeOptsKey?.toLowerCase()]
const correctFeeRepresentation = !Number.isNaN(window?.zeroxFeePercent)
&& window.zeroxFeePercent >= 0
&& window.zeroxFeePercent <= 100
if (currentFeeOpts?.address && correctFeeRepresentation) {
// percent of the buyAmount >= 0 && <= 1
const apiPercentFormat = new BigNumber(window.zeroxFeePercent).dividedBy(MAX_PERCENT)
this.setState(() => ({
serviceFee: {
address: currentFeeOpts.address,
percent: Number(apiPercentFormat),
},
}))
} else {
this.setState(() => ({
serviceFee: false,
}))
}
}
updateBaseChainWallet = (currencyItem: CurrencyMenuItem) => {
const { coin, blockchain } = getCoinInfo(currencyItem.value)
const baseChainWallet = actions.core.getWallet({
currency: blockchain || coin,
})
this.setState(() => ({
baseChainWallet,
}))
}
updateNetwork = async () => {
const { spendedCurrency } = this.state
const network = externalConfig.evmNetworks[spendedCurrency.blockchain || spendedCurrency.value.toUpperCase()]
this.updateBaseChainWallet(spendedCurrency)
this.setState(
() => ({
network,
}),
async () => {
await this.updateCurrentPairAddress()
},
)
}
updateWallets = () => {
const { spendedCurrency, receivedCurrency } = this.state
this.updateBaseChainWallet(spendedCurrency)
const fromWallet = actions.core.getWallet({
currency: spendedCurrency.value,
})
const toWallet = actions.core.getWallet({
currency: receivedCurrency.value,
})
this.setState(() => ({
fromWallet,
toWallet,
}))
}
saveOptionsInStorage = () => {
const { fromWallet, toWallet } = this.state
const exchangeSettings = localStorage.getItem(constants.localStorage.exchangeSettings)
if (exchangeSettings) {
const sell = fromWallet.tokenKey || fromWallet.currency || ''
const buy = toWallet.tokenKey || toWallet.currency || ''
exchangeSettings.quickCurrency = {
sell,
buy,
}
localStorage.setItem(constants.localStorage.exchangeSettings, exchangeSettings)
}
}
returnReceivedList = (currencies, spendedCurrency) => {
const result = currencies.filter((item) => {
const currentSpendedAsset = item.value === spendedCurrency?.value
const spendedAssetChain = item.blockchain || item.value.toUpperCase()
const receivedAssetChain = spendedCurrency?.blockchain || spendedCurrency?.value?.toUpperCase()
return spendedAssetChain === receivedAssetChain && !currentSpendedAsset
})
return result
}
updateReceivedList = () => {
const { currencies, spendedCurrency } = this.state
let receivedList = this.returnReceivedList(currencies, spendedCurrency)
if (!receivedList.length) {
receivedList = [
{
blockchain: '-',
fullTitle: '-',
name: '-',
notExist: true,
},
]
}
this.setState(
() => ({
receivedList,
receivedCurrency: receivedList[0],
toWallet: actions.core.getWallet({ currency: receivedList[0].value }),
}),
async () => {
this.resetSwapData()
},
)
}
reportError = (error: IError) => {
const { liquidityErrorMessage } = this.state
const possibleNoLiquidity = JSON.stringify(error)?.match(/INSUFFICIENT_ASSET_LIQUIDITY/)
const insufficientSlippage = JSON.stringify(error)?.match(/IncompleteTransformERC20Error/)
const notEnoughBalance = error.message?.match(/(N|n)ot enough .* balance/)
if (possibleNoLiquidity) {
this.setBlockReason(BlockReasons.NoLiquidity)
} else if (insufficientSlippage) {
this.setBlockReason(BlockReasons.InsufficientSlippage)
} else if (notEnoughBalance) {
this.setBlockReason(BlockReasons.NoBalance)
} else if (liquidityErrorMessage) {
this.setBlockReason(BlockReasons.Liquidity)
} else {
this.setBlockReason(BlockReasons.Unknown)
console.group('%c Swap', 'color: red;')
console.error(error)
console.groupEnd()
}
this.setState(() => ({
isPending: false,
error,
}))
}
createSwapRequest = (skipValidation = false) => {
const { slippage, spendedAmount, fromWallet, toWallet, serviceFee } = this.state
const sellToken = fromWallet?.contractAddress || EVM_COIN_ADDRESS
const buyToken = toWallet?.contractAddress || EVM_COIN_ADDRESS
const sellAmount = utils.amount.formatWithDecimals(
spendedAmount,
fromWallet.decimals || COIN_DECIMALS,
)
const enoughBalanceForSwap = new BigNumber(fromWallet.balance).isGreaterThan(new BigNumber(spendedAmount))
const request = [
`/swap/v1/quote?`,
`buyToken=${buyToken}&`,
`sellToken=${sellToken}&`,
`sellAmount=${sellAmount}`,
]
if (enoughBalanceForSwap) {
request.push(`&takerAddress=${fromWallet.address}`)
}
if (window?.STATISTICS_ENABLED) {
request.push(`&affiliateAddress=${externalConfig.swapContract.affiliateAddress}`)
}
if (serviceFee) {
const { address, percent } = serviceFee
request.push(`&feeRecipient=${address}`)
request.push(`&buyTokenPercentageFee=${percent}`)
}
if (skipValidation) {
request.push(`&skipValidation=true`)
}
if (slippage) {
// allow users to enter an amount up to 100, because it's more easy then enter the amount from 0 to 1
// and now convert it into the api format
const correctValue = new BigNumber(slippage).dividedBy(MAX_PERCENT)
request.push(`&slippagePercentage=${correctValue}`)
}
return request.join('')
}
onInputDataChange = async () => {
const { activeSection, sourceAction, currentLiquidityPair } = this.state
await this.updateCurrentPairAddress()
await this.checkApprove(Direction.Spend)
if (activeSection === Sections.Source && sourceAction === Actions.AddLiquidity) {
await this.checkApprove(Direction.Receive)
}
if (
activeSection === Sections.Source
&& sourceAction !== Actions.AddLiquidity
&& currentLiquidityPair
) {
this.resetSwapData()
}
this.setState(() => ({
error: null,
}))
if (activeSection === Sections.Aggregator) {
await this.fetchSwapAPIData()
} else if (activeSection === Sections.Source) {
await this.processingSourceActions()
}
}
tryToSkipValidation = (error): boolean => {
const { code, reason, values } = JSON.parse(error.message)
const INVALID_TX_CODE = 105
const transactionError = code === INVALID_TX_CODE && reason === 'Error'
const insufficientSlippage = reason === 'IncompleteTransformERC20Error'
if (transactionError && !insufficientSlippage) {
const liquidityError = values.message.match(/^[0-9a-zA-Z]+: K$/m)
if (liquidityError) {
this.setState(() => ({
liquidityErrorMessage: liquidityError[0],
}))
}
return true
}
return false
}
calculateDataFromSwap = async (params) => {
const { baseChainWallet, toWallet, gasLimit, gasPrice } = this.state
const { swap, withoutValidation } = params
// we've had a special error in the previous request. It means there is
// some problem and we add a "skip validation" parameter to bypass it.
// Usually the swap tx with this parameter fails in the blockchain,
// because it's not enough gas limit. Estimate it by yourself
if (withoutValidation) {
const estimatedGas = await actions[baseChainWallet.currency.toLowerCase()]?.estimateGas(swap)
if (typeof estimatedGas === 'number') {
swap.gas = estimatedGas
} else if (estimatedGas instanceof Error) {
this.reportError(estimatedGas)
}
}
const customGasLimit = gasLimit && gasLimit > swap.gas ? gasLimit : swap.gas
const customGasPrice = gasPrice
? utils.amount.formatWithDecimals(gasPrice, GWEI_DECIMALS)
: swap.gasPrice
const weiFee = new BigNumber(customGasLimit).times(customGasPrice)
const swapFee = utils.amount.formatWithoutDecimals(weiFee, COIN_DECIMALS)
const receivedAmount = utils.amount.formatWithoutDecimals(
swap.buyAmount,
toWallet?.decimals || COIN_DECIMALS,
)
this.setState(() => ({
receivedAmount,
swapData: swap,
swapFee,
isPending: false,
}))
}
fetchSwapAPIData = async () => {
const { network, spendedAmount, isPending } = this.state
const dontFetch = (
new BigNumber(spendedAmount).isNaN()
|| new BigNumber(spendedAmount).isEqualTo(0)
|| isPending
)
if (dontFetch) return
this.setState(() => ({
isPending: true,
blockReason: undefined,
}))
let repeatRequest = true
let swapRequest = this.createSwapRequest()
while (repeatRequest) {
const swap: any = await apiLooper.get(API_NAME[network.networkVersion], swapRequest, {
reportErrors: (error) => {
if (!repeatRequest) {
this.reportError(error)
}
},
sourceError: true,
})
if (!(swap instanceof Error)) {
repeatRequest = false
await this.calculateDataFromSwap({
swap,
withoutValidation: swapRequest.match(/skipValidation/),
})
} else if (this.tryToSkipValidation(swap)) {
// it's a special error. Will be a new request
swapRequest = this.createSwapRequest(true)
} else {
this.reportError(swap)
repeatRequest = false
}
}
}
updateCurrentPairAddress = async () => {
const { network, baseChainWallet, fromWallet, toWallet } = this.state
const tokenA = fromWallet?.contractAddress || EVM_COIN_ADDRESS
const tokenB = toWallet?.contractAddress || EVM_COIN_ADDRESS
let pairAddress = cacheStorageGet(
'quickswapLiquidityPair',
`${externalConfig.entry}_${tokenA}_${tokenB}`,
)
if (!pairAddress) {
pairAddress = await actions.uniswap.getPairAddress({
baseCurrency: baseChainWallet.currency,
chainId: network.networkVersion,
factoryAddress: LIQUIDITY_SOURCE_DATA[network.networkVersion]?.factory,
tokenA,
tokenB,
})
const SECONDS = 15
cacheStorageSet(
'quickswapLiquidityPair',
`${externalConfig.entry}_${tokenA}_${tokenB}`,
pairAddress,
SECONDS,
)
}
const noLiquidityPair = pairAddress === ZERO_ADDRESS
this.setState(() => ({
currentLiquidityPair: noLiquidityPair ? null : pairAddress,
blockReason: noLiquidityPair ? BlockReasons.PairDoesNotExist : undefined,
}))
}
processingSourceActions = async () => {
const { sourceAction, currentLiquidityPair } = this.state
if (!currentLiquidityPair) return
switch (sourceAction) {
case Actions.Swap:
await this.fetchAmountOut()
break
case Actions.AddLiquidity:
await this.fetchLiquidityData()
}
}
fetchAmountOut = async () => {
const { network, baseChainWallet, spendedAmount, fromWallet, toWallet } = this.state
const tokenA = fromWallet.contractAddress ?? EVM_COIN_ADDRESS
const tokenB = toWallet.contractAddress ?? EVM_COIN_ADDRESS
this.setPending(true)
try {
const amountOut = await actions.uniswap.getAmountOut({
routerAddress: LIQUIDITY_SOURCE_DATA[network.networkVersion]?.router,
baseCurrency: baseChainWallet.currency,
chainId: network.networkVersion,
tokenA,
tokenADecimals: fromWallet.decimals ?? COIN_DECIMALS,
amountIn: spendedAmount,
tokenB,
tokenBDecimals: toWallet.decimals ?? COIN_DECIMALS,
})
this.setState(() => ({
receivedAmount: amountOut,
}))
} catch (error) {
this.reportError(error)
} finally {
this.setPending(false)
}
}
fetchLiquidityData = async () => {
const { network, spendedAmount, baseChainWallet, currentLiquidityPair, fromWallet, toWallet } = this.state
this.setPending(true)
try {
const result = await actions.uniswap.getLiquidityAmountForAssetB({
chainId: network.networkVersion,
pairAddress: currentLiquidityPair,
routerAddress: LIQUIDITY_SOURCE_DATA[network.networkVersion]?.router,
baseCurrency: baseChainWallet.currency,
tokenA: fromWallet.contractAddress ?? EVM_COIN_ADDRESS,
amountADesired: spendedAmount,
tokenADecimals: fromWallet.decimals ?? COIN_DECIMALS,
tokenBDecimals: toWallet.decimals ?? COIN_DECIMALS,
})
this.setState(() => ({
receivedAmount: result,
}))
} catch (error) {
this.reportError(error)
} finally {
this.setPending(false)
}
}
setSpendedAmount = (value) => {
this.setState(() => ({
spendedAmount: value,
}))
}
setReceivedAmount = (value) => {
this.setState(() => ({
receivedAmount: value,
}))
}
resetReceivedAmount = () => {
this.setState(() => ({
receivedAmount: '',
}))
}
resetSwapData = () => {
this.setState(() => ({ swapData: undefined }))
this.resetReceivedAmount()
}
checkApprove = async (direction) => {
const { network, isSourceMode, spendedAmount, receivedAmount, fromWallet, toWallet } = this.state
let amount = spendedAmount
let wallet = fromWallet
const spender = isSourceMode
? LIQUIDITY_SOURCE_DATA[network.networkVersion]?.router
: externalConfig.swapContract.zerox
if (direction === Direction.Receive) {
amount = receivedAmount
wallet = toWallet
}
if (!wallet.isToken) {
this.setNeedApprove(direction, false)
} else {
const { standard, address, contractAddress, decimals } = wallet
const allowance = await erc20Like[standard].checkAllowance({
contract: contractAddress,
owner: address,
decimals,
spender,
})
if (amount) {
this.setNeedApprove(direction, new BigNumber(amount).isGreaterThan(allowance))
}
}
}
setNeedApprove = (direction, value) => {
if (direction === Direction.Spend) {
this.setState(() => ({ needApproveA: value }))
} else {
this.setState(() => ({ needApproveB: value }))
}
}
selectCurrency = (params) => {
const { direction, value } = params
const { spendedCurrency, receivedCurrency } = this.state
const changeSpendedSide = direction === Direction.Spend && spendedCurrency.value !== value.value
const changeReceivedSide = direction === Direction.Receive && receivedCurrency.value !== value.value
if (changeSpendedSide) {
this.setState(
() => ({
spendedCurrency: value,
}),
this.updateSpendedSide,
)
}
if (changeReceivedSide) {
this.setState(
() => ({
receivedCurrency: value,
}),
this.updateReceivedSide,
)
}
}
updateSpendedSide = async () => {
const { spendedCurrency } = this.state
const fromWallet = actions.core.getWallet({ currency: spendedCurrency.value })
this.setState(
() => ({
fromWallet,
}),
async () => {
this.updateNetwork()
this.updateReceivedList()
this.updateServiceFeeData()
await this.onInputDataChange()
},
)
}
updateReceivedSide = () => {
const { receivedCurrency } = this.state
this.setState(
() => ({
toWallet: actions.core.getWallet({ currency: receivedCurrency.value }),
}),
async () => {
await this.onInputDataChange()
},
)
}
flipCurrency = () => {
const { currencies, fromWallet, spendedCurrency, receivedCurrency, toWallet, wrongNetwork } = this.state
if (wrongNetwork || receivedCurrency.notExist) return
const receivedList = this.returnReceivedList(currencies, receivedCurrency)
this.setState(
() => ({
fromWallet: toWallet,
spendedCurrency: receivedCurrency,
receivedList,
toWallet: fromWallet,
receivedCurrency: spendedCurrency,
}),
async () => {
await this.onInputDataChange()
},
)
}
openExternalExchange = () => {
const { externalExchangeReference, fromWallet } = this.state
const link = user.getExternalExchangeLink({
address: fromWallet.address,
currency: fromWallet.currency,
})
if (link && (externalExchangeReference === null || externalExchangeReference.closed)) {
this.setPending(true)
const newWindowProxy = window.open(link)
this.setState(
() => ({
externalExchangeReference: newWindowProxy,
}),
this.startCheckingExternalWindow,
)
} else {
// in this case window reference must exist and the window is not closed
externalExchangeReference?.focus()
}
}
startCheckingExternalWindow = () => {
const { externalExchangeReference } = this.state
const timer = setInterval(() => {
if (externalExchangeReference?.closed) {
this.closeExternalExchange()
}
}, 1000)
this.setState(() => ({
externalWindowTimer: timer,
}))
}
closeExternalExchange = () => {
const { externalExchangeReference, externalWindowTimer } = this.state
if (externalExchangeReference) {
externalExchangeReference.close()
this.setState(() => ({
externalExchangeReference: null,
}))
}
if (externalWindowTimer) {
clearInterval(externalWindowTimer)
this.setState(() => ({
externalWindowTimer: null,
}))
}
this.setPending(false)
}
clearWindowTimer = () => {
const { externalWindowTimer } = this.state
if (externalWindowTimer) {
clearInterval(externalWindowTimer)
}
}
openAggregatorSection = () => {
this.setState(() => ({
activeSection: Sections.Aggregator,
isSourceMode: false,
receivedAmount: '',
}))
}
openSourceSection = () => {
this.setState(() => ({
activeSection: Sections.Source,
isSourceMode: true,
receivedAmount: '',
swapData: undefined,
}))
}
openSettingsSection = () => {
this.setState(() => ({
activeSection: Sections.Settings,
}))
}
setAction = (type) => {
this.resetSwapData()
this.setState(() => ({
spendedAmount: '',
sourceAction: type,
}))
}
mnemonicIsSaved = () => localStorage.getItem(constants.privateKeyNames.twentywords) === '-'
setPending = (value: boolean) => {
this.setState(() => ({
isPending: value,
}))
}
setBlockReason = (value: BlockReasons) => {
this.setState(() => ({
blockReason: value,
}))
}
resetSpendedAmount = () => {
this.setState(() => ({
spendedAmount: '',
}))
}
isApiRequestBlocking = () => {
const {
isPending,
spendedAmount,
fromWallet,
baseChainWallet,
slippage,
slippageMaxRange,
gasPrice,
gasLimit,
} = this.state
const wrongSlippage = slippage
&& (new BigNumber(slippage).isEqualTo(0)
|| new BigNumber(slippage).isGreaterThan(slippageMaxRange))
const wrongGasPrice = new BigNumber(gasPrice).isPositive()
&& new BigNumber(gasPrice).isGreaterThan(API_GAS_LIMITS.MAX_PRICE)
const wrongGasLimit = new BigNumber(gasLimit).isPositive()
&& (new BigNumber(gasLimit).isLessThan(API_GAS_LIMITS.MIN_LIMIT)
|| new BigNumber(gasLimit).isGreaterThan(API_GAS_LIMITS.MAX_LIMIT))
const wrongSettings = wrongGasPrice || wrongGasLimit || wrongSlippage
const noBalance = baseChainWallet.balanceError || new BigNumber(baseChainWallet.balance).isEqualTo(0)
return (
noBalance
|| isPending
|| wrongSettings
|| new BigNumber(spendedAmount).isNaN()
|| new BigNumber(spendedAmount).isEqualTo(0)
|| new BigNumber(spendedAmount).isGreaterThan(fromWallet.balance)
)
}
createLimitOrder = () => {
actions.modals.open(constants.modals.LimitOrder)
}
render() {
const { history } = this.props
const {
baseChainWallet,
activeSection,
isSourceMode,
onlyAggregator,
onlySource,
needApproveA,
needApproveB,
fiat,
spendedAmount,
spendedCurrency,
receivedAmount,
fromWallet,
toWallet,
receivedCurrency,
sourceAction,
wrongNetwork,
network,
swapData,
swapFee,
blockReason,
slippage,
serviceFee,
} = this.state
const linked = Link.all(
this,
'slippage',
'gasPrice',
'gasLimit',
'userDeadline',
'spendedAmount',
'receivedAmount',
)
const insufficientBalanceA = new BigNumber(fromWallet.balance).isEqualTo(0)
|| new BigNumber(spendedAmount)
.plus(fromWallet?.standard ? 0 : swapFee || 0)
.isGreaterThan(fromWallet.balance)
const insufficientBalanceB = new BigNumber(toWallet.balance).isEqualTo(0)
|| new BigNumber(receivedAmount).isGreaterThan(toWallet.balance)
return (
<>
{onlyAggregator && <TokenInstruction />}
{spendedCurrency.notExist || receivedCurrency.notExist && (
<p styleName="noAssetsNotice">
<FormattedMessage
id="notEnoughAssetsNotice"
defaultMessage="You don't have available assets for {networkName} to exchange. Please change the network or add a custom asset to the wallet."
values={{
networkName: network.chainName || 'Unknown network',
}}
/>
</p>
)}
<section styleName="quickSwap">
<Header
network={network}
onlyAggregator={onlyAggregator}
onlySource={onlySource}
activeSection={activeSection}
wrongNetwork={wrongNetwork}
receivedCurrency={receivedCurrency}
openAggregatorSection={this.openAggregatorSection}
openSourceSection={this.openSourceSection}
openSettingsSection={this.openSettingsSection}
/>
{activeSection === Sections.Settings ? (
<Settings
isSourceMode={isSourceMode}
stateReference={linked}
onInputDataChange={this.onInputDataChange}
resetSwapData={this.resetSwapData}
slippage={slippage}
/>
) : (
<>
<div styleName={`${wrongNetwork ? 'disabled' : ''}`}>
<InputForm
parentState={this.state}
stateReference={linked}
selectCurrency={this.selectCurrency}
flipCurrency={this.flipCurrency}
openExternalExchange={this.openExternalExchange}
onInputDataChange={this.onInputDataChange}
setSpendedAmount={this.setSpendedAmount}
updateWallets={this.updateWallets}
insufficientBalanceA={insufficientBalanceA}
insufficientBalanceB={insufficientBalanceB}
resetReceivedAmount={this.resetReceivedAmount}
setReceivedAmount={this.setReceivedAmount}
/>
</div>
{activeSection === Sections.Source && (
<SourceActions sourceAction={sourceAction} setAction={this.setAction} />
)}
<UserInfo
history={history}
isSourceMode={isSourceMode}
slippage={slippage}
network={network}
swapData={swapData}
swapFee={swapFee}
spendedAmount={spendedAmount}
baseChainWallet={baseChainWallet}
fromWallet={fromWallet}
toWallet={toWallet}
fiat={fiat}
serviceFee={serviceFee}
/>
<Feedback
network={network}
isSourceMode={isSourceMode}
wrongNetwork={wrongNetwork}
insufficientBalanceA={insufficientBalanceA}
blockReason={blockReason}
baseChainWallet={baseChainWallet}
spendedAmount={spendedAmount}
needApproveA={needApproveA}
needApproveB={needApproveB}
spendedCurrency={spendedCurrency}
receivedCurrency={receivedCurrency}
sourceAction={sourceAction}
/>
<Footer
parentState={this.state}
isSourceMode={isSourceMode}
sourceAction={sourceAction}
reportError={this.reportError}
setBlockReason={this.setBlockReason}
resetSwapData={this.resetSwapData}
resetSpendedAmount={this.resetSpendedAmount}
isApiRequestBlocking={this.isApiRequestBlocking}
insufficientBalanceA={insufficientBalanceA}
insufficientBalanceB={insufficientBalanceB}
setPending={this.setPending}
onInputDataChange={this.onInputDataChange}
baseChainWallet={baseChainWallet}
/>
</>
)}
</section>
</>
)
}
}
export default connect(({ currencies, user, oneinch }) => ({
allCurrencies: currencies.items,
tokensWallets: user.tokensData,
activeFiat: user.activeFiat,
metamaskData: user.metamaskData,
availableBlockchains: oneinch.blockchains,
}))(CSSModules(QuickSwap, styles, { allowMultiple: true })) | the_stack |
import {
Block,
BlockFactory,
CssBlockError,
DEFAULT_NAMESPACE,
SourceRange,
isNamespaceReserved,
} from "@css-blocks/core";
import { AST, Walker, preprocess } from "@glimmer/syntax";
import { ElementNode } from "@glimmer/syntax/dist/types/lib/types/nodes";
import { Position, TextDocuments } from "vscode-languageserver";
import { PathTransformer } from "../pathTransformers/PathTransformer";
import { FocusPath, createFocusPath } from "./createFocusPath";
import { toPosition } from "./estTreeUtils";
import { transformPathsFromUri } from "./pathTransformer";
/**
* Recursively walk a glimmer ast and execute a callback for each class
* attribute.
*/
function walkClasses(astNode: AST.Node, callback: (namespace: string, classAttr: AST.AttrNode, classAttrValue: AST.TextNode) => void) {
let walker = new Walker();
walker.visit(astNode, (node) => {
if (node.type === "ElementNode") {
for (let attrNode of node.attributes) {
let nsAttr = parseNamespacedBlockAttribute(attrNode);
if (nsAttr && isClassAttribute(nsAttr) && attrNode.value.type === "TextNode") {
callback(nsAttr.ns, attrNode, attrNode.value);
}
}
}
});
}
/**
* A simple helper to determine whether an attribute node's text value is
* defined with wrapping quotes or with "raw text." In the case of raw,
* unquoted text the length of the `chars` string will be exactly equal to the
* length of the location start and end values. In the case of a quoted string,
* the length of the location start and end will be greater than the length of
* the raw value.
*/
function hasQuotedAttributeValue(attr: AST.TextNode) {
if (attr.loc.end.line - attr.loc.start.line > 0) {
return true;
}
return (attr.loc.end.column - attr.loc.start.column - attr.chars.length) > 0;
}
/**
* Walks the class attribute nodes of a glimmer template ast and uses its
* corresponding css block to check for errors.
*/
export function hbsErrorParser(
documentText: string,
block: Block,
): CssBlockError[] {
let ast = preprocess(documentText);
let errors: CssBlockError[] = [];
walkClasses(ast, (blockName, classAttr, classAttrValue) => {
let rawTextChars = classAttrValue.chars;
let lines = rawTextChars.split(/\r?\n/);
let blockOfClass = blockName === "block" ? block : block.getExportedBlock(blockName);
if (!blockOfClass) {
let range: SourceRange = {
start: {
line: classAttr.loc.start.line,
column: classAttr.loc.start.column + 1,
},
end: {
line: classAttr.loc.start.line,
column: classAttr.loc.start.column + blockName.length,
},
};
errors.push(new CssBlockError(`No exported block named '${blockName}'.`, range));
return;
}
lines.forEach((line, lineNum) => {
if (!line.trim().length) {
return;
}
line.split(/\s+/).forEach(className => {
if (className.length === 0) {
return;
}
let klass = blockOfClass!.getClass(className);
if (klass === null) {
let startColumnOffset = hasQuotedAttributeValue(classAttrValue) ? 1 : 0;
let classNameStartColumn = lineNum === 0 ? classAttrValue.loc.start.column + line.indexOf(className) + startColumnOffset : line.indexOf(className);
let classNameLine = classAttrValue.loc.start.line + lineNum;
let range: SourceRange = {
start: {
line: classNameLine,
column: classNameStartColumn + 1,
},
end: {
line: classNameLine,
column: classNameStartColumn + className.length,
},
};
errors.push(new CssBlockError(`Class name '${className}' not found.`, range));
}
});
});
});
return errors;
}
export function isTemplateFile(uri: string) {
return uri.endsWith(".hbs");
}
interface ErrorsForUri {
uri: string;
errors: CssBlockError[];
}
export async function validateTemplates(
documents: TextDocuments,
factory: BlockFactory,
pathTransformer: PathTransformer,
): Promise<Map<string, CssBlockError[]>> {
let openTextDocuments = documents
.all()
.filter(doc => isTemplateFile(doc.uri));
let errorsForUri: (ErrorsForUri | null)[] = await Promise.all(
openTextDocuments.map(
async (document): Promise<ErrorsForUri | null> => {
const { blockFsPath, templateUri } = transformPathsFromUri(
document.uri,
pathTransformer,
factory.configuration,
);
if (blockFsPath && templateUri) {
try {
let block = await factory.getBlockFromPath(blockFsPath);
let documentText = document.getText();
let errors = hbsErrorParser(documentText, block);
return {
uri: templateUri,
errors,
};
} catch (e) {
// TODO: we need to do *something* about this
}
}
return null;
},
),
);
return errorsForUri.reduce((result, uriWithErrors) => {
if (uriWithErrors) {
result.set(uriWithErrors.uri, uriWithErrors.errors);
}
return result;
}, new Map());
}
export const enum AttributeType {
state = "state",
class = "class",
scope = "scope",
ambiguous = "ambiguous",
}
interface BlockAttributeBase {
attributeType: AttributeType;
referencedBlock?: string;
}
export interface ScopeAttribute extends BlockAttributeBase {
attributeType: AttributeType.scope;
}
export interface ClassAttribute extends BlockAttributeBase {
attributeType: AttributeType.class;
name?: string;
}
export interface StateAttribute extends BlockAttributeBase {
attributeType: AttributeType.state;
name: string;
value?: string;
}
export interface AmbiguousAttribute extends BlockAttributeBase {
attributeType: AttributeType.ambiguous;
referencedBlock?: undefined;
name: string;
}
export type BlockAttribute = ScopeAttribute | ClassAttribute | StateAttribute | AmbiguousAttribute;
interface NamespacedAttr {
ns: string;
name: string;
value?: string;
}
interface ItemAtCursor {
attribute: BlockAttribute;
siblingAttributes: ClassAttribute[];
}
function getParentElement(focusRoot: FocusPath | null): ElementNode | null {
let curr = focusRoot;
while (curr) {
if (curr.data && curr.data.type === "ElementNode") {
return curr.data;
}
curr = curr.parent;
}
return null;
}
function buildClassAttribute(attr: NamespacedAttr | null, attrValue: AST.AttrNode["value"]): ClassAttribute | null {
if (attr === null) return null;
if (attrValue.type === "TextNode") {
if (attr.ns === "block") {
return {
attributeType: AttributeType.class,
name: attrValue.chars.trim(),
};
} else {
return {
attributeType: AttributeType.class,
referencedBlock: attr.ns,
name: attrValue.chars.trim(),
};
}
} else {
return null;
}
}
function parseNamespacedBlockAttribute(attrNode: AST.Node | null | undefined): NamespacedAttr | null {
if (!attrNode || !isAttrNode(attrNode)) return null;
if (/([^:]+):([^:]+|$)/.test(attrNode.name)) {
let ns = RegExp.$1;
let name = RegExp.$2;
if (isNamespaceReserved(ns)) {
return null;
}
return {ns, name};
}
return null;
}
function isAttrNode(node: FocusPath | AST.Node | NamespacedAttr | null): node is AST.AttrNode {
return node !== null && ((<AST.Node>node).type) === "AttrNode";
}
function isStateAttribute(attr: NamespacedAttr): boolean {
return attr.name !== AttributeType.class && attr.name !== AttributeType.scope;
}
function isClassAttribute(attr: NamespacedAttr): boolean {
return attr.name === AttributeType.class;
}
// TODO: this will be handy when we add support for the scope attribute.
//
// function isScopeAttribute(attr: NamespacedAttr | null): attr is NamespacedAttr {
// if (attr === null) return false;
// return attr.name === SupportedAttributes.scope;
// }
/**
* Returns an object that represents the item under the cursor in the client
* editor which contains metadata regarding sibling css-block classes,
* referenced blocks, and the parent attribute type of the current item. The
* sibling blocks are useful for making auto-completions for state attributes
* more contextual.
*/
export function getItemAtCursor(text: string, position: Position): ItemAtCursor | null {
let ast = preprocess(text);
let focusRoot = createFocusPath(ast, toPosition(position));
let data = focusRoot && focusRoot.data;
let focusedAttr = focusRoot;
while (focusedAttr && focusedAttr.data && focusedAttr.data.type !== "AttrNode") {
focusedAttr = focusedAttr.parent;
}
let attrNode = focusedAttr && <AST.AttrNode | null>focusedAttr.data;
if (!attrNode || !focusedAttr) {
return null;
}
let attr = parseNamespacedBlockAttribute(attrNode);
if (!attr) {
return {
attribute: {
attributeType: AttributeType.ambiguous,
name: attrNode.name,
},
siblingAttributes: [],
};
}
if (isStateAttribute(attr)) {
return getStateAtCursor(focusRoot, attr);
}
// TODO: Handle the other types of attribute value nodes
if (isClassAttribute(attr) && data && data.type === "TextNode") {
let attribute = buildClassAttribute(attr, data);
if (attribute) {
return { attribute, siblingAttributes: []};
} else {
return null;
}
}
return null;
}
function getStateAtCursor(focusRoot: FocusPath | null, attr: NamespacedAttr): ItemAtCursor | null {
let parentElement = getParentElement(focusRoot);
if (!parentElement) {
return null;
}
let attribute: StateAttribute = {
attributeType: AttributeType.state,
referencedBlock: attr.ns === DEFAULT_NAMESPACE ? undefined : attr.ns,
name: attr.name,
};
let classAttributes = parentElement.attributes.map(attrNode => {
return [parseNamespacedBlockAttribute(attrNode), attrNode.value] as const;
}).filter(([attr, _attrValue]) => {
return attr && isClassAttribute(attr);
});
let siblingAttributes = classAttributes.map(([attr, attrValue]) => {
return buildClassAttribute(attr, attrValue);
}).filter((bs): bs is ClassAttribute => {
return bs !== null;
});
if (siblingAttributes.length > 0) {
return {
attribute,
siblingAttributes,
};
} else {
return null;
}
} | the_stack |
import { AxisRenderer, IAxisRendererSettings, IAxisRendererPrivate } from "./AxisRenderer";
import { p100 } from "../../../core/util/Percent";
import type { IPoint } from "../../../core/util/IPoint";
import * as $type from "../../../core/util/Type";
import * as $utils from "../../../core/util/Utils";
import type { Graphics } from "../../../core/render/Graphics";
import type { AxisLabel } from "./AxisLabel";
import type { AxisBullet } from "./AxisBullet";
import type { Grid } from "./Grid";
import type { AxisTick } from "./AxisTick";
import type { Tooltip } from "../../../core/render/Tooltip";
import type { Template } from "../../../core/util/Template";
import { Rectangle } from "../../../core/render/Rectangle";
export interface IAxisRendererYSettings extends IAxisRendererSettings {
/**
* If set to `true` the axis will be drawn on the opposite side of the plot
* area.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Axis_position} for more info
* @default false
*/
opposite?: boolean;
/**
* If set to `true`, all axis elements (ticks, labels) will be drawn inside
* plot area.
*
* @default false
*/
inside?: boolean;
}
export interface IAxisRendererYPrivate extends IAxisRendererPrivate {
}
/**
* Used to render vertical axis.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/#Axis_renderer} for more info
* @important
*/
export class AxisRendererY extends AxisRenderer {
public static className: string = "AxisRendererY";
public static classNames: Array<string> = AxisRenderer.classNames.concat([AxisRendererY.className]);
declare public _settings: IAxisRendererYSettings;
declare public _privateSettings: IAxisRendererYPrivate;
declare public readonly labelTemplate: Template<AxisLabel>;
protected _downY?: number;
public thumb: Rectangle = Rectangle.new(this._root, { height: p100, themeTags: ["axis", "y", "thumb"] });
public _afterNew() {
this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["renderer", "y"]);
if (this._settings.opposite) {
this._settings.themeTags.push("opposite");
}
super._afterNew();
this.setPrivateRaw("letter", "Y");
const gridTemplate = this.grid.template;
gridTemplate.set("width", p100);
gridTemplate.set("height", 0);
gridTemplate.set("draw", (display, graphics) => {
display.moveTo(0, 0);
display.lineTo(graphics.width(), 0);
});
this.set("draw", (display, renderer) => {
display.moveTo(0, 0);
display.lineTo(0, renderer.height());
});
}
protected _getPan(point1: IPoint, point2: IPoint): number {
return (point1.y - point2.y) / this.height();
}
public _changed() {
super._changed();
const axis = this.axis;
if (this.isDirty("inside")) {
axis.markDirtySize();
}
const thumb = this.thumb;
const opposite = "opposite"
if (this.isDirty(opposite)) {
const chart = this.chart;
const axisChildren = axis.children;
if (chart) {
if (this.get(opposite)) {
const children = chart.rightAxesContainer.children;
if (children.indexOf(axis) == -1) {
children.moveValue(axis, 0);
}
axis.addTag(opposite);
axisChildren.moveValue(this, 0);
thumb.set("centerX", 0);
}
else {
const children = chart.leftAxesContainer.children;
if (children.indexOf(axis) == -1) {
children.moveValue(axis);
}
axis.removeTag("opposite");
axisChildren.moveValue(this);
thumb.set("centerX", p100);
}
axis.markDirtySize();
}
axis.ghostLabel._applyThemes();
}
thumb.setPrivate("width", axis.labelsContainer.width());
}
/**
* @ignore
*/
public processAxis() {
super.processAxis();
const axis = this.axis;
if (axis.get("height") == null) {
axis.set("height", p100);
}
const horizontalLayout = this._root.horizontalLayout;
axis.set("layout", horizontalLayout);
axis.labelsContainer.set("height", p100);
axis.axisHeader.set("layout", horizontalLayout);
}
public _updatePositions() {
const axis = this.axis;
axis.gridContainer.set("y", axis.y() - $utils.relativeToValue(axis.get("centerY", 0), axis.height()));
axis.bulletsContainer.set("x", this.x());
const chart = axis.chart;
if (chart) {
const plotContainer = chart.plotContainer;
const axisHeader = axis.axisHeader;
let height = axis.get("marginTop", 0);
if (axisHeader.children.length > 0) {
height = axis.axisHeader.height();
axis.set("marginTop", height);
}
else {
axisHeader.set("height", height);
}
axisHeader.setAll({ y: axis.y() - height, x: -1, width: plotContainer.width() + 2 });
}
}
/**
* @ignore
*/
public axisLength(): number {
return this.axis.innerHeight();
}
/**
* Converts axis relative position to actual coordinate in pixels.
*
* @param position Position
* @return Point
*/
public positionToPoint(position: number): IPoint {
return { x: 0, y: this.positionToCoordinate(position) };
}
/**
* @ignore
*/
public updateLabel(label?: AxisLabel, position?: number, endPosition?: number, count?: number) {
if (label) {
if (!$type.isNumber(position)) {
position = 0;
}
let location = 0.5;
if ($type.isNumber(count) && count > 1) {
location = label.get("multiLocation", location)
}
else {
location = label.get("location", location)
}
const opposite = this.get("opposite");
const inside = label.get("inside", this.get("inside", false));
if (opposite) {
label.set("x", 0);
if (inside) {
label.set("position", "absolute");
}
else {
label.set("position", "relative");
}
}
else {
if (inside) {
label.set("x", 0);
label.set("position", "absolute");
}
else {
label.set("x", undefined);
label.set("position", "relative");
}
}
if ($type.isNumber(endPosition) && endPosition != position) {
position = position + (endPosition - position) * location;
}
label.set("y", this.positionToCoordinate(position));
this.toggleVisibility(label, position, label.get("minPosition", 0), label.get("maxPosition", 1));
}
}
/**
* @ignore
*/
public updateGrid(grid?: Grid, position?: number, endPosition?: number) {
if (grid) {
if (!$type.isNumber(position)) {
position = 0;
}
let location = grid.get("location", 0.5);
if ($type.isNumber(endPosition) && endPosition != position) {
position = position + (endPosition - position) * location;
}
let y = this.positionToCoordinate(position);
grid.set("y", y);
this.toggleVisibility(grid, position, 0, 1);
}
}
/**
* @ignore
*/
public updateTick(tick?: AxisTick, position?: number, endPosition?: number, count?: number) {
if (tick) {
if (!$type.isNumber(position)) {
position = 0;
}
let location = 0.5;
if ($type.isNumber(count) && count > 1) {
location = tick.get("multiLocation", location);
}
else {
location = tick.get("location", location);
}
if ($type.isNumber(endPosition) && endPosition != position) {
position = position + (endPosition - position) * location;
}
tick.set("y", this.positionToCoordinate(position));
let length = tick.get("length", 0);
const inside = tick.get("inside", this.get("inside", false));
if (this.get("opposite")) {
tick.set("x", 0);
if (inside) {
length *= -1
}
}
else {
if (!inside) {
length *= -1
}
}
tick.set("draw", (display) => {
display.moveTo(0, 0);
display.lineTo(length, 0);
})
this.toggleVisibility(tick, position, tick.get("minPosition", 0), tick.get("maxPosition", 1));
}
}
/**
* @ignore
*/
public updateBullet(bullet?: AxisBullet, position?: number, endPosition?: number) {
if (bullet) {
const sprite = bullet.get("sprite");
if (sprite) {
if (!$type.isNumber(position)) {
position = 0;
}
let location = bullet.get("location", 0.5);
if ($type.isNumber(endPosition) && endPosition != position) {
position = position + (endPosition - position) * location;
}
sprite.set("y", this.positionToCoordinate(position));
this.toggleVisibility(sprite, position, 0, 1);
}
}
}
/**
* @ignore
*/
public updateFill(fill?: Graphics, position?: number, endPosition?: number) {
if (fill) {
if (!$type.isNumber(position)) {
position = 0;
}
if (!$type.isNumber(endPosition)) {
endPosition = 1;
}
let y0 = this.positionToCoordinate(position);
let y1 = this.positionToCoordinate(endPosition);
this.fillDrawMethod(fill, y0, y1);
}
}
protected fillDrawMethod(fill: Graphics, y0: number, y1: number) {
fill.set("draw", (display) => {
// using for holes, so can not be rectangle
const w = this.axis!.gridContainer.width();
const h = this.height();
if (y1 < y0) {
[y1, y0] = [y0, y1];
}
if (y0 > h || y1 < 0) {
return;
}
y0 = Math.max(0, y0);
y1 = Math.min(h, y1);
display.moveTo(0, y0);
display.lineTo(w, y0);
display.lineTo(w, y1);
display.lineTo(0, y1);
display.lineTo(0, y0);
})
}
/**
* Converts relative position (0-1) on axis to a pixel coordinate.
*
* @param position Position (0-1)
* @return Coordinate (px)
*/
public positionToCoordinate(position: number): number {
if (!this._inversed) {
return (this._end - position) * this._axisLength;
}
else {
return (position - this._start) * this._axisLength;
}
}
/**
* @ignore
*/
public positionTooltip(tooltip: Tooltip, position: number) {
this._positionTooltip(tooltip, { x: 0, y: this.positionToCoordinate(position) });
}
/**
* @ignore
*/
public updateTooltipBounds(tooltip: Tooltip) {
const inside = this.get("inside");
const num = 100000;
let global = this._display.toGlobal({ x: 0, y: 0 });
let y = global.y;
let x = 0;
let h = this.axisLength();
let w = num;
let pointerOrientation: "left" | "right" = "right";
if (this.get("opposite")) {
if (inside) {
pointerOrientation = "right";
x = global.x - num;
w = num;
}
else {
pointerOrientation = "left";
x = global.x;
w = num;
}
}
else {
if (inside) {
pointerOrientation = "left";
x = global.x;
w = num;
}
else {
pointerOrientation = "right";
x = global.x - num;
w = num;
}
}
const bounds = { left: x, right: x + w, top: y, bottom: y + h };
const oldBounds = tooltip.get("bounds");
if (!$utils.sameBounds(bounds, oldBounds)) {
tooltip.set("bounds", bounds);
tooltip.set("pointerOrientation", pointerOrientation);
}
}
public _updateLC() {
const axis = this.axis;
const parent = axis.parent;
if (parent) {
const h = parent.innerHeight();
this._lc = this.axisLength() / h;
this._ls = axis.y() / h;
}
}
/**
* @ignore
*/
public toAxisPosition(position: number): number {
const start = this._start || 0;
const end = this._end || 1;
position -= this._ls;
position = position * (end - start) / this._lc;
if (this.get("inversed")) {
position = start + position;
}
else {
position = end - position;
}
return position;
}
/**
* @ignore
*/
public fixPosition(position: number) {
if (!this.get("inversed")) {
return 1 - position;
}
return position;
}
} | the_stack |
import Point from '@mapbox/point-geometry';
import Transform from './transform';
import LngLat from './lng_lat';
import {OverscaledTileID, CanonicalTileID} from '../source/tile_id';
import {fixedLngLat, fixedCoord} from '../../test/unit/lib/fixed';
import type Terrain from '../render/terrain';
describe('transform', () => {
test('creates a transform', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(500, 500);
expect(transform.unmodified).toBe(true);
expect(transform.maxValidLatitude).toBe(85.051129);
expect(transform.tileSize).toBe(512);
expect(transform.worldSize).toBe(512);
expect(transform.width).toBe(500);
expect(transform.minZoom).toBe(0);
expect(transform.minPitch).toBe(0);
// Support signed zero
expect(transform.bearing === 0 ? 0 : transform.bearing).toBe(0);
expect(transform.bearing = 1).toBe(1);
expect(transform.bearing).toBe(1);
expect(transform.bearing = 0).toBe(0);
expect(transform.unmodified).toBe(false);
expect(transform.minZoom = 10).toBe(10);
expect(transform.maxZoom = 10).toBe(10);
expect(transform.minZoom).toBe(10);
expect(transform.center).toEqual({lng: 0, lat: 0});
expect(transform.maxZoom).toBe(10);
expect(transform.minPitch = 10).toBe(10);
expect(transform.maxPitch = 10).toBe(10);
expect(transform.size.equals(new Point(500, 500))).toBe(true);
expect(transform.centerPoint.equals(new Point(250, 250))).toBe(true);
expect(transform.scaleZoom(0)).toBe(-Infinity);
expect(transform.scaleZoom(10)).toBe(3.3219280948873626);
expect(transform.point).toEqual(new Point(262144, 262144));
expect(transform.height).toBe(500);
expect(fixedLngLat(transform.pointLocation(new Point(250, 250)))).toEqual({lng: 0, lat: 0});
expect(fixedCoord(transform.pointCoordinate(new Point(250, 250)))).toEqual({x: 0.5, y: 0.5, z: 0});
expect(transform.locationPoint(new LngLat(0, 0))).toEqual({x: 250, y: 250});
expect(transform.locationCoordinate(new LngLat(0, 0))).toEqual({x: 0.5, y: 0.5, z: 0});
});
test('does not throw on bad center', () => {
expect(() => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(500, 500);
transform.center = new LngLat(50, -90);
}).not.toThrow();
});
test('setLocationAt', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(500, 500);
transform.zoom = 4;
expect(transform.center).toEqual({lng: 0, lat: 0});
transform.setLocationAtPoint(new LngLat(13, 10), new Point(15, 45));
expect(fixedLngLat(transform.pointLocation(new Point(15, 45)))).toEqual({lng: 13, lat: 10});
});
test('setLocationAt tilted', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(500, 500);
transform.zoom = 4;
transform.pitch = 50;
expect(transform.center).toEqual({lng: 0, lat: 0});
transform.setLocationAtPoint(new LngLat(13, 10), new Point(15, 45));
expect(fixedLngLat(transform.pointLocation(new Point(15, 45)))).toEqual({lng: 13, lat: 10});
});
test('has a default zoom', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(500, 500);
expect(transform.tileZoom).toBe(0);
expect(transform.tileZoom).toBe(transform.zoom);
});
test('set fov', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.fov = 10;
expect(transform.fov).toBe(10);
transform.fov = 10;
expect(transform.fov).toBe(10);
});
test('lngRange & latRange constrain zoom and center', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.center = new LngLat(0, 0);
transform.zoom = 10;
transform.resize(500, 500);
transform.lngRange = [-5, 5];
transform.latRange = [-5, 5];
transform.zoom = 0;
expect(transform.zoom).toBe(5.135709286104402);
transform.center = new LngLat(-50, -30);
expect(transform.center).toEqual(new LngLat(0, -0.0063583052861417855));
transform.zoom = 10;
transform.center = new LngLat(-50, -30);
expect(transform.center).toEqual(new LngLat(-4.828338623046875, -4.828969771321582));
});
describe('coveringTiles', () => {
const options = {
minzoom: 1,
maxzoom: 10,
tileSize: 512
};
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(200, 200);
test('generell', () => {
// make slightly off center so that sort order is not subject to precision issues
transform.center = new LngLat(-0.01, 0.01);
transform.zoom = 0;
expect(transform.coveringTiles(options)).toEqual([]);
transform.zoom = 1;
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(1, 0, 1, 0, 0),
new OverscaledTileID(1, 0, 1, 1, 0),
new OverscaledTileID(1, 0, 1, 0, 1),
new OverscaledTileID(1, 0, 1, 1, 1)]);
transform.zoom = 2.4;
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(2, 0, 2, 1, 1),
new OverscaledTileID(2, 0, 2, 2, 1),
new OverscaledTileID(2, 0, 2, 1, 2),
new OverscaledTileID(2, 0, 2, 2, 2)]);
transform.zoom = 10;
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(10, 0, 10, 511, 511),
new OverscaledTileID(10, 0, 10, 512, 511),
new OverscaledTileID(10, 0, 10, 511, 512),
new OverscaledTileID(10, 0, 10, 512, 512)]);
transform.zoom = 11;
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(10, 0, 10, 511, 511),
new OverscaledTileID(10, 0, 10, 512, 511),
new OverscaledTileID(10, 0, 10, 511, 512),
new OverscaledTileID(10, 0, 10, 512, 512)]);
transform.zoom = 5.1;
transform.pitch = 60.0;
transform.bearing = 32.0;
transform.center = new LngLat(56.90, 48.20);
transform.resize(1024, 768);
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(5, 0, 5, 21, 11),
new OverscaledTileID(5, 0, 5, 20, 11),
new OverscaledTileID(5, 0, 5, 21, 10),
new OverscaledTileID(5, 0, 5, 20, 10),
new OverscaledTileID(5, 0, 5, 21, 12),
new OverscaledTileID(5, 0, 5, 22, 11),
new OverscaledTileID(5, 0, 5, 20, 12),
new OverscaledTileID(5, 0, 5, 22, 10),
new OverscaledTileID(5, 0, 5, 21, 9),
new OverscaledTileID(5, 0, 5, 20, 9),
new OverscaledTileID(5, 0, 5, 22, 9),
new OverscaledTileID(5, 0, 5, 23, 10),
new OverscaledTileID(5, 0, 5, 21, 8),
new OverscaledTileID(5, 0, 5, 20, 8),
new OverscaledTileID(5, 0, 5, 23, 9),
new OverscaledTileID(5, 0, 5, 22, 8),
new OverscaledTileID(5, 0, 5, 23, 8),
new OverscaledTileID(5, 0, 5, 21, 7),
new OverscaledTileID(5, 0, 5, 20, 7),
new OverscaledTileID(5, 0, 5, 24, 9),
new OverscaledTileID(5, 0, 5, 22, 7)
]);
transform.zoom = 8;
transform.pitch = 60;
transform.bearing = 45.0;
transform.center = new LngLat(25.02, 60.15);
transform.resize(300, 50);
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(8, 0, 8, 145, 74),
new OverscaledTileID(8, 0, 8, 145, 73),
new OverscaledTileID(8, 0, 8, 146, 74)
]);
transform.resize(50, 300);
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(8, 0, 8, 145, 74),
new OverscaledTileID(8, 0, 8, 145, 73),
new OverscaledTileID(8, 0, 8, 146, 74),
new OverscaledTileID(8, 0, 8, 146, 73)
]);
transform.zoom = 2;
transform.pitch = 0;
transform.bearing = 0;
transform.resize(300, 300);
});
test('calculates tile coverage at w > 0', () => {
transform.center = new LngLat(630.01, 0.01);
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(2, 2, 2, 1, 1),
new OverscaledTileID(2, 2, 2, 1, 2),
new OverscaledTileID(2, 2, 2, 0, 1),
new OverscaledTileID(2, 2, 2, 0, 2)
]);
});
test('calculates tile coverage at w = -1', () => {
transform.center = new LngLat(-360.01, 0.01);
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(2, -1, 2, 1, 1),
new OverscaledTileID(2, -1, 2, 1, 2),
new OverscaledTileID(2, -1, 2, 2, 1),
new OverscaledTileID(2, -1, 2, 2, 2)
]);
});
test('calculates tile coverage across meridian', () => {
transform.zoom = 1;
transform.center = new LngLat(-180.01, 0.01);
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(1, 0, 1, 0, 0),
new OverscaledTileID(1, 0, 1, 0, 1),
new OverscaledTileID(1, -1, 1, 1, 0),
new OverscaledTileID(1, -1, 1, 1, 1)
]);
});
test('only includes tiles for a single world, if renderWorldCopies is set to false', () => {
transform.zoom = 1;
transform.center = new LngLat(-180.01, 0.01);
transform.renderWorldCopies = false;
expect(transform.coveringTiles(options)).toEqual([
new OverscaledTileID(1, 0, 1, 0, 0),
new OverscaledTileID(1, 0, 1, 0, 1)
]);
});
});
test('coveringZoomLevel', () => {
const options = {
minzoom: 1,
maxzoom: 10,
tileSize: 512,
roundZoom: false,
};
const transform = new Transform(0, 22, 0, 60, true);
transform.zoom = 0;
expect(transform.coveringZoomLevel(options)).toBe(0);
transform.zoom = 0.1;
expect(transform.coveringZoomLevel(options)).toBe(0);
transform.zoom = 1;
expect(transform.coveringZoomLevel(options)).toBe(1);
transform.zoom = 2.4;
expect(transform.coveringZoomLevel(options)).toBe(2);
transform.zoom = 10;
expect(transform.coveringZoomLevel(options)).toBe(10);
transform.zoom = 11;
expect(transform.coveringZoomLevel(options)).toBe(11);
transform.zoom = 11.5;
expect(transform.coveringZoomLevel(options)).toBe(11);
options.tileSize = 256;
transform.zoom = 0;
expect(transform.coveringZoomLevel(options)).toBe(1);
transform.zoom = 0.1;
expect(transform.coveringZoomLevel(options)).toBe(1);
transform.zoom = 1;
expect(transform.coveringZoomLevel(options)).toBe(2);
transform.zoom = 2.4;
expect(transform.coveringZoomLevel(options)).toBe(3);
transform.zoom = 10;
expect(transform.coveringZoomLevel(options)).toBe(11);
transform.zoom = 11;
expect(transform.coveringZoomLevel(options)).toBe(12);
transform.zoom = 11.5;
expect(transform.coveringZoomLevel(options)).toBe(12);
options.roundZoom = true;
expect(transform.coveringZoomLevel(options)).toBe(13);
});
test('clamps latitude', () => {
const transform = new Transform(0, 22, 0, 60, true);
expect(transform.project(new LngLat(0, -90))).toEqual(transform.project(new LngLat(0, -transform.maxValidLatitude)));
expect(transform.project(new LngLat(0, 90))).toEqual(transform.project(new LngLat(0, transform.maxValidLatitude)));
});
test('clamps pitch', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.pitch = 45;
expect(transform.pitch).toBe(45);
transform.pitch = -10;
expect(transform.pitch).toBe(0);
transform.pitch = 90;
expect(transform.pitch).toBe(60);
});
test('visibleUnwrappedCoordinates', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(200, 200);
transform.zoom = 0;
transform.center = new LngLat(-170.01, 0.01);
let unwrappedCoords = transform.getVisibleUnwrappedCoordinates(new CanonicalTileID(0, 0, 0));
expect(unwrappedCoords).toHaveLength(4);
//getVisibleUnwrappedCoordinates should honor _renderWorldCopies
transform._renderWorldCopies = false;
unwrappedCoords = transform.getVisibleUnwrappedCoordinates(new CanonicalTileID(0, 0, 0));
expect(unwrappedCoords).toHaveLength(1);
});
test('maintains high float precision when calculating matrices', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(200.25, 200.25);
transform.zoom = 20.25;
transform.pitch = 67.25;
transform.center = new LngLat(0.0, 0.0);
transform._calcMatrices();
expect(transform.customLayerMatrix()[0].toString().length).toBeGreaterThan(10);
expect(transform.glCoordMatrix[0].toString().length).toBeGreaterThan(10);
expect(transform.maxPitchScaleFactor()).toBeCloseTo(2.366025418080343, 10);
});
test('recalcuateZoom', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.elevation = 200;
transform.center = new LngLat(10.0, 50.0);
transform.zoom = 14;
transform.resize(512, 512);
// expect same values because of no elevation change
transform.getElevation = () => 200;
transform.recalculateZoom(null);
expect(transform.zoom).toBe(14);
// expect new zoom because of elevation change
transform.getElevation = () => 400;
transform.recalculateZoom(null);
expect(transform.zoom).toBe(14.127997275621933);
expect(transform.elevation).toBe(400);
expect(transform._center.lng).toBe(10.00000000000071);
expect(transform._center.lat).toBe(50.00000000000017);
});
test('pointCoordinate with terrain when returning null should fall back to 2D', () => {
const transform = new Transform(0, 22, 0, 60, true);
transform.resize(500, 500);
const terrain = {
pointCoordinate: () => null
} as any as Terrain;
const coordinate = transform.pointCoordinate(new Point(0, 0), terrain);
expect(coordinate).toBeDefined();
});
test('horizon', () => {
const transform = new Transform(0, 22, 0, 85, true);
transform.resize(500, 500);
transform.pitch = 75;
const horizon = transform.getHorizon();
expect(horizon).toBeCloseTo(170.8176101748407, 10);
});
test('getBounds with horizon', () => {
const transform = new Transform(0, 22, 0, 85, true);
transform.resize(500, 500);
transform.pitch = 60;
expect(transform.getBounds().getNorthWest().toArray()).toStrictEqual(transform.pointLocation(new Point(0, 0)).toArray());
transform.pitch = 75;
const top = Math.max(0, transform.height / 2 - transform.getHorizon());
expect(top).toBeCloseTo(79.1823898251593, 10);
expect(transform.getBounds().getNorthWest().toArray()).toStrictEqual(transform.pointLocation(new Point(0, top)).toArray());
});
}); | the_stack |
import "./Tests";
import { SortDefinitionOrder, TriggerCallbackHandler, SortDefinition, RelativeSortDefinition, Parser, Widget, ParsedCell, TablesorterHeading, StorageConfiguration } from "tablesorter";
import { RelativeSorting } from "tablesorter/Sorting/RelativeSorting";
import { StorageType } from "tablesorter/Storage/StorageType";
/**
* Provides tests for the methods.
*/
export class TestMethods<T extends HTMLElement> {
/**
* A jQuery-object for testing.
*/
protected table = $<T>("");
/**
* A set of sort-definitions for testing.
*/
protected sorting: ReadonlyArray<SortDefinition> = [[0, 1], [1, 0]];
/**
* A set of relative sort-definitions for testing.
*/
protected relativeSorting: ReadonlyArray<RelativeSortDefinition> = [[0, "o"], [1, "s"]];
/**
* A set of mixed sort-definitions for testing.
*/
protected mixedSorting: ReadonlyArray<SortDefinition | RelativeSortDefinition> = [
[0, "d"],
[1, "o"]];
/**
* A trigger-callback for testing.
*/
protected triggerCallback: TriggerCallbackHandler<T> = (table) => {
// $ExpectType T
table;
}
/**
* Tests for the methods.
*/
Test() {
const $: JQueryStatic<T> = {} as any;
const tableElement = this.table[0];
const config = this.table[0].config;
const parser: Parser<T> = {} as any;
const widget: Widget<T> = {} as any;
const parsedCellCallback = (cell: ParsedCell): void => { };
const ajaxSettings: JQuery.AjaxSettings = {} as any;
const request: JQuery.jqXHR = {} as any;
const storageConfig: StorageConfiguration = {
group: "",
id: "",
page: "",
storageType: "c",
url: ""
};
/**
* Methods
* Invoking methods directly
*/
$.tablesorter.addHeaderResizeEvent(this.table, true);
$.tablesorter.addHeaderResizeEvent(this.table, true, { timer: 20 });
$.tablesorter.addHeaderResizeEvent(tableElement, true);
$.tablesorter.addHeaderResizeEvent(tableElement, true, { timer: 20 });
$.tablesorter.addRows(config, $(), true);
$.tablesorter.addRows(config, $(), true, this.triggerCallback);
$.tablesorter.addRows(config, $(), this.sorting);
$.tablesorter.addRows(config, $(), this.sorting, this.triggerCallback);
$.tablesorter.addRows(config, "", true);
$.tablesorter.addRows(config, "", true, this.triggerCallback);
$.tablesorter.addRows(config, "", this.sorting);
$.tablesorter.addRows(config, "", this.sorting, this.triggerCallback);
$.tablesorter.addInstanceMethods({ hello: () => null });
$.tablesorter.addInstanceMethods({ world() { } });
$.tablesorter.addParser(parser);
$.tablesorter.addWidget(widget);
$.tablesorter.appendCache(config);
$.tablesorter.applyWidget(this.table);
$.tablesorter.applyWidget(this.table, true);
$.tablesorter.applyWidget(this.table, true, this.triggerCallback);
$.tablesorter.applyWidget(tableElement);
$.tablesorter.applyWidget(tableElement, true);
$.tablesorter.applyWidget(tableElement, true, this.triggerCallback);
$.tablesorter.applyWidgetId(this.table, "zebra");
$.tablesorter.applyWidgetId(tableElement, "zebra");
$.tablesorter.bindEvents(this.table, $());
$.tablesorter.bindEvents(tableElement, $());
$.tablesorter.clearTableBody(this.table);
$.tablesorter.clearTableBody(tableElement);
$.tablesorter.computeColumnIndex($(), config);
$.tablesorter.destroy(this.table);
$.tablesorter.destroy(this.table, true);
$.tablesorter.destroy(this.table, true, this.triggerCallback);
$.tablesorter.destroy(tableElement);
$.tablesorter.destroy(tableElement, true);
$.tablesorter.destroy(tableElement, true, this.triggerCallback);
$.tablesorter.fixColumnWidth(this.table);
$.tablesorter.fixColumnWidth(tableElement);
$.tablesorter.formatFloat("", this.table);
$.tablesorter.formatFloat("", tableElement);
// $ExpectType Widget<T>
$.tablesorter.getColumnData(this.table, { 0: widget, "*": widget }, 0);
// $ExpectType Widget<T>
$.tablesorter.getColumnData(this.table, { 0: widget, "*": widget }, "*");
// $ExpectType Widget<T>
$.tablesorter.getColumnData(tableElement, { 0: widget, "*": widget }, 0);
// $ExpectType Widget<T>
$.tablesorter.getColumnData(tableElement, { 0: widget, "*": widget }, "*");
$.tablesorter.getColumnText(this.table, 0);
$.tablesorter.getColumnText(this.table, 0, parsedCellCallback);
$.tablesorter.getColumnText(this.table, 0, parsedCellCallback, "*");
$.tablesorter.getColumnText(this.table, 0, parsedCellCallback, $());
$.tablesorter.getColumnText(this.table, 0, parsedCellCallback, $()[0]);
$.tablesorter.getColumnText(
this.table,
0,
parsedCellCallback,
(index, element) => {
// $ExpectType number
index;
// $ExpectType HTMLElement
element;
return true;
});
$.tablesorter.getColumnText(tableElement, 0);
$.tablesorter.getColumnText(tableElement, 0, parsedCellCallback);
$.tablesorter.getColumnText(tableElement, 0, parsedCellCallback, "*");
$.tablesorter.getColumnText(tableElement, 0, parsedCellCallback, $());
$.tablesorter.getColumnText(tableElement, 0, parsedCellCallback, $()[0]);
$.tablesorter.getColumnText(
tableElement,
0,
parsedCellCallback,
(index, element) => {
// $ExpectType number
index;
// $ExpectType HTMLElement
element;
return true;
});
// $ExpectType string | boolean | undefined
$.tablesorter.getData($(), config.headers[0], "sorter");
// $ExpectType string | boolean | undefined
$.tablesorter.getData($()[0], config.headers[0], "sorter");
// $ExpectType "top" | "bottom" | "zero" | "min" | "max" | undefined || "top" | "bottom" | "min" | "max" | "zero" | undefined || StringSorting | undefined
$.tablesorter.getData($(), config.headers[0], "string");
// $ExpectType "top" | "bottom" | "zero" | "min" | "max" | undefined || "top" | "bottom" | "min" | "max" | "zero" | undefined || StringSorting | undefined
$.tablesorter.getData($()[0], config.headers[0], "string");
// $ExpectType string[]
$.tablesorter.getFilters(this.table);
// $ExpectType string[]
$.tablesorter.getFilters(this.table, true);
// $ExpectType string[]
$.tablesorter.getFilters(tableElement);
// $ExpectType string[]
$.tablesorter.getFilters(tableElement, true);
// $ExpectType Widget<T>
$.tablesorter.getWidgetById("");
// $ExpectType boolean
$.tablesorter.hasWidget(this.table, "");
// $ExpectType boolean
$.tablesorter.hasWidget(tableElement, "");
// $ExpectType boolean
$.tablesorter.isDigit("");
$.tablesorter.isProcessing(this.table, true);
$.tablesorter.isProcessing(this.table, true, $());
$.tablesorter.isProcessing(tableElement, true);
$.tablesorter.isProcessing(tableElement, true, $());
// $ExpectType boolean
$.tablesorter.isValueInArray(2, this.sorting);
// $ExpectType boolean
$.tablesorter.isValueInArray(2, [[0, "this.table"], [1, 2102311923084], [3, {}]]);
// $ExpectType void
$.tablesorter.processTbody(this.table, $());
// $ExpectType void
$.tablesorter.processTbody(this.table, $(), false);
// $ExpectType JQuery<HTMLElement>
$.tablesorter.processTbody(this.table, $(), true);
// $ExpectType void
$.tablesorter.processTbody(tableElement, $());
// $ExpectType void
$.tablesorter.processTbody(tableElement, $(), false);
// $ExpectType JQuery<HTMLElement>
$.tablesorter.processTbody(tableElement, $(), true);
$.tablesorter.refreshWidgets(this.table);
$.tablesorter.refreshWidgets(this.table, true);
$.tablesorter.refreshWidgets(this.table, true, true);
$.tablesorter.refreshWidgets(tableElement);
$.tablesorter.refreshWidgets(tableElement, true);
$.tablesorter.refreshWidgets(tableElement, true, true);
$.tablesorter.removeWidget(this.table, true);
$.tablesorter.removeWidget(this.table, true, true);
$.tablesorter.removeWidget(this.table, "");
$.tablesorter.removeWidget(this.table, "", true);
$.tablesorter.removeWidget(this.table, ["", ""]);
$.tablesorter.removeWidget(this.table, ["", ""], true);
$.tablesorter.removeWidget(tableElement, true);
$.tablesorter.removeWidget(tableElement, true, true);
$.tablesorter.removeWidget(tableElement, "");
$.tablesorter.removeWidget(tableElement, "", true);
$.tablesorter.removeWidget(tableElement, ["", ""]);
$.tablesorter.removeWidget(tableElement, ["", ""], true);
// $ExpectType string
$.tablesorter.replaceAccents("");
$.tablesorter.resizableReset(this.table);
$.tablesorter.resizableReset(this.table, true);
$.tablesorter.resizableReset(tableElement);
$.tablesorter.resizableReset(tableElement, true);
$.tablesorter.restoreHeaders(this.table);
$.tablesorter.restoreHeaders(tableElement);
$.tablesorter.setFilters(this.table, [""]);
$.tablesorter.setFilters(this.table, [""], true);
$.tablesorter.setFilters(tableElement, [""]);
$.tablesorter.setFilters(tableElement, [""], true);
$.tablesorter.showError(this.table, "", ajaxSettings, "");
$.tablesorter.showError(this.table, request, ajaxSettings, "");
$.tablesorter.showError(tableElement, "", ajaxSettings, "");
$.tablesorter.showError(tableElement, request, ajaxSettings, "");
// $ExpectType number
$.tablesorter.sortNatural("", "");
// $ExpectType number
$.tablesorter.sortText("", "");
$.tablesorter.sortOn(config, this.sorting);
$.tablesorter.sortOn(config, this.sorting, this.triggerCallback);
$.tablesorter.sortOn(config, this.relativeSorting);
$.tablesorter.sortOn(config, this.relativeSorting, this.triggerCallback);
$.tablesorter.sortOn(config, this.mixedSorting);
$.tablesorter.sortOn(config, this.mixedSorting, this.triggerCallback);
$.tablesorter.sortReset(config);
$.tablesorter.sortReset(config, this.triggerCallback);
// $ExpectType any
$.tablesorter.storage(this.table, "");
// $ExpectType void
$.tablesorter.storage(this.table, "", {});
// $ExpectType void
$.tablesorter.storage(this.table, "", {}, storageConfig);
// $ExpectType any
$.tablesorter.storage(tableElement, "");
// $ExpectType void
$.tablesorter.storage(tableElement, "", {});
// $ExpectType void
$.tablesorter.storage(tableElement, "", {}, storageConfig);
$.tablesorter.update(config);
$.tablesorter.update(config, true);
$.tablesorter.update(config, true, this.triggerCallback);
$.tablesorter.update(config, this.sorting);
$.tablesorter.update(config, this.sorting, this.triggerCallback);
$.tablesorter.updateRows(config);
$.tablesorter.updateRows(config, true);
$.tablesorter.updateRows(config, true, this.triggerCallback);
$.tablesorter.updateRows(config, this.sorting);
$.tablesorter.updateRows(config, this.sorting, this.triggerCallback);
$.tablesorter.updateAll(config);
$.tablesorter.updateAll(config, true);
$.tablesorter.updateAll(config, true, this.triggerCallback);
$.tablesorter.updateAll(config, this.sorting);
$.tablesorter.updateAll(config, this.sorting, this.triggerCallback);
$.tablesorter.updateCache(config);
$.tablesorter.updateCache(config, this.triggerCallback);
$.tablesorter.updateCache(config, this.triggerCallback, $());
$.tablesorter.updateCell(config, $());
$.tablesorter.updateCell(config, $(), true);
$.tablesorter.updateCell(config, $(), true, this.triggerCallback);
$.tablesorter.updateCell(config, $(), this.sorting);
$.tablesorter.updateCell(config, $(), this.sorting, this.triggerCallback);
$.tablesorter.updateHeaders(config);
$.tablesorter.updateHeaders(config, this.triggerCallback);
$.tablesorter.filter.bindSearch(this.table, $(), true);
$.tablesorter.filter.bindSearch(tableElement, $(), true);
$.tablesorter.filter.buildSelect(this.table, 0, [1, 2, 3, 4], true);
$.tablesorter.filter.buildSelect(this.table, 0, [1, 2, 3, 4], true, true);
$.tablesorter.filter.buildSelect(this.table, 0, "", true);
$.tablesorter.filter.buildSelect(this.table, 0, "", true, true);
$.tablesorter.filter.buildSelect(this.table, 0, $(), true);
$.tablesorter.filter.buildSelect(this.table, 0, $(), true, true);
$.tablesorter.filter.buildSelect(tableElement, 0, [1, 2, 3, 4], true);
$.tablesorter.filter.buildSelect(tableElement, 0, [1, 2, 3, 4], true, true);
$.tablesorter.filter.buildSelect(tableElement, 0, "", true);
$.tablesorter.filter.buildSelect(tableElement, 0, "", true, true);
$.tablesorter.filter.buildSelect(tableElement, 0, $(), true);
$.tablesorter.filter.buildSelect(tableElement, 0, $(), true, true);
// $ExpectType string[]
$.tablesorter.filter.getOptions(this.table, 0);
// $ExpectType string[]
$.tablesorter.filter.getOptions(this.table, 0, true);
// $ExpectType string[]
$.tablesorter.filter.getOptions(tableElement, 0);
// $ExpectType string[]
$.tablesorter.filter.getOptions(tableElement, 0, true);
// $ExpectType ParsedOption[]
$.tablesorter.filter.getOptionSource(this.table, 0);
// $ExpectType ParsedOption[]
$.tablesorter.filter.getOptionSource(this.table, 0, true);
// $ExpectType ParsedOption[]
$.tablesorter.filter.getOptionSource(tableElement, 0);
// $ExpectType ParsedOption[]
$.tablesorter.filter.getOptionSource(tableElement, 0, true);
// $ExpectType string[]
$.tablesorter.filter.processOptions(this.table, 0, []);
// $ExpectType string[]
$.tablesorter.filter.processOptions(this.table, null, []);
}
} | the_stack |
module Fayde.Controls {
var Key = Input.Key;
var MAX_UNDO_COUNT = 10;
export class TextBoxBase extends Control {
static CaretBrushProperty = DependencyProperty.RegisterCore("CaretBrush", () => Media.Brush, TextBoxBase);
static SelectionForegroundProperty = DependencyProperty.RegisterCore("SelectionForeground", () => Media.Brush, TextBoxBase);
static SelectionBackgroundProperty = DependencyProperty.RegisterCore("SelectionBackground", () => Media.Brush, TextBoxBase);
static SelectionLengthProperty = DependencyProperty.RegisterFull("SelectionLength", () => Number, TextBoxBase, 0, undefined, undefined, true, positiveIntValidator);
static SelectionStartProperty = DependencyProperty.RegisterFull("SelectionStart", () => Number, TextBoxBase, 0, undefined, undefined, true, positiveIntValidator);
static BaselineOffsetProperty = DependencyProperty.Register("BaselineOffset", () => Number, TextBoxBase);
static MaxLengthProperty = DependencyProperty.RegisterFull("MaxLength", () => Number, TextBoxBase, 0, undefined, undefined, undefined, positiveIntValidator);
static SelectionOnFocusProperty = DependencyProperty.Register("SelectionOnFocus", () => new Enum(SelectionOnFocus), TextBoxBase, SelectionOnFocus.Default);
CaretBrush: Media.Brush;
SelectionForeground: Media.Brush;
SelectionBackground: Media.Brush;
SelectionLength: number;
SelectionStart: number;
BaselineOffset: number;
MaxLength: number;
SelectionOnFocus: SelectionOnFocus;
private _Selecting: boolean = false;
private _Captured: boolean = false;
IsReadOnly = false;
AcceptsReturn = false;
$ContentProxy = new Internal.TextBoxContentProxy();
$Proxy: Text.Proxy;
$Advancer: Internal.ICursorAdvancer;
$View: Internal.TextBoxView;
$Clipboard = Clipboard.Create();
constructor(eventsMask: Text.EmitChangedType) {
super();
var view = this.$View = this.CreateView();
view.MouseLeftButtonDown.on((s, e) => this.OnMouseLeftButtonDown(e), this);
view.MouseLeftButtonUp.on((s, e) => this.OnMouseLeftButtonUp(e), this);
this.$Proxy = new Text.Proxy(eventsMask, MAX_UNDO_COUNT);
this._SyncFont();
}
private _SyncFont() {
var view = this.$View;
var propds = [
Control.ForegroundProperty,
Control.FontFamilyProperty,
Control.FontSizeProperty,
Control.FontStretchProperty,
Control.FontStyleProperty,
Control.FontWeightProperty
];
propds.forEach(propd => propd.Store.ListenToChanged(this, propd, (dobj, args) => view.setFontProperty(propd, args.NewValue), this));
}
CreateView(): Internal.TextBoxView {
return new Internal.TextBoxView();
}
get Cursor(): CursorType {
var cursor = this.GetValue(FrameworkElement.CursorProperty);
if (cursor === CursorType.Default)
return CursorType.IBeam;
return cursor;
}
private selectBasedonSelectionMode() {
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
switch (this.SelectionOnFocus) {
case SelectionOnFocus.Unchanged: // 0
break;
case SelectionOnFocus.SelectAll: // 1
proxy.selectAll();
break;
case SelectionOnFocus.CaretToBeginning: // 2
cursor = this.$Advancer.CursorLineBegin(cursor);
proxy.setAnchorCursor(anchor, cursor);
break;
case SelectionOnFocus.CaretToEnd: // 3
cursor = this.$Advancer.CursorLineEnd(cursor);
proxy.setAnchorCursor(anchor, cursor);
break;
case SelectionOnFocus.DefaultSelectAll: // 5
proxy.selectAll();
break;
default: // SelectionOnFocus.Default (4)
break;
}
}
OnApplyTemplate() {
super.OnApplyTemplate();
this.$ContentProxy.setElement(<FrameworkElement>this.GetTemplateChild("ContentElement", FrameworkElement), this.$View);
}
OnLostFocus(e: RoutedEventArgs) {
super.OnLostFocus(e);
this.$View.setIsFocused(false);
}
OnGotFocus(e: RoutedEventArgs) {
super.OnGotFocus(e);
this.$View.setIsFocused(true);
this.selectBasedonSelectionMode();
}
OnMouseLeftButtonDown(e: Input.MouseButtonEventArgs) {
if (e.Handled)
return;
e.Handled = true;
this.Focus();
this._Captured = this.CaptureMouse();
this._Selecting = true;
var cursor = this.$View.GetCursorFromPoint(e.GetPosition(this.$View));
this.$Proxy.beginSelect(cursor);
}
OnMouseLeftButtonUp(e: Input.MouseButtonEventArgs) {
if (e.Handled)
return;
if (this._Captured)
this.ReleaseMouseCapture();
e.Handled = true;
this._Selecting = false;
this._Captured = false;
}
OnMouseMove(e: Input.MouseEventArgs) {
if (!this._Selecting)
return;
e.Handled = true;
var cursor = this.$View.GetCursorFromPoint(e.GetPosition(this.$View));
this.$Proxy.adjustSelection(cursor);
}
OnTouchDown(e: Input.TouchEventArgs) {
super.OnTouchDown(e);
if (e.Handled)
return;
e.Handled = true;
this.Focus();
e.Device.Capture(this);
this._Selecting = true;
var pos = e.Device.GetTouchPoint(this.$View).Position;
var cursor = this.$View.GetCursorFromPoint(pos);
this.$Proxy.beginSelect(cursor);
}
OnTouchUp(e: Input.TouchEventArgs) {
super.OnTouchUp(e);
if (e.Handled)
return;
if (e.Device.Captured === this)
e.Device.ReleaseCapture(this);
e.Handled = true;
this._Selecting = false;
}
OnTouchMove(e: Input.TouchEventArgs) {
super.OnTouchMove(e);
if (!this._Selecting)
return;
e.Handled = true;
var pos = e.Device.GetTouchPoint(this.$View).Position;
var cursor = this.$View.GetCursorFromPoint(pos);
this.$Proxy.adjustSelection(cursor);
}
OnKeyDown(args: Input.KeyEventArgs) {
switch (args.Key) {
case Key.Shift: //shift
case Key.Ctrl: //ctrl
case Key.Alt: //alt
return;
}
var isReadOnly = this.IsReadOnly;
var handled = false;
var proxy = this.$Proxy;
proxy.begin();
switch (args.Key) {
case Key.Back:
if (isReadOnly)
break;
handled = this._KeyDownBackSpace(args.Modifiers);
break;
case Key.Delete:
if (isReadOnly)
break;
if (args.Modifiers.Shift) {
//Shift+Delete => Cut
handled = true;
} else {
handled = this._KeyDownDelete(args.Modifiers);
}
break;
case Key.Insert:
if (args.Modifiers.Shift) {
//Shift+Insert => Paste
handled = true;
} else if (args.Modifiers.Ctrl) {
//Ctrl+Insert => Copy
handled = true;
}
break;
case Key.PageDown:
handled = this._KeyDownPageDown(args.Modifiers);
break;
case Key.PageUp:
handled = this._KeyDownPageUp(args.Modifiers);
break;
case Key.Home:
handled = this._KeyDownHome(args.Modifiers);
break;
case Key.End:
handled = this._KeyDownEnd(args.Modifiers);
break;
case Key.Left:
handled = this._KeyDownLeft(args.Modifiers);
break;
case Key.Right:
handled = this._KeyDownRight(args.Modifiers);
break;
case Key.Down:
handled = this._KeyDownDown(args.Modifiers);
break;
case Key.Up:
handled = this._KeyDownUp(args.Modifiers);
break;
default:
if (args.Modifiers.Ctrl) {
switch (args.Key) {
case Key.A:
//Ctrl+A => Select All
handled = true;
proxy.selectAll();
break;
case Key.C:
//Ctrl+C => Copy
this.$Clipboard.CopyText(this.$Proxy.getSelectedText());
handled = true;
break;
case Key.X:
//Ctrl+X => Cut
if (isReadOnly)
break;
this.$Clipboard.CopyText(this.$Proxy.getSelectedText());
proxy.removeText(this.$Proxy.selAnchor, this.$Proxy.selCursor);
handled = true;
break;
case Key.V:
//Ctrl+V => Paste
if (isReadOnly)
break;
this.$Clipboard.GetTextContents((text) => proxy.paste(text));
handled = true;
break;
case Key.Y:
//Ctrl+Y => Redo
if (!isReadOnly) {
handled = true;
proxy.redo();
}
break;
case Key.Z:
//Ctrl+Z => Undo
if (!isReadOnly) {
handled = true;
proxy.undo();
}
break;
}
}
break;
}
if (handled) {
args.Handled = handled;
}
proxy.end();
if (!args.Handled && !isReadOnly)
this.PostOnKeyDown(args);
}
PostOnKeyDown(args: Input.KeyEventArgs) {
if (args.Handled)
return;
if (args.Modifiers.Alt || args.Modifiers.Ctrl)
return;
var proxy = this.$Proxy;
proxy.begin();
if (args.Key === Key.Enter) {
if (this.AcceptsReturn === true) {
proxy.enterText('\n');
args.Handled = true;
}
} else if (args.Char != null && !args.Modifiers.Ctrl && !args.Modifiers.Alt) {
proxy.enterText(args.Char);
args.Handled = true;
}
proxy.end();
}
private _KeyDownBackSpace(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Shift || modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
var start = 0;
var length = 0;
if (cursor !== anchor) {
length = Math.abs(cursor - anchor);
start = Math.min(anchor, cursor);
} else if (modifiers.Ctrl) {
start = this.$Advancer.CursorPrevWord(cursor);
length = cursor - start;
} else if (cursor > 0) {
start = this.$Advancer.CursorPrevChar(cursor);
length = cursor - start;
}
proxy.removeText(start, length);
return true;
}
private _KeyDownDelete(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Shift || modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
var start = 0;
var length = 0;
if (cursor !== anchor) {
length = Math.abs(cursor - anchor);
start = Math.min(anchor, cursor);
} else if (modifiers.Ctrl) {
//Ctrl+Delete => delete the word start at the cursor
length = this.$Advancer.CursorNextWord(cursor) - cursor;
start = cursor;
} else {
length = this.$Advancer.CursorNextChar(cursor) - cursor;
start = cursor;
}
return proxy.removeText(start, length);
}
private _KeyDownPageDown(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
cursor = this.$Advancer.CursorDown(cursor, true);
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
private _KeyDownPageUp(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
cursor = this.$Advancer.CursorUp(cursor, true);
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
private _KeyDownHome(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
if (modifiers.Ctrl) {
cursor = this.$Advancer.CursorBegin(cursor);
} else {
cursor = this.$Advancer.CursorLineBegin(cursor);
}
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
private _KeyDownEnd(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
if (modifiers.Ctrl) {
cursor = this.$Advancer.CursorEnd(cursor);
} else {
cursor = this.$Advancer.CursorLineEnd(cursor);
}
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
private _KeyDownLeft(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
if (modifiers.Ctrl) {
cursor = this.$Advancer.CursorPrevWord(cursor);
} else if (!modifiers.Shift && anchor !== cursor) {
cursor = Math.min(anchor, cursor);
} else {
cursor = this.$Advancer.CursorPrevChar(cursor);
}
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
private _KeyDownRight(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var anchor = proxy.selAnchor;
var cursor = proxy.selCursor;
if (modifiers.Ctrl) {
cursor = this.$Advancer.CursorNextWord(cursor);
} else if (!modifiers.Shift && anchor !== cursor) {
cursor = Math.max(anchor, cursor);
} else {
cursor = this.$Advancer.CursorNextChar(cursor);
}
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
private _KeyDownDown(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var cursor = this.$Advancer.CursorDown(proxy.selCursor, false);
var anchor = proxy.selAnchor;
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
private _KeyDownUp(modifiers: Input.IModifiersOn): boolean {
if (modifiers.Alt)
return false;
var proxy = this.$Proxy;
var cursor = this.$Advancer.CursorUp(proxy.selCursor, false);
var anchor = proxy.selAnchor;
if (!modifiers.Shift)
anchor = cursor;
return proxy.setAnchorCursor(anchor, cursor);
}
}
Fayde.RegisterType(TextBoxBase, Fayde.XMLNSINTERNAL);
module reactions {
DPReaction<Media.Brush>(TextBoxBase.CaretBrushProperty, (tbb: TextBoxBase, ov, nv) => {
tbb.$View.setCaretBrush(nv);
});
DPReaction<number>(TextBoxBase.SelectionStartProperty, (tbb: TextBoxBase, ov, nv) => {
tbb.$Proxy.setSelectionStart(nv);
tbb.$View.setSelectionStart(nv);
}, false);
DPReaction<number>(TextBoxBase.SelectionLengthProperty, (tbb: TextBoxBase, ov, nv) => {
tbb.$Proxy.setSelectionLength(nv);
tbb.$View.setSelectionLength(nv);
}, false);
DPReaction<Media.Brush>(TextBoxBase.SelectionBackgroundProperty, (tbb: TextBoxBase, ov, nv) => {
tbb.$View.setFontAttr("selectionBackground", nv);
tbb.XamlNode.LayoutUpdater.invalidate();
});
DPReaction<Media.Brush>(TextBoxBase.SelectionForegroundProperty, (tbb: TextBoxBase, ov, nv) => {
tbb.$View.setFontAttr("selectionForeground", nv);
tbb.XamlNode.LayoutUpdater.invalidate();
});
DPReaction<number>(TextBoxBase.MaxLengthProperty, (tbb: TextBoxBase, ov, nv) => {
tbb.$Proxy.maxLength = nv;
}, false);
}
function positiveIntValidator(dobj: DependencyObject, propd: DependencyProperty, value: any): boolean {
if (typeof value !== 'number')
return false;
return value >= 0;
}
} | the_stack |
import { ApiObject, ApiObjectMetadata, GroupVersionKind } from 'cdk8s';
import { Construct } from 'constructs';
/**
* Jenkins is the Schema for the jenkins API
*
* @schema Jenkins
*/
export class Jenkins extends ApiObject {
/**
* Returns the apiVersion and kind for "Jenkins"
*/
public static readonly GVK: GroupVersionKind = {
apiVersion: 'jenkins.io/v1alpha2',
kind: 'Jenkins',
}
/**
* Renders a Kubernetes manifest for "Jenkins".
*
* This can be used to inline resource manifests inside other objects (e.g. as templates).
*
* @param props initialization props
*/
public static manifest(props: JenkinsProps = {}): any {
return {
...Jenkins.GVK,
...toJson_JenkinsProps(props),
};
}
/**
* Defines a "Jenkins" API object
* @param scope the scope in which to define this object
* @param id a scope-local name for the object
* @param props initialization props
*/
public constructor(scope: Construct, id: string, props: JenkinsProps = {}) {
super(scope, id, {
...Jenkins.GVK,
...props,
});
}
/**
* Renders the object to Kubernetes JSON.
*/
public toJson(): any {
const resolved = super.toJson();
return {
...Jenkins.GVK,
...toJson_JenkinsProps(resolved),
};
}
}
/**
* Jenkins is the Schema for the jenkins API
*
* @schema Jenkins
*/
export interface JenkinsProps {
/**
* @schema Jenkins#metadata
*/
readonly metadata?: ApiObjectMetadata;
/**
* Spec defines the desired state of the Jenkins
*
* @schema Jenkins#spec
*/
readonly spec?: JenkinsSpec;
}
/**
* Converts an object of type 'JenkinsProps' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsProps(obj: JenkinsProps | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'metadata': obj.metadata,
'spec': toJson_JenkinsSpec(obj.spec),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Spec defines the desired state of the Jenkins
*
* @schema JenkinsSpec
*/
export interface JenkinsSpec {
/**
* Backup defines configuration of Jenkins backup More info: https://github.com/jenkinsci/kubernetes-operator/blob/master/docs/getting-started.md#configure-backup-and-restore
*
* @schema JenkinsSpec#backup
*/
readonly backup?: JenkinsSpecBackup;
/**
* ConfigurationAsCode defines configuration of Jenkins customization via Configuration as Code Jenkins plugin
*
* @schema JenkinsSpec#configurationAsCode
*/
readonly configurationAsCode?: JenkinsSpecConfigurationAsCode;
/**
* GroovyScripts defines configuration of Jenkins customization via groovy scripts
*
* @schema JenkinsSpec#groovyScripts
*/
readonly groovyScripts?: JenkinsSpecGroovyScripts;
/**
* JenkinsAPISettings defines configuration used by the operator to gain admin access to the Jenkins API
*
* @schema JenkinsSpec#jenkinsAPISettings
*/
readonly jenkinsApiSettings: JenkinsSpecJenkinsApiSettings;
/**
* Master represents Jenkins master pod properties and Jenkins plugins. Every single change here requires a pod restart.
*
* @schema JenkinsSpec#master
*/
readonly master: JenkinsSpecMaster;
/**
* Notifications defines list of a services which are used to inform about Jenkins status Can be used to integrate chat services like Slack, Microsoft Teams or Mailgun
*
* @schema JenkinsSpec#notifications
*/
readonly notifications?: JenkinsSpecNotifications[];
/**
* Backup defines configuration of Jenkins backup restore More info: https://github.com/jenkinsci/kubernetes-operator/blob/master/docs/getting-started.md#configure-backup-and-restore
*
* @schema JenkinsSpec#restore
*/
readonly restore?: JenkinsSpecRestore;
/**
* Roles defines list of extra RBAC roles for the Jenkins Master pod service account
*
* @schema JenkinsSpec#roles
*/
readonly roles?: JenkinsSpecRoles[];
/**
* SeedJobs defines list of Jenkins Seed Job configurations More info: https://github.com/jenkinsci/kubernetes-operator/blob/master/docs/getting-started.md#configure-seed-jobs-and-pipelines
*
* @schema JenkinsSpec#seedJobs
*/
readonly seedJobs?: JenkinsSpecSeedJobs[];
/**
* Service is Kubernetes service of Jenkins master HTTP pod Defaults to : port: 8080 type: ClusterIP
*
* @default port: 8080 type: ClusterIP
* @schema JenkinsSpec#service
*/
readonly service?: JenkinsSpecService;
/**
* ServiceAccount defines Jenkins master service account attributes
*
* @schema JenkinsSpec#serviceAccount
*/
readonly serviceAccount?: JenkinsSpecServiceAccount;
/**
* Service is Kubernetes service of Jenkins slave pods Defaults to : port: 50000 type: ClusterIP
*
* @default port: 50000 type: ClusterIP
* @schema JenkinsSpec#slaveService
*/
readonly slaveService?: JenkinsSpecSlaveService;
}
/**
* Converts an object of type 'JenkinsSpec' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpec(obj: JenkinsSpec | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'backup': toJson_JenkinsSpecBackup(obj.backup),
'configurationAsCode': toJson_JenkinsSpecConfigurationAsCode(obj.configurationAsCode),
'groovyScripts': toJson_JenkinsSpecGroovyScripts(obj.groovyScripts),
'jenkinsAPISettings': toJson_JenkinsSpecJenkinsApiSettings(obj.jenkinsApiSettings),
'master': toJson_JenkinsSpecMaster(obj.master),
'notifications': obj.notifications?.map(y => toJson_JenkinsSpecNotifications(y)),
'restore': toJson_JenkinsSpecRestore(obj.restore),
'roles': obj.roles?.map(y => toJson_JenkinsSpecRoles(y)),
'seedJobs': obj.seedJobs?.map(y => toJson_JenkinsSpecSeedJobs(y)),
'service': toJson_JenkinsSpecService(obj.service),
'serviceAccount': toJson_JenkinsSpecServiceAccount(obj.serviceAccount),
'slaveService': toJson_JenkinsSpecSlaveService(obj.slaveService),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Backup defines configuration of Jenkins backup More info: https://github.com/jenkinsci/kubernetes-operator/blob/master/docs/getting-started.md#configure-backup-and-restore
*
* @schema JenkinsSpecBackup
*/
export interface JenkinsSpecBackup {
/**
* Action defines action which performs backup in backup container sidecar
*
* @schema JenkinsSpecBackup#action
*/
readonly action: JenkinsSpecBackupAction;
/**
* ContainerName is the container name responsible for backup operation
*
* @schema JenkinsSpecBackup#containerName
*/
readonly containerName: string;
/**
* Interval tells how often make backup in seconds Defaults to 30.
*
* @default 30.
* @schema JenkinsSpecBackup#interval
*/
readonly interval: number;
/**
* MakeBackupBeforePodDeletion tells operator to make backup before Jenkins master pod deletion
*
* @schema JenkinsSpecBackup#makeBackupBeforePodDeletion
*/
readonly makeBackupBeforePodDeletion: boolean;
}
/**
* Converts an object of type 'JenkinsSpecBackup' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecBackup(obj: JenkinsSpecBackup | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'action': toJson_JenkinsSpecBackupAction(obj.action),
'containerName': obj.containerName,
'interval': obj.interval,
'makeBackupBeforePodDeletion': obj.makeBackupBeforePodDeletion,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ConfigurationAsCode defines configuration of Jenkins customization via Configuration as Code Jenkins plugin
*
* @schema JenkinsSpecConfigurationAsCode
*/
export interface JenkinsSpecConfigurationAsCode {
/**
* @schema JenkinsSpecConfigurationAsCode#configurations
*/
readonly configurations: JenkinsSpecConfigurationAsCodeConfigurations[];
/**
* SecretRef is reference to Kubernetes secret
*
* @schema JenkinsSpecConfigurationAsCode#secret
*/
readonly secret: JenkinsSpecConfigurationAsCodeSecret;
}
/**
* Converts an object of type 'JenkinsSpecConfigurationAsCode' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecConfigurationAsCode(obj: JenkinsSpecConfigurationAsCode | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'configurations': obj.configurations?.map(y => toJson_JenkinsSpecConfigurationAsCodeConfigurations(y)),
'secret': toJson_JenkinsSpecConfigurationAsCodeSecret(obj.secret),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* GroovyScripts defines configuration of Jenkins customization via groovy scripts
*
* @schema JenkinsSpecGroovyScripts
*/
export interface JenkinsSpecGroovyScripts {
/**
* @schema JenkinsSpecGroovyScripts#configurations
*/
readonly configurations: JenkinsSpecGroovyScriptsConfigurations[];
/**
* SecretRef is reference to Kubernetes secret
*
* @schema JenkinsSpecGroovyScripts#secret
*/
readonly secret: JenkinsSpecGroovyScriptsSecret;
}
/**
* Converts an object of type 'JenkinsSpecGroovyScripts' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecGroovyScripts(obj: JenkinsSpecGroovyScripts | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'configurations': obj.configurations?.map(y => toJson_JenkinsSpecGroovyScriptsConfigurations(y)),
'secret': toJson_JenkinsSpecGroovyScriptsSecret(obj.secret),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* JenkinsAPISettings defines configuration used by the operator to gain admin access to the Jenkins API
*
* @schema JenkinsSpecJenkinsApiSettings
*/
export interface JenkinsSpecJenkinsApiSettings {
/**
* AuthorizationStrategy defines authorization strategy of the operator for the Jenkins API
*
* @schema JenkinsSpecJenkinsApiSettings#authorizationStrategy
*/
readonly authorizationStrategy: string;
}
/**
* Converts an object of type 'JenkinsSpecJenkinsApiSettings' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecJenkinsApiSettings(obj: JenkinsSpecJenkinsApiSettings | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'authorizationStrategy': obj.authorizationStrategy,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Master represents Jenkins master pod properties and Jenkins plugins. Every single change here requires a pod restart.
*
* @schema JenkinsSpecMaster
*/
export interface JenkinsSpecMaster {
/**
* Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations
*
* @schema JenkinsSpecMaster#annotations
*/
readonly annotations?: { [key: string]: string };
/**
* BasePlugins contains plugins required by operator Defaults to : - name: kubernetes version: 1.15.7 - name: workflow-job version: "2.32" - name: workflow-aggregator version: "2.6" - name: git version: 3.10.0 - name: job-dsl version: "1.74" - name: configuration-as-code version: "1.19" - name: configuration-as-code-support version: "1.19" - name: kubernetes-credentials-provider version: 0.12.1
*
* @default name: kubernetes version: 1.15.7 - name: workflow-job version: "2.32" - name: workflow-aggregator version: "2.6" - name: git version: 3.10.0 - name: job-dsl version: "1.74" - name: configuration-as-code version: "1.19" - name: configuration-as-code-support version: "1.19" - name: kubernetes-credentials-provider version: 0.12.1
* @schema JenkinsSpecMaster#basePlugins
*/
readonly basePlugins?: JenkinsSpecMasterBasePlugins[];
/**
* List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Defaults to: - image: jenkins/jenkins:lts imagePullPolicy: Always livenessProbe: failureThreshold: 12 httpGet: path: /login port: http scheme: HTTP initialDelaySeconds: 80 periodSeconds: 10 successThreshold: 1 timeoutSeconds: 5 name: jenkins-master readinessProbe: failureThreshold: 3 httpGet: path: /login port: http scheme: HTTP initialDelaySeconds: 30 periodSeconds: 10 successThreshold: 1 timeoutSeconds: 1 resources: limits: cpu: 1500m memory: 3Gi requests: cpu: "1" memory: 600Mi
*
* @default image: jenkins/jenkins:lts imagePullPolicy: Always livenessProbe: failureThreshold: 12 httpGet: path: /login port: http scheme: HTTP initialDelaySeconds: 80 periodSeconds: 10 successThreshold: 1 timeoutSeconds: 5 name: jenkins-master readinessProbe: failureThreshold: 3 httpGet: path: /login port: http scheme: HTTP initialDelaySeconds: 30 periodSeconds: 10 successThreshold: 1 timeoutSeconds: 1 resources: limits: cpu: 1500m memory: 3Gi requests: cpu: "1" memory: 600Mi
* @schema JenkinsSpecMaster#containers
*/
readonly containers?: JenkinsSpecMasterContainers[];
/**
* DisableCSRFProtection allows you to toggle CSRF Protection on Jenkins
*
* @schema JenkinsSpecMaster#disableCSRFProtection
*/
readonly disableCsrfProtection: boolean;
/**
* ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod
*
* @schema JenkinsSpecMaster#imagePullSecrets
*/
readonly imagePullSecrets?: JenkinsSpecMasterImagePullSecrets[];
/**
* Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels
*
* @schema JenkinsSpecMaster#labels
*/
readonly labels?: { [key: string]: string };
/**
* Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations Deprecated: will be removed in the future, please use Annotations(annotations)
*
* @schema JenkinsSpecMaster#masterAnnotations
*/
readonly masterAnnotations?: { [key: string]: string };
/**
* NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
*
* @schema JenkinsSpecMaster#nodeSelector
*/
readonly nodeSelector?: { [key: string]: string };
/**
* Plugins contains plugins required by user
*
* @schema JenkinsSpecMaster#plugins
*/
readonly plugins?: JenkinsSpecMasterPlugins[];
/**
* SecurityContext that applies to all the containers of the Jenkins Master. As per kubernetes specification, it can be overridden for each container individually. Defaults to: runAsUser: 1000 fsGroup: 1000
*
* @default runAsUser: 1000 fsGroup: 1000
* @schema JenkinsSpecMaster#securityContext
*/
readonly securityContext?: JenkinsSpecMasterSecurityContext;
/**
* If specified, the pod's tolerations.
*
* @schema JenkinsSpecMaster#tolerations
*/
readonly tolerations?: JenkinsSpecMasterTolerations[];
/**
* List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes
*
* @schema JenkinsSpecMaster#volumes
*/
readonly volumes?: JenkinsSpecMasterVolumes[];
}
/**
* Converts an object of type 'JenkinsSpecMaster' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMaster(obj: JenkinsSpecMaster | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'annotations': ((obj.annotations) === undefined) ? undefined : (Object.entries(obj.annotations).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'basePlugins': obj.basePlugins?.map(y => toJson_JenkinsSpecMasterBasePlugins(y)),
'containers': obj.containers?.map(y => toJson_JenkinsSpecMasterContainers(y)),
'disableCSRFProtection': obj.disableCsrfProtection,
'imagePullSecrets': obj.imagePullSecrets?.map(y => toJson_JenkinsSpecMasterImagePullSecrets(y)),
'labels': ((obj.labels) === undefined) ? undefined : (Object.entries(obj.labels).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'masterAnnotations': ((obj.masterAnnotations) === undefined) ? undefined : (Object.entries(obj.masterAnnotations).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'nodeSelector': ((obj.nodeSelector) === undefined) ? undefined : (Object.entries(obj.nodeSelector).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'plugins': obj.plugins?.map(y => toJson_JenkinsSpecMasterPlugins(y)),
'securityContext': toJson_JenkinsSpecMasterSecurityContext(obj.securityContext),
'tolerations': obj.tolerations?.map(y => toJson_JenkinsSpecMasterTolerations(y)),
'volumes': obj.volumes?.map(y => toJson_JenkinsSpecMasterVolumes(y)),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Notification is a service configuration used to send notifications about Jenkins status
*
* @schema JenkinsSpecNotifications
*/
export interface JenkinsSpecNotifications {
/**
* NotificationLevel defines the level of a Notification
*
* @schema JenkinsSpecNotifications#level
*/
readonly level: string;
/**
* Mailgun is handler for Mailgun email service notification channel
*
* @schema JenkinsSpecNotifications#mailgun
*/
readonly mailgun?: JenkinsSpecNotificationsMailgun;
/**
* @schema JenkinsSpecNotifications#name
*/
readonly name: string;
/**
* Slack is handler for Slack notification channel
*
* @schema JenkinsSpecNotifications#slack
*/
readonly slack?: JenkinsSpecNotificationsSlack;
/**
* SMTP is handler for sending emails via this protocol
*
* @schema JenkinsSpecNotifications#smtp
*/
readonly smtp?: JenkinsSpecNotificationsSmtp;
/**
* MicrosoftTeams is handler for Microsoft MicrosoftTeams notification channel
*
* @schema JenkinsSpecNotifications#teams
*/
readonly teams?: JenkinsSpecNotificationsTeams;
/**
* @schema JenkinsSpecNotifications#verbose
*/
readonly verbose: boolean;
}
/**
* Converts an object of type 'JenkinsSpecNotifications' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotifications(obj: JenkinsSpecNotifications | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'level': obj.level,
'mailgun': toJson_JenkinsSpecNotificationsMailgun(obj.mailgun),
'name': obj.name,
'slack': toJson_JenkinsSpecNotificationsSlack(obj.slack),
'smtp': toJson_JenkinsSpecNotificationsSmtp(obj.smtp),
'teams': toJson_JenkinsSpecNotificationsTeams(obj.teams),
'verbose': obj.verbose,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Backup defines configuration of Jenkins backup restore More info: https://github.com/jenkinsci/kubernetes-operator/blob/master/docs/getting-started.md#configure-backup-and-restore
*
* @schema JenkinsSpecRestore
*/
export interface JenkinsSpecRestore {
/**
* Action defines action which performs restore backup in restore container sidecar
*
* @schema JenkinsSpecRestore#action
*/
readonly action: JenkinsSpecRestoreAction;
/**
* ContainerName is the container name responsible for restore backup operation
*
* @schema JenkinsSpecRestore#containerName
*/
readonly containerName: string;
/**
* RecoveryOnce if want to restore specific backup set this field and then Jenkins will be restarted and desired backup will be restored
*
* @schema JenkinsSpecRestore#recoveryOnce
*/
readonly recoveryOnce?: number;
}
/**
* Converts an object of type 'JenkinsSpecRestore' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecRestore(obj: JenkinsSpecRestore | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'action': toJson_JenkinsSpecRestoreAction(obj.action),
'containerName': obj.containerName,
'recoveryOnce': obj.recoveryOnce,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* RoleRef contains information that points to the role being used
*
* @schema JenkinsSpecRoles
*/
export interface JenkinsSpecRoles {
/**
* APIGroup is the group for the resource being referenced
*
* @schema JenkinsSpecRoles#apiGroup
*/
readonly apiGroup: string;
/**
* Kind is the type of resource being referenced
*
* @schema JenkinsSpecRoles#kind
*/
readonly kind: string;
/**
* Name is the name of resource being referenced
*
* @schema JenkinsSpecRoles#name
*/
readonly name: string;
}
/**
* Converts an object of type 'JenkinsSpecRoles' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecRoles(obj: JenkinsSpecRoles | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'apiGroup': obj.apiGroup,
'kind': obj.kind,
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SeedJob defines configuration for seed job More info: https://github.com/jenkinsci/kubernetes-operator/blob/master/docs/getting-started.md#configure-seed-jobs-and-pipelines
*
* @schema JenkinsSpecSeedJobs
*/
export interface JenkinsSpecSeedJobs {
/**
* AdditionalClasspath is setting for Job DSL API plugin to set Additional Classpath
*
* @schema JenkinsSpecSeedJobs#additionalClasspath
*/
readonly additionalClasspath?: string;
/**
* BitbucketPushTrigger is used for Bitbucket web hooks
*
* @schema JenkinsSpecSeedJobs#bitbucketPushTrigger
*/
readonly bitbucketPushTrigger?: boolean;
/**
* BuildPeriodically is setting for scheduled trigger
*
* @schema JenkinsSpecSeedJobs#buildPeriodically
*/
readonly buildPeriodically?: string;
/**
* CredentialID is the Kubernetes secret name which stores repository access credentials
*
* @schema JenkinsSpecSeedJobs#credentialID
*/
readonly credentialId?: string;
/**
* JenkinsCredentialType is the https://jenkinsci.github.io/kubernetes-credentials-provider-plugin/ credential type
*
* @schema JenkinsSpecSeedJobs#credentialType
*/
readonly credentialType?: string;
/**
* Description is the description of the seed job
*
* @schema JenkinsSpecSeedJobs#description
*/
readonly description?: string;
/**
* FailOnMissingPlugin is setting for Job DSL API plugin that fails job if required plugin is missing
*
* @schema JenkinsSpecSeedJobs#failOnMissingPlugin
*/
readonly failOnMissingPlugin?: boolean;
/**
* GitHubPushTrigger is used for GitHub web hooks
*
* @schema JenkinsSpecSeedJobs#githubPushTrigger
*/
readonly githubPushTrigger?: boolean;
/**
* ID is the unique seed job name
*
* @schema JenkinsSpecSeedJobs#id
*/
readonly id?: string;
/**
* IgnoreMissingFiles is setting for Job DSL API plugin to ignore files that miss
*
* @schema JenkinsSpecSeedJobs#ignoreMissingFiles
*/
readonly ignoreMissingFiles?: boolean;
/**
* PollSCM is setting for polling changes in SCM
*
* @schema JenkinsSpecSeedJobs#pollSCM
*/
readonly pollScm?: string;
/**
* RepositoryBranch is the repository branch where are seed job definitions
*
* @schema JenkinsSpecSeedJobs#repositoryBranch
*/
readonly repositoryBranch?: string;
/**
* RepositoryURL is the repository access URL. Can be SSH or HTTPS.
*
* @schema JenkinsSpecSeedJobs#repositoryUrl
*/
readonly repositoryUrl?: string;
/**
* Targets is the repository path where are seed job definitions
*
* @schema JenkinsSpecSeedJobs#targets
*/
readonly targets?: string;
/**
* UnstableOnDeprecation is setting for Job DSL API plugin that sets build status as unstable if build using deprecated features
*
* @schema JenkinsSpecSeedJobs#unstableOnDeprecation
*/
readonly unstableOnDeprecation?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecSeedJobs' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecSeedJobs(obj: JenkinsSpecSeedJobs | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'additionalClasspath': obj.additionalClasspath,
'bitbucketPushTrigger': obj.bitbucketPushTrigger,
'buildPeriodically': obj.buildPeriodically,
'credentialID': obj.credentialId,
'credentialType': obj.credentialType,
'description': obj.description,
'failOnMissingPlugin': obj.failOnMissingPlugin,
'githubPushTrigger': obj.githubPushTrigger,
'id': obj.id,
'ignoreMissingFiles': obj.ignoreMissingFiles,
'pollSCM': obj.pollScm,
'repositoryBranch': obj.repositoryBranch,
'repositoryUrl': obj.repositoryUrl,
'targets': obj.targets,
'unstableOnDeprecation': obj.unstableOnDeprecation,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Service is Kubernetes service of Jenkins master HTTP pod Defaults to : port: 8080 type: ClusterIP
*
* @default port: 8080 type: ClusterIP
* @schema JenkinsSpecService
*/
export interface JenkinsSpecService {
/**
* Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations
*
* @schema JenkinsSpecService#annotations
*/
readonly annotations?: { [key: string]: string };
/**
* Route service traffic to pods with label keys and values matching this selector. If empty or not present, the service is assumed to have an external process managing its endpoints, which Kubernetes will not modify. Only applies to types ClusterIP, NodePort, and LoadBalancer. Ignored if type is ExternalName. More info: https://kubernetes.io/docs/concepts/services-networking/service/
*
* @schema JenkinsSpecService#labels
*/
readonly labels?: { [key: string]: string };
/**
* Only applies to Service Type: LoadBalancer LoadBalancer will get created with the IP specified in this field. This feature depends on whether the underlying cloud-provider supports specifying the loadBalancerIP when a load balancer is created. This field will be ignored if the cloud-provider does not support the feature.
*
* @schema JenkinsSpecService#loadBalancerIP
*/
readonly loadBalancerIp?: string;
/**
* If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature." More info: https://kubernetes.io/docs/tasks/access-application-cluster/configure-cloud-provider-firewall/
*
* @schema JenkinsSpecService#loadBalancerSourceRanges
*/
readonly loadBalancerSourceRanges?: string[];
/**
* The port on each node on which this service is exposed when type=NodePort or LoadBalancer. Usually assigned by the system. If specified, it will be allocated to the service if unused or else creation of the service will fail. Default is to auto-allocate a port if the ServiceType of this Service requires one. More info: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport
*
* @default to auto-allocate a port if the ServiceType of this Service requires one. More info: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport
* @schema JenkinsSpecService#nodePort
*/
readonly nodePort?: number;
/**
* The port that are exposed by this service. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies
*
* @schema JenkinsSpecService#port
*/
readonly port?: number;
/**
* Type determines how the Service is exposed. Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and LoadBalancer. "ExternalName" maps to the specified externalName. "ClusterIP" allocates a cluster-internal IP address for load-balancing to endpoints. Endpoints are determined by the selector or if that is not specified, by manual construction of an Endpoints object. If clusterIP is "None", no virtual IP is allocated and the endpoints are published as a set of endpoints rather than a stable IP. "NodePort" builds on ClusterIP and allocates a port on every node which routes to the clusterIP. "LoadBalancer" builds on NodePort and creates an external load-balancer (if supported in the current cloud) which routes to the clusterIP. More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types
*
* @default ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and LoadBalancer. "ExternalName" maps to the specified externalName. "ClusterIP" allocates a cluster-internal IP address for load-balancing to endpoints. Endpoints are determined by the selector or if that is not specified, by manual construction of an Endpoints object. If clusterIP is "None", no virtual IP is allocated and the endpoints are published as a set of endpoints rather than a stable IP. "NodePort" builds on ClusterIP and allocates a port on every node which routes to the clusterIP. "LoadBalancer" builds on NodePort and creates an external load-balancer (if supported in the current cloud) which routes to the clusterIP. More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types
* @schema JenkinsSpecService#type
*/
readonly type?: string;
}
/**
* Converts an object of type 'JenkinsSpecService' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecService(obj: JenkinsSpecService | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'annotations': ((obj.annotations) === undefined) ? undefined : (Object.entries(obj.annotations).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'labels': ((obj.labels) === undefined) ? undefined : (Object.entries(obj.labels).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'loadBalancerIP': obj.loadBalancerIp,
'loadBalancerSourceRanges': obj.loadBalancerSourceRanges?.map(y => y),
'nodePort': obj.nodePort,
'port': obj.port,
'type': obj.type,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ServiceAccount defines Jenkins master service account attributes
*
* @schema JenkinsSpecServiceAccount
*/
export interface JenkinsSpecServiceAccount {
/**
* Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations
*
* @schema JenkinsSpecServiceAccount#annotations
*/
readonly annotations?: { [key: string]: string };
}
/**
* Converts an object of type 'JenkinsSpecServiceAccount' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecServiceAccount(obj: JenkinsSpecServiceAccount | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'annotations': ((obj.annotations) === undefined) ? undefined : (Object.entries(obj.annotations).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Service is Kubernetes service of Jenkins slave pods Defaults to : port: 50000 type: ClusterIP
*
* @default port: 50000 type: ClusterIP
* @schema JenkinsSpecSlaveService
*/
export interface JenkinsSpecSlaveService {
/**
* Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations
*
* @schema JenkinsSpecSlaveService#annotations
*/
readonly annotations?: { [key: string]: string };
/**
* Route service traffic to pods with label keys and values matching this selector. If empty or not present, the service is assumed to have an external process managing its endpoints, which Kubernetes will not modify. Only applies to types ClusterIP, NodePort, and LoadBalancer. Ignored if type is ExternalName. More info: https://kubernetes.io/docs/concepts/services-networking/service/
*
* @schema JenkinsSpecSlaveService#labels
*/
readonly labels?: { [key: string]: string };
/**
* Only applies to Service Type: LoadBalancer LoadBalancer will get created with the IP specified in this field. This feature depends on whether the underlying cloud-provider supports specifying the loadBalancerIP when a load balancer is created. This field will be ignored if the cloud-provider does not support the feature.
*
* @schema JenkinsSpecSlaveService#loadBalancerIP
*/
readonly loadBalancerIp?: string;
/**
* If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature." More info: https://kubernetes.io/docs/tasks/access-application-cluster/configure-cloud-provider-firewall/
*
* @schema JenkinsSpecSlaveService#loadBalancerSourceRanges
*/
readonly loadBalancerSourceRanges?: string[];
/**
* The port on each node on which this service is exposed when type=NodePort or LoadBalancer. Usually assigned by the system. If specified, it will be allocated to the service if unused or else creation of the service will fail. Default is to auto-allocate a port if the ServiceType of this Service requires one. More info: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport
*
* @default to auto-allocate a port if the ServiceType of this Service requires one. More info: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport
* @schema JenkinsSpecSlaveService#nodePort
*/
readonly nodePort?: number;
/**
* The port that are exposed by this service. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies
*
* @schema JenkinsSpecSlaveService#port
*/
readonly port?: number;
/**
* Type determines how the Service is exposed. Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and LoadBalancer. "ExternalName" maps to the specified externalName. "ClusterIP" allocates a cluster-internal IP address for load-balancing to endpoints. Endpoints are determined by the selector or if that is not specified, by manual construction of an Endpoints object. If clusterIP is "None", no virtual IP is allocated and the endpoints are published as a set of endpoints rather than a stable IP. "NodePort" builds on ClusterIP and allocates a port on every node which routes to the clusterIP. "LoadBalancer" builds on NodePort and creates an external load-balancer (if supported in the current cloud) which routes to the clusterIP. More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types
*
* @default ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and LoadBalancer. "ExternalName" maps to the specified externalName. "ClusterIP" allocates a cluster-internal IP address for load-balancing to endpoints. Endpoints are determined by the selector or if that is not specified, by manual construction of an Endpoints object. If clusterIP is "None", no virtual IP is allocated and the endpoints are published as a set of endpoints rather than a stable IP. "NodePort" builds on ClusterIP and allocates a port on every node which routes to the clusterIP. "LoadBalancer" builds on NodePort and creates an external load-balancer (if supported in the current cloud) which routes to the clusterIP. More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types
* @schema JenkinsSpecSlaveService#type
*/
readonly type?: string;
}
/**
* Converts an object of type 'JenkinsSpecSlaveService' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecSlaveService(obj: JenkinsSpecSlaveService | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'annotations': ((obj.annotations) === undefined) ? undefined : (Object.entries(obj.annotations).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'labels': ((obj.labels) === undefined) ? undefined : (Object.entries(obj.labels).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'loadBalancerIP': obj.loadBalancerIp,
'loadBalancerSourceRanges': obj.loadBalancerSourceRanges?.map(y => y),
'nodePort': obj.nodePort,
'port': obj.port,
'type': obj.type,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Action defines action which performs backup in backup container sidecar
*
* @schema JenkinsSpecBackupAction
*/
export interface JenkinsSpecBackupAction {
/**
* Exec specifies the action to take.
*
* @schema JenkinsSpecBackupAction#exec
*/
readonly exec?: JenkinsSpecBackupActionExec;
}
/**
* Converts an object of type 'JenkinsSpecBackupAction' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecBackupAction(obj: JenkinsSpecBackupAction | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'exec': toJson_JenkinsSpecBackupActionExec(obj.exec),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ConfigMapRef is reference to Kubernetes ConfigMap
*
* @schema JenkinsSpecConfigurationAsCodeConfigurations
*/
export interface JenkinsSpecConfigurationAsCodeConfigurations {
/**
* @schema JenkinsSpecConfigurationAsCodeConfigurations#name
*/
readonly name: string;
}
/**
* Converts an object of type 'JenkinsSpecConfigurationAsCodeConfigurations' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecConfigurationAsCodeConfigurations(obj: JenkinsSpecConfigurationAsCodeConfigurations | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretRef is reference to Kubernetes secret
*
* @schema JenkinsSpecConfigurationAsCodeSecret
*/
export interface JenkinsSpecConfigurationAsCodeSecret {
/**
* @schema JenkinsSpecConfigurationAsCodeSecret#name
*/
readonly name: string;
}
/**
* Converts an object of type 'JenkinsSpecConfigurationAsCodeSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecConfigurationAsCodeSecret(obj: JenkinsSpecConfigurationAsCodeSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ConfigMapRef is reference to Kubernetes ConfigMap
*
* @schema JenkinsSpecGroovyScriptsConfigurations
*/
export interface JenkinsSpecGroovyScriptsConfigurations {
/**
* @schema JenkinsSpecGroovyScriptsConfigurations#name
*/
readonly name: string;
}
/**
* Converts an object of type 'JenkinsSpecGroovyScriptsConfigurations' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecGroovyScriptsConfigurations(obj: JenkinsSpecGroovyScriptsConfigurations | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretRef is reference to Kubernetes secret
*
* @schema JenkinsSpecGroovyScriptsSecret
*/
export interface JenkinsSpecGroovyScriptsSecret {
/**
* @schema JenkinsSpecGroovyScriptsSecret#name
*/
readonly name: string;
}
/**
* Converts an object of type 'JenkinsSpecGroovyScriptsSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecGroovyScriptsSecret(obj: JenkinsSpecGroovyScriptsSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Plugin defines Jenkins plugin
*
* @schema JenkinsSpecMasterBasePlugins
*/
export interface JenkinsSpecMasterBasePlugins {
/**
* Name is the name of Jenkins plugin
*
* @schema JenkinsSpecMasterBasePlugins#name
*/
readonly name: string;
/**
* Version is the version of Jenkins plugin
*
* @schema JenkinsSpecMasterBasePlugins#version
*/
readonly version: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterBasePlugins' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterBasePlugins(obj: JenkinsSpecMasterBasePlugins | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'version': obj.version,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Container defines Kubernetes container attributes
*
* @schema JenkinsSpecMasterContainers
*/
export interface JenkinsSpecMasterContainers {
/**
* Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
*
* @schema JenkinsSpecMasterContainers#args
*/
readonly args?: string[];
/**
* Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
*
* @schema JenkinsSpecMasterContainers#command
*/
readonly command?: string[];
/**
* List of environment variables to set in the container.
*
* @schema JenkinsSpecMasterContainers#env
*/
readonly env?: JenkinsSpecMasterContainersEnv[];
/**
* List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence.
*
* @schema JenkinsSpecMasterContainers#envFrom
*/
readonly envFrom?: JenkinsSpecMasterContainersEnvFrom[];
/**
* Docker image name. More info: https://kubernetes.io/docs/concepts/containers/images
*
* @schema JenkinsSpecMasterContainers#image
*/
readonly image: string;
/**
* Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always.
*
* @default Always.
* @schema JenkinsSpecMasterContainers#imagePullPolicy
*/
readonly imagePullPolicy: string;
/**
* Actions that the management system should take in response to container lifecycle events.
*
* @schema JenkinsSpecMasterContainers#lifecycle
*/
readonly lifecycle?: JenkinsSpecMasterContainersLifecycle;
/**
* Periodic probe of container liveness. Container will be restarted if the probe fails.
*
* @schema JenkinsSpecMasterContainers#livenessProbe
*/
readonly livenessProbe?: JenkinsSpecMasterContainersLivenessProbe;
/**
* Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL).
*
* @schema JenkinsSpecMasterContainers#name
*/
readonly name: string;
/**
* List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network.
*
* @schema JenkinsSpecMasterContainers#ports
*/
readonly ports?: JenkinsSpecMasterContainersPorts[];
/**
* Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails.
*
* @schema JenkinsSpecMasterContainers#readinessProbe
*/
readonly readinessProbe?: JenkinsSpecMasterContainersReadinessProbe;
/**
* Compute Resources required by this container. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/
*
* @schema JenkinsSpecMasterContainers#resources
*/
readonly resources: JenkinsSpecMasterContainersResources;
/**
* Security options the pod should run with. More info: https://kubernetes.io/docs/concepts/policy/security-context/ More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
*
* @schema JenkinsSpecMasterContainers#securityContext
*/
readonly securityContext?: JenkinsSpecMasterContainersSecurityContext;
/**
* Pod volumes to mount into the container's filesystem.
*
* @schema JenkinsSpecMasterContainers#volumeMounts
*/
readonly volumeMounts?: JenkinsSpecMasterContainersVolumeMounts[];
/**
* Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image.
*
* @schema JenkinsSpecMasterContainers#workingDir
*/
readonly workingDir?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainers' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainers(obj: JenkinsSpecMasterContainers | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'args': obj.args?.map(y => y),
'command': obj.command?.map(y => y),
'env': obj.env?.map(y => toJson_JenkinsSpecMasterContainersEnv(y)),
'envFrom': obj.envFrom?.map(y => toJson_JenkinsSpecMasterContainersEnvFrom(y)),
'image': obj.image,
'imagePullPolicy': obj.imagePullPolicy,
'lifecycle': toJson_JenkinsSpecMasterContainersLifecycle(obj.lifecycle),
'livenessProbe': toJson_JenkinsSpecMasterContainersLivenessProbe(obj.livenessProbe),
'name': obj.name,
'ports': obj.ports?.map(y => toJson_JenkinsSpecMasterContainersPorts(y)),
'readinessProbe': toJson_JenkinsSpecMasterContainersReadinessProbe(obj.readinessProbe),
'resources': toJson_JenkinsSpecMasterContainersResources(obj.resources),
'securityContext': toJson_JenkinsSpecMasterContainersSecurityContext(obj.securityContext),
'volumeMounts': obj.volumeMounts?.map(y => toJson_JenkinsSpecMasterContainersVolumeMounts(y)),
'workingDir': obj.workingDir,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace.
*
* @schema JenkinsSpecMasterImagePullSecrets
*/
export interface JenkinsSpecMasterImagePullSecrets {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterImagePullSecrets#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterImagePullSecrets' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterImagePullSecrets(obj: JenkinsSpecMasterImagePullSecrets | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Plugin defines Jenkins plugin
*
* @schema JenkinsSpecMasterPlugins
*/
export interface JenkinsSpecMasterPlugins {
/**
* Name is the name of Jenkins plugin
*
* @schema JenkinsSpecMasterPlugins#name
*/
readonly name: string;
/**
* Version is the version of Jenkins plugin
*
* @schema JenkinsSpecMasterPlugins#version
*/
readonly version: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterPlugins' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterPlugins(obj: JenkinsSpecMasterPlugins | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'version': obj.version,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecurityContext that applies to all the containers of the Jenkins Master. As per kubernetes specification, it can be overridden for each container individually. Defaults to: runAsUser: 1000 fsGroup: 1000
*
* @default runAsUser: 1000 fsGroup: 1000
* @schema JenkinsSpecMasterSecurityContext
*/
export interface JenkinsSpecMasterSecurityContext {
/**
* A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod:
* 1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw----
* If unset, the Kubelet will not modify the ownership and permissions of any volume.
*
* @schema JenkinsSpecMasterSecurityContext#fsGroup
*/
readonly fsGroup?: number;
/**
* The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
*
* @schema JenkinsSpecMasterSecurityContext#runAsGroup
*/
readonly runAsGroup?: number;
/**
* Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterSecurityContext#runAsNonRoot
*/
readonly runAsNonRoot?: boolean;
/**
* The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
*
* @default user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
* @schema JenkinsSpecMasterSecurityContext#runAsUser
*/
readonly runAsUser?: number;
/**
* The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
*
* @schema JenkinsSpecMasterSecurityContext#seLinuxOptions
*/
readonly seLinuxOptions?: JenkinsSpecMasterSecurityContextSeLinuxOptions;
/**
* A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container.
*
* @schema JenkinsSpecMasterSecurityContext#supplementalGroups
*/
readonly supplementalGroups?: number[];
/**
* Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch.
*
* @schema JenkinsSpecMasterSecurityContext#sysctls
*/
readonly sysctls?: JenkinsSpecMasterSecurityContextSysctls[];
/**
* The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterSecurityContext#windowsOptions
*/
readonly windowsOptions?: JenkinsSpecMasterSecurityContextWindowsOptions;
}
/**
* Converts an object of type 'JenkinsSpecMasterSecurityContext' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterSecurityContext(obj: JenkinsSpecMasterSecurityContext | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsGroup': obj.fsGroup,
'runAsGroup': obj.runAsGroup,
'runAsNonRoot': obj.runAsNonRoot,
'runAsUser': obj.runAsUser,
'seLinuxOptions': toJson_JenkinsSpecMasterSecurityContextSeLinuxOptions(obj.seLinuxOptions),
'supplementalGroups': obj.supplementalGroups?.map(y => y),
'sysctls': obj.sysctls?.map(y => toJson_JenkinsSpecMasterSecurityContextSysctls(y)),
'windowsOptions': toJson_JenkinsSpecMasterSecurityContextWindowsOptions(obj.windowsOptions),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The pod this Toleration is attached to tolerates any taint that matches the triple <key,value,effect> using the matching operator <operator>.
*
* @schema JenkinsSpecMasterTolerations
*/
export interface JenkinsSpecMasterTolerations {
/**
* Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.
*
* @schema JenkinsSpecMasterTolerations#effect
*/
readonly effect?: string;
/**
* Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys.
*
* @schema JenkinsSpecMasterTolerations#key
*/
readonly key?: string;
/**
* Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category.
*
* @default Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category.
* @schema JenkinsSpecMasterTolerations#operator
*/
readonly operator?: string;
/**
* TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system.
*
* @schema JenkinsSpecMasterTolerations#tolerationSeconds
*/
readonly tolerationSeconds?: number;
/**
* Value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string.
*
* @schema JenkinsSpecMasterTolerations#value
*/
readonly value?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterTolerations' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterTolerations(obj: JenkinsSpecMasterTolerations | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'effect': obj.effect,
'key': obj.key,
'operator': obj.operator,
'tolerationSeconds': obj.tolerationSeconds,
'value': obj.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Volume represents a named volume in a pod that may be accessed by any container in the pod.
*
* @schema JenkinsSpecMasterVolumes
*/
export interface JenkinsSpecMasterVolumes {
/**
* AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore
*
* @schema JenkinsSpecMasterVolumes#awsElasticBlockStore
*/
readonly awsElasticBlockStore?: JenkinsSpecMasterVolumesAwsElasticBlockStore;
/**
* AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.
*
* @schema JenkinsSpecMasterVolumes#azureDisk
*/
readonly azureDisk?: JenkinsSpecMasterVolumesAzureDisk;
/**
* AzureFile represents an Azure File Service mount on the host and bind mount to the pod.
*
* @schema JenkinsSpecMasterVolumes#azureFile
*/
readonly azureFile?: JenkinsSpecMasterVolumesAzureFile;
/**
* CephFS represents a Ceph FS mount on the host that shares a pod's lifetime
*
* @schema JenkinsSpecMasterVolumes#cephfs
*/
readonly cephfs?: JenkinsSpecMasterVolumesCephfs;
/**
* Cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md
*
* @schema JenkinsSpecMasterVolumes#cinder
*/
readonly cinder?: JenkinsSpecMasterVolumesCinder;
/**
* ConfigMap represents a configMap that should populate this volume
*
* @schema JenkinsSpecMasterVolumes#configMap
*/
readonly configMap?: JenkinsSpecMasterVolumesConfigMap;
/**
* CSI (Container Storage Interface) represents storage that is handled by an external CSI driver (Alpha feature).
*
* @schema JenkinsSpecMasterVolumes#csi
*/
readonly csi?: JenkinsSpecMasterVolumesCsi;
/**
* DownwardAPI represents downward API about the pod that should populate this volume
*
* @schema JenkinsSpecMasterVolumes#downwardAPI
*/
readonly downwardApi?: JenkinsSpecMasterVolumesDownwardApi;
/**
* EmptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir
*
* @schema JenkinsSpecMasterVolumes#emptyDir
*/
readonly emptyDir?: JenkinsSpecMasterVolumesEmptyDir;
/**
* FC represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.
*
* @schema JenkinsSpecMasterVolumes#fc
*/
readonly fc?: JenkinsSpecMasterVolumesFc;
/**
* FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.
*
* @schema JenkinsSpecMasterVolumes#flexVolume
*/
readonly flexVolume?: JenkinsSpecMasterVolumesFlexVolume;
/**
* Flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running
*
* @schema JenkinsSpecMasterVolumes#flocker
*/
readonly flocker?: JenkinsSpecMasterVolumesFlocker;
/**
* GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
*
* @schema JenkinsSpecMasterVolumes#gcePersistentDisk
*/
readonly gcePersistentDisk?: JenkinsSpecMasterVolumesGcePersistentDisk;
/**
* GitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.
*
* @schema JenkinsSpecMasterVolumes#gitRepo
*/
readonly gitRepo?: JenkinsSpecMasterVolumesGitRepo;
/**
* Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md
*
* @schema JenkinsSpecMasterVolumes#glusterfs
*/
readonly glusterfs?: JenkinsSpecMasterVolumesGlusterfs;
/**
* HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath --- TODO(jonesdl) We need to restrict who can use host directory mounts and who can/can not mount host directories as read/write.
*
* @schema JenkinsSpecMasterVolumes#hostPath
*/
readonly hostPath?: JenkinsSpecMasterVolumesHostPath;
/**
* ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md
*
* @schema JenkinsSpecMasterVolumes#iscsi
*/
readonly iscsi?: JenkinsSpecMasterVolumesIscsi;
/**
* Volume's name. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
*
* @schema JenkinsSpecMasterVolumes#name
*/
readonly name: string;
/**
* NFS represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
*
* @schema JenkinsSpecMasterVolumes#nfs
*/
readonly nfs?: JenkinsSpecMasterVolumesNfs;
/**
* PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
*
* @schema JenkinsSpecMasterVolumes#persistentVolumeClaim
*/
readonly persistentVolumeClaim?: JenkinsSpecMasterVolumesPersistentVolumeClaim;
/**
* PhotonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine
*
* @schema JenkinsSpecMasterVolumes#photonPersistentDisk
*/
readonly photonPersistentDisk?: JenkinsSpecMasterVolumesPhotonPersistentDisk;
/**
* PortworxVolume represents a portworx volume attached and mounted on kubelets host machine
*
* @schema JenkinsSpecMasterVolumes#portworxVolume
*/
readonly portworxVolume?: JenkinsSpecMasterVolumesPortworxVolume;
/**
* Items for all in one resources secrets, configmaps, and downward API
*
* @schema JenkinsSpecMasterVolumes#projected
*/
readonly projected?: JenkinsSpecMasterVolumesProjected;
/**
* Quobyte represents a Quobyte mount on the host that shares a pod's lifetime
*
* @schema JenkinsSpecMasterVolumes#quobyte
*/
readonly quobyte?: JenkinsSpecMasterVolumesQuobyte;
/**
* RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md
*
* @schema JenkinsSpecMasterVolumes#rbd
*/
readonly rbd?: JenkinsSpecMasterVolumesRbd;
/**
* ScaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.
*
* @schema JenkinsSpecMasterVolumes#scaleIO
*/
readonly scaleIo?: JenkinsSpecMasterVolumesScaleIo;
/**
* Secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret
*
* @schema JenkinsSpecMasterVolumes#secret
*/
readonly secret?: JenkinsSpecMasterVolumesSecret;
/**
* StorageOS represents a StorageOS volume attached and mounted on Kubernetes nodes.
*
* @schema JenkinsSpecMasterVolumes#storageos
*/
readonly storageos?: JenkinsSpecMasterVolumesStorageos;
/**
* VsphereVolume represents a vSphere volume attached and mounted on kubelets host machine
*
* @schema JenkinsSpecMasterVolumes#vsphereVolume
*/
readonly vsphereVolume?: JenkinsSpecMasterVolumesVsphereVolume;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumes' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumes(obj: JenkinsSpecMasterVolumes | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'awsElasticBlockStore': toJson_JenkinsSpecMasterVolumesAwsElasticBlockStore(obj.awsElasticBlockStore),
'azureDisk': toJson_JenkinsSpecMasterVolumesAzureDisk(obj.azureDisk),
'azureFile': toJson_JenkinsSpecMasterVolumesAzureFile(obj.azureFile),
'cephfs': toJson_JenkinsSpecMasterVolumesCephfs(obj.cephfs),
'cinder': toJson_JenkinsSpecMasterVolumesCinder(obj.cinder),
'configMap': toJson_JenkinsSpecMasterVolumesConfigMap(obj.configMap),
'csi': toJson_JenkinsSpecMasterVolumesCsi(obj.csi),
'downwardAPI': toJson_JenkinsSpecMasterVolumesDownwardApi(obj.downwardApi),
'emptyDir': toJson_JenkinsSpecMasterVolumesEmptyDir(obj.emptyDir),
'fc': toJson_JenkinsSpecMasterVolumesFc(obj.fc),
'flexVolume': toJson_JenkinsSpecMasterVolumesFlexVolume(obj.flexVolume),
'flocker': toJson_JenkinsSpecMasterVolumesFlocker(obj.flocker),
'gcePersistentDisk': toJson_JenkinsSpecMasterVolumesGcePersistentDisk(obj.gcePersistentDisk),
'gitRepo': toJson_JenkinsSpecMasterVolumesGitRepo(obj.gitRepo),
'glusterfs': toJson_JenkinsSpecMasterVolumesGlusterfs(obj.glusterfs),
'hostPath': toJson_JenkinsSpecMasterVolumesHostPath(obj.hostPath),
'iscsi': toJson_JenkinsSpecMasterVolumesIscsi(obj.iscsi),
'name': obj.name,
'nfs': toJson_JenkinsSpecMasterVolumesNfs(obj.nfs),
'persistentVolumeClaim': toJson_JenkinsSpecMasterVolumesPersistentVolumeClaim(obj.persistentVolumeClaim),
'photonPersistentDisk': toJson_JenkinsSpecMasterVolumesPhotonPersistentDisk(obj.photonPersistentDisk),
'portworxVolume': toJson_JenkinsSpecMasterVolumesPortworxVolume(obj.portworxVolume),
'projected': toJson_JenkinsSpecMasterVolumesProjected(obj.projected),
'quobyte': toJson_JenkinsSpecMasterVolumesQuobyte(obj.quobyte),
'rbd': toJson_JenkinsSpecMasterVolumesRbd(obj.rbd),
'scaleIO': toJson_JenkinsSpecMasterVolumesScaleIo(obj.scaleIo),
'secret': toJson_JenkinsSpecMasterVolumesSecret(obj.secret),
'storageos': toJson_JenkinsSpecMasterVolumesStorageos(obj.storageos),
'vsphereVolume': toJson_JenkinsSpecMasterVolumesVsphereVolume(obj.vsphereVolume),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Mailgun is handler for Mailgun email service notification channel
*
* @schema JenkinsSpecNotificationsMailgun
*/
export interface JenkinsSpecNotificationsMailgun {
/**
* SecretKeySelector selects a key of a Secret.
*
* @schema JenkinsSpecNotificationsMailgun#apiKeySecretKeySelector
*/
readonly apiKeySecretKeySelector: JenkinsSpecNotificationsMailgunApiKeySecretKeySelector;
/**
* @schema JenkinsSpecNotificationsMailgun#domain
*/
readonly domain: string;
/**
* @schema JenkinsSpecNotificationsMailgun#from
*/
readonly from: string;
/**
* @schema JenkinsSpecNotificationsMailgun#recipient
*/
readonly recipient: string;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsMailgun' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsMailgun(obj: JenkinsSpecNotificationsMailgun | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'apiKeySecretKeySelector': toJson_JenkinsSpecNotificationsMailgunApiKeySecretKeySelector(obj.apiKeySecretKeySelector),
'domain': obj.domain,
'from': obj.from,
'recipient': obj.recipient,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Slack is handler for Slack notification channel
*
* @schema JenkinsSpecNotificationsSlack
*/
export interface JenkinsSpecNotificationsSlack {
/**
* The web hook URL to Slack App
*
* @schema JenkinsSpecNotificationsSlack#webHookURLSecretKeySelector
*/
readonly webHookUrlSecretKeySelector: JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSlack' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSlack(obj: JenkinsSpecNotificationsSlack | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'webHookURLSecretKeySelector': toJson_JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector(obj.webHookUrlSecretKeySelector),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SMTP is handler for sending emails via this protocol
*
* @schema JenkinsSpecNotificationsSmtp
*/
export interface JenkinsSpecNotificationsSmtp {
/**
* @schema JenkinsSpecNotificationsSmtp#from
*/
readonly from: string;
/**
* SecretKeySelector selects a key of a Secret.
*
* @schema JenkinsSpecNotificationsSmtp#passwordSecretKeySelector
*/
readonly passwordSecretKeySelector: JenkinsSpecNotificationsSmtpPasswordSecretKeySelector;
/**
* @schema JenkinsSpecNotificationsSmtp#port
*/
readonly port: number;
/**
* @schema JenkinsSpecNotificationsSmtp#server
*/
readonly server: string;
/**
* @schema JenkinsSpecNotificationsSmtp#tlsInsecureSkipVerify
*/
readonly tlsInsecureSkipVerify?: boolean;
/**
* @schema JenkinsSpecNotificationsSmtp#to
*/
readonly to: string;
/**
* SecretKeySelector selects a key of a Secret.
*
* @schema JenkinsSpecNotificationsSmtp#usernameSecretKeySelector
*/
readonly usernameSecretKeySelector: JenkinsSpecNotificationsSmtpUsernameSecretKeySelector;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSmtp' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSmtp(obj: JenkinsSpecNotificationsSmtp | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'from': obj.from,
'passwordSecretKeySelector': toJson_JenkinsSpecNotificationsSmtpPasswordSecretKeySelector(obj.passwordSecretKeySelector),
'port': obj.port,
'server': obj.server,
'tlsInsecureSkipVerify': obj.tlsInsecureSkipVerify,
'to': obj.to,
'usernameSecretKeySelector': toJson_JenkinsSpecNotificationsSmtpUsernameSecretKeySelector(obj.usernameSecretKeySelector),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* MicrosoftTeams is handler for Microsoft MicrosoftTeams notification channel
*
* @schema JenkinsSpecNotificationsTeams
*/
export interface JenkinsSpecNotificationsTeams {
/**
* The web hook URL to MicrosoftTeams App
*
* @schema JenkinsSpecNotificationsTeams#webHookURLSecretKeySelector
*/
readonly webHookUrlSecretKeySelector: JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsTeams' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsTeams(obj: JenkinsSpecNotificationsTeams | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'webHookURLSecretKeySelector': toJson_JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector(obj.webHookUrlSecretKeySelector),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Action defines action which performs restore backup in restore container sidecar
*
* @schema JenkinsSpecRestoreAction
*/
export interface JenkinsSpecRestoreAction {
/**
* Exec specifies the action to take.
*
* @schema JenkinsSpecRestoreAction#exec
*/
readonly exec?: JenkinsSpecRestoreActionExec;
}
/**
* Converts an object of type 'JenkinsSpecRestoreAction' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecRestoreAction(obj: JenkinsSpecRestoreAction | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'exec': toJson_JenkinsSpecRestoreActionExec(obj.exec),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Exec specifies the action to take.
*
* @schema JenkinsSpecBackupActionExec
*/
export interface JenkinsSpecBackupActionExec {
/**
* Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
*
* @schema JenkinsSpecBackupActionExec#command
*/
readonly command?: string[];
}
/**
* Converts an object of type 'JenkinsSpecBackupActionExec' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecBackupActionExec(obj: JenkinsSpecBackupActionExec | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'command': obj.command?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* EnvVar represents an environment variable present in a Container.
*
* @schema JenkinsSpecMasterContainersEnv
*/
export interface JenkinsSpecMasterContainersEnv {
/**
* Name of the environment variable. Must be a C_IDENTIFIER.
*
* @schema JenkinsSpecMasterContainersEnv#name
*/
readonly name: string;
/**
* Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to "".
*
* @default .
* @schema JenkinsSpecMasterContainersEnv#value
*/
readonly value?: string;
/**
* Source for the environment variable's value. Cannot be used if value is not empty.
*
* @schema JenkinsSpecMasterContainersEnv#valueFrom
*/
readonly valueFrom?: JenkinsSpecMasterContainersEnvValueFrom;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnv' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnv(obj: JenkinsSpecMasterContainersEnv | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'value': obj.value,
'valueFrom': toJson_JenkinsSpecMasterContainersEnvValueFrom(obj.valueFrom),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* EnvFromSource represents the source of a set of ConfigMaps
*
* @schema JenkinsSpecMasterContainersEnvFrom
*/
export interface JenkinsSpecMasterContainersEnvFrom {
/**
* The ConfigMap to select from
*
* @schema JenkinsSpecMasterContainersEnvFrom#configMapRef
*/
readonly configMapRef?: JenkinsSpecMasterContainersEnvFromConfigMapRef;
/**
* An optional identifier to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER.
*
* @schema JenkinsSpecMasterContainersEnvFrom#prefix
*/
readonly prefix?: string;
/**
* The Secret to select from
*
* @schema JenkinsSpecMasterContainersEnvFrom#secretRef
*/
readonly secretRef?: JenkinsSpecMasterContainersEnvFromSecretRef;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvFrom' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvFrom(obj: JenkinsSpecMasterContainersEnvFrom | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'configMapRef': toJson_JenkinsSpecMasterContainersEnvFromConfigMapRef(obj.configMapRef),
'prefix': obj.prefix,
'secretRef': toJson_JenkinsSpecMasterContainersEnvFromSecretRef(obj.secretRef),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Actions that the management system should take in response to container lifecycle events.
*
* @schema JenkinsSpecMasterContainersLifecycle
*/
export interface JenkinsSpecMasterContainersLifecycle {
/**
* PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
*
* @schema JenkinsSpecMasterContainersLifecycle#postStart
*/
readonly postStart?: JenkinsSpecMasterContainersLifecyclePostStart;
/**
* PreStop is called immediately before a container is terminated due to an API request or management event such as liveness/startup probe failure, preemption, resource contention, etc. The handler is not called if the container crashes or exits. The reason for termination is passed to the handler. The Pod's termination grace period countdown begins before the PreStop hooked is executed. Regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period. Other management of the container blocks until the hook completes or until the termination grace period is reached. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
*
* @schema JenkinsSpecMasterContainersLifecycle#preStop
*/
readonly preStop?: JenkinsSpecMasterContainersLifecyclePreStop;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecycle' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecycle(obj: JenkinsSpecMasterContainersLifecycle | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'postStart': toJson_JenkinsSpecMasterContainersLifecyclePostStart(obj.postStart),
'preStop': toJson_JenkinsSpecMasterContainersLifecyclePreStop(obj.preStop),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Periodic probe of container liveness. Container will be restarted if the probe fails.
*
* @schema JenkinsSpecMasterContainersLivenessProbe
*/
export interface JenkinsSpecMasterContainersLivenessProbe {
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersLivenessProbe#exec
*/
readonly exec?: JenkinsSpecMasterContainersLivenessProbeExec;
/**
* Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.
*
* @default 3. Minimum value is 1.
* @schema JenkinsSpecMasterContainersLivenessProbe#failureThreshold
*/
readonly failureThreshold?: number;
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersLivenessProbe#httpGet
*/
readonly httpGet?: JenkinsSpecMasterContainersLivenessProbeHttpGet;
/**
* Number of seconds after the container has started before liveness probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
*
* @schema JenkinsSpecMasterContainersLivenessProbe#initialDelaySeconds
*/
readonly initialDelaySeconds?: number;
/**
* How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.
*
* @default 10 seconds. Minimum value is 1.
* @schema JenkinsSpecMasterContainersLivenessProbe#periodSeconds
*/
readonly periodSeconds?: number;
/**
* Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1.
*
* @default 1. Must be 1 for liveness and startup. Minimum value is 1.
* @schema JenkinsSpecMasterContainersLivenessProbe#successThreshold
*/
readonly successThreshold?: number;
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersLivenessProbe#tcpSocket
*/
readonly tcpSocket?: JenkinsSpecMasterContainersLivenessProbeTcpSocket;
/**
* Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
*
* @default 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
* @schema JenkinsSpecMasterContainersLivenessProbe#timeoutSeconds
*/
readonly timeoutSeconds?: number;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLivenessProbe' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLivenessProbe(obj: JenkinsSpecMasterContainersLivenessProbe | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'exec': toJson_JenkinsSpecMasterContainersLivenessProbeExec(obj.exec),
'failureThreshold': obj.failureThreshold,
'httpGet': toJson_JenkinsSpecMasterContainersLivenessProbeHttpGet(obj.httpGet),
'initialDelaySeconds': obj.initialDelaySeconds,
'periodSeconds': obj.periodSeconds,
'successThreshold': obj.successThreshold,
'tcpSocket': toJson_JenkinsSpecMasterContainersLivenessProbeTcpSocket(obj.tcpSocket),
'timeoutSeconds': obj.timeoutSeconds,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ContainerPort represents a network port in a single container.
*
* @schema JenkinsSpecMasterContainersPorts
*/
export interface JenkinsSpecMasterContainersPorts {
/**
* Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.
*
* @schema JenkinsSpecMasterContainersPorts#containerPort
*/
readonly containerPort: number;
/**
* What host IP to bind the external port to.
*
* @schema JenkinsSpecMasterContainersPorts#hostIP
*/
readonly hostIp?: string;
/**
* Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.
*
* @schema JenkinsSpecMasterContainersPorts#hostPort
*/
readonly hostPort?: number;
/**
* If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services.
*
* @schema JenkinsSpecMasterContainersPorts#name
*/
readonly name?: string;
/**
* Protocol for port. Must be UDP, TCP, or SCTP. Defaults to "TCP".
*
* @default TCP".
* @schema JenkinsSpecMasterContainersPorts#protocol
*/
readonly protocol?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersPorts' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersPorts(obj: JenkinsSpecMasterContainersPorts | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'containerPort': obj.containerPort,
'hostIP': obj.hostIp,
'hostPort': obj.hostPort,
'name': obj.name,
'protocol': obj.protocol,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails.
*
* @schema JenkinsSpecMasterContainersReadinessProbe
*/
export interface JenkinsSpecMasterContainersReadinessProbe {
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersReadinessProbe#exec
*/
readonly exec?: JenkinsSpecMasterContainersReadinessProbeExec;
/**
* Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.
*
* @default 3. Minimum value is 1.
* @schema JenkinsSpecMasterContainersReadinessProbe#failureThreshold
*/
readonly failureThreshold?: number;
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersReadinessProbe#httpGet
*/
readonly httpGet?: JenkinsSpecMasterContainersReadinessProbeHttpGet;
/**
* Number of seconds after the container has started before liveness probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
*
* @schema JenkinsSpecMasterContainersReadinessProbe#initialDelaySeconds
*/
readonly initialDelaySeconds?: number;
/**
* How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.
*
* @default 10 seconds. Minimum value is 1.
* @schema JenkinsSpecMasterContainersReadinessProbe#periodSeconds
*/
readonly periodSeconds?: number;
/**
* Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1.
*
* @default 1. Must be 1 for liveness and startup. Minimum value is 1.
* @schema JenkinsSpecMasterContainersReadinessProbe#successThreshold
*/
readonly successThreshold?: number;
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersReadinessProbe#tcpSocket
*/
readonly tcpSocket?: JenkinsSpecMasterContainersReadinessProbeTcpSocket;
/**
* Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
*
* @default 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
* @schema JenkinsSpecMasterContainersReadinessProbe#timeoutSeconds
*/
readonly timeoutSeconds?: number;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersReadinessProbe' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersReadinessProbe(obj: JenkinsSpecMasterContainersReadinessProbe | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'exec': toJson_JenkinsSpecMasterContainersReadinessProbeExec(obj.exec),
'failureThreshold': obj.failureThreshold,
'httpGet': toJson_JenkinsSpecMasterContainersReadinessProbeHttpGet(obj.httpGet),
'initialDelaySeconds': obj.initialDelaySeconds,
'periodSeconds': obj.periodSeconds,
'successThreshold': obj.successThreshold,
'tcpSocket': toJson_JenkinsSpecMasterContainersReadinessProbeTcpSocket(obj.tcpSocket),
'timeoutSeconds': obj.timeoutSeconds,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Compute Resources required by this container. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/
*
* @schema JenkinsSpecMasterContainersResources
*/
export interface JenkinsSpecMasterContainersResources {
/**
* Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/
*
* @schema JenkinsSpecMasterContainersResources#limits
*/
readonly limits?: { [key: string]: string };
/**
* Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/
*
* @schema JenkinsSpecMasterContainersResources#requests
*/
readonly requests?: { [key: string]: string };
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersResources' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersResources(obj: JenkinsSpecMasterContainersResources | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'limits': ((obj.limits) === undefined) ? undefined : (Object.entries(obj.limits).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'requests': ((obj.requests) === undefined) ? undefined : (Object.entries(obj.requests).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Security options the pod should run with. More info: https://kubernetes.io/docs/concepts/policy/security-context/ More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
*
* @schema JenkinsSpecMasterContainersSecurityContext
*/
export interface JenkinsSpecMasterContainersSecurityContext {
/**
* AllowPrivilegeEscalation controls whether a process can gain more privileges than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is: 1) run as Privileged 2) has CAP_SYS_ADMIN
*
* @schema JenkinsSpecMasterContainersSecurityContext#allowPrivilegeEscalation
*/
readonly allowPrivilegeEscalation?: boolean;
/**
* The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime.
*
* @default the default set of capabilities granted by the container runtime.
* @schema JenkinsSpecMasterContainersSecurityContext#capabilities
*/
readonly capabilities?: JenkinsSpecMasterContainersSecurityContextCapabilities;
/**
* Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false.
*
* @default false.
* @schema JenkinsSpecMasterContainersSecurityContext#privileged
*/
readonly privileged?: boolean;
/**
* procMount denotes the type of proc mount to use for the containers. The default is DefaultProcMount which uses the container runtime defaults for readonly paths and masked paths. This requires the ProcMountType feature flag to be enabled.
*
* @schema JenkinsSpecMasterContainersSecurityContext#procMount
*/
readonly procMount?: string;
/**
* Whether this container has a read-only root filesystem. Default is false.
*
* @default false.
* @schema JenkinsSpecMasterContainersSecurityContext#readOnlyRootFilesystem
*/
readonly readOnlyRootFilesystem?: boolean;
/**
* The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterContainersSecurityContext#runAsGroup
*/
readonly runAsGroup?: number;
/**
* Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterContainersSecurityContext#runAsNonRoot
*/
readonly runAsNonRoot?: boolean;
/**
* The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @default user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
* @schema JenkinsSpecMasterContainersSecurityContext#runAsUser
*/
readonly runAsUser?: number;
/**
* The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterContainersSecurityContext#seLinuxOptions
*/
readonly seLinuxOptions?: JenkinsSpecMasterContainersSecurityContextSeLinuxOptions;
/**
* The Windows specific settings applied to all containers. If unspecified, the options from the PodSecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterContainersSecurityContext#windowsOptions
*/
readonly windowsOptions?: JenkinsSpecMasterContainersSecurityContextWindowsOptions;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersSecurityContext' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersSecurityContext(obj: JenkinsSpecMasterContainersSecurityContext | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'allowPrivilegeEscalation': obj.allowPrivilegeEscalation,
'capabilities': toJson_JenkinsSpecMasterContainersSecurityContextCapabilities(obj.capabilities),
'privileged': obj.privileged,
'procMount': obj.procMount,
'readOnlyRootFilesystem': obj.readOnlyRootFilesystem,
'runAsGroup': obj.runAsGroup,
'runAsNonRoot': obj.runAsNonRoot,
'runAsUser': obj.runAsUser,
'seLinuxOptions': toJson_JenkinsSpecMasterContainersSecurityContextSeLinuxOptions(obj.seLinuxOptions),
'windowsOptions': toJson_JenkinsSpecMasterContainersSecurityContextWindowsOptions(obj.windowsOptions),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* VolumeMount describes a mounting of a Volume within a container.
*
* @schema JenkinsSpecMasterContainersVolumeMounts
*/
export interface JenkinsSpecMasterContainersVolumeMounts {
/**
* Path within the container at which the volume should be mounted. Must not contain ':'.
*
* @schema JenkinsSpecMasterContainersVolumeMounts#mountPath
*/
readonly mountPath: string;
/**
* mountPropagation determines how mounts are propagated from the host to container and the other way around. When not set, MountPropagationNone is used. This field is beta in 1.10.
*
* @schema JenkinsSpecMasterContainersVolumeMounts#mountPropagation
*/
readonly mountPropagation?: string;
/**
* This must match the Name of a Volume.
*
* @schema JenkinsSpecMasterContainersVolumeMounts#name
*/
readonly name: string;
/**
* Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.
*
* @default false.
* @schema JenkinsSpecMasterContainersVolumeMounts#readOnly
*/
readonly readOnly?: boolean;
/**
* Path within the volume from which the container's volume should be mounted. Defaults to "" (volume's root).
*
* @default volume's root).
* @schema JenkinsSpecMasterContainersVolumeMounts#subPath
*/
readonly subPath?: string;
/**
* Expanded path within the volume from which the container's volume should be mounted. Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment. Defaults to "" (volume's root). SubPathExpr and SubPath are mutually exclusive. This field is beta in 1.15.
*
* @default volume's root). SubPathExpr and SubPath are mutually exclusive. This field is beta in 1.15.
* @schema JenkinsSpecMasterContainersVolumeMounts#subPathExpr
*/
readonly subPathExpr?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersVolumeMounts' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersVolumeMounts(obj: JenkinsSpecMasterContainersVolumeMounts | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'mountPath': obj.mountPath,
'mountPropagation': obj.mountPropagation,
'name': obj.name,
'readOnly': obj.readOnly,
'subPath': obj.subPath,
'subPathExpr': obj.subPathExpr,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
*
* @schema JenkinsSpecMasterSecurityContextSeLinuxOptions
*/
export interface JenkinsSpecMasterSecurityContextSeLinuxOptions {
/**
* Level is SELinux level label that applies to the container.
*
* @schema JenkinsSpecMasterSecurityContextSeLinuxOptions#level
*/
readonly level?: string;
/**
* Role is a SELinux role label that applies to the container.
*
* @schema JenkinsSpecMasterSecurityContextSeLinuxOptions#role
*/
readonly role?: string;
/**
* Type is a SELinux type label that applies to the container.
*
* @schema JenkinsSpecMasterSecurityContextSeLinuxOptions#type
*/
readonly type?: string;
/**
* User is a SELinux user label that applies to the container.
*
* @schema JenkinsSpecMasterSecurityContextSeLinuxOptions#user
*/
readonly user?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterSecurityContextSeLinuxOptions' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterSecurityContextSeLinuxOptions(obj: JenkinsSpecMasterSecurityContextSeLinuxOptions | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'level': obj.level,
'role': obj.role,
'type': obj.type,
'user': obj.user,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Sysctl defines a kernel parameter to be set
*
* @schema JenkinsSpecMasterSecurityContextSysctls
*/
export interface JenkinsSpecMasterSecurityContextSysctls {
/**
* Name of a property to set
*
* @schema JenkinsSpecMasterSecurityContextSysctls#name
*/
readonly name: string;
/**
* Value of a property to set
*
* @schema JenkinsSpecMasterSecurityContextSysctls#value
*/
readonly value: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterSecurityContextSysctls' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterSecurityContextSysctls(obj: JenkinsSpecMasterSecurityContextSysctls | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'value': obj.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterSecurityContextWindowsOptions
*/
export interface JenkinsSpecMasterSecurityContextWindowsOptions {
/**
* GMSACredentialSpec is where the GMSA admission webhook (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the GMSA credential spec named by the GMSACredentialSpecName field. This field is alpha-level and is only honored by servers that enable the WindowsGMSA feature flag.
*
* @schema JenkinsSpecMasterSecurityContextWindowsOptions#gmsaCredentialSpec
*/
readonly gmsaCredentialSpec?: string;
/**
* GMSACredentialSpecName is the name of the GMSA credential spec to use. This field is alpha-level and is only honored by servers that enable the WindowsGMSA feature flag.
*
* @schema JenkinsSpecMasterSecurityContextWindowsOptions#gmsaCredentialSpecName
*/
readonly gmsaCredentialSpecName?: string;
/**
* The UserName in Windows to run the entrypoint of the container process. Defaults to the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. This field is alpha-level and it is only honored by servers that enable the WindowsRunAsUserName feature flag.
*
* @default the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. This field is alpha-level and it is only honored by servers that enable the WindowsRunAsUserName feature flag.
* @schema JenkinsSpecMasterSecurityContextWindowsOptions#runAsUserName
*/
readonly runAsUserName?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterSecurityContextWindowsOptions' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterSecurityContextWindowsOptions(obj: JenkinsSpecMasterSecurityContextWindowsOptions | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'gmsaCredentialSpec': obj.gmsaCredentialSpec,
'gmsaCredentialSpecName': obj.gmsaCredentialSpecName,
'runAsUserName': obj.runAsUserName,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore
*
* @schema JenkinsSpecMasterVolumesAwsElasticBlockStore
*/
export interface JenkinsSpecMasterVolumesAwsElasticBlockStore {
/**
* Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore TODO: how do we prevent errors in the filesystem from compromising the machine
*
* @schema JenkinsSpecMasterVolumesAwsElasticBlockStore#fsType
*/
readonly fsType?: string;
/**
* The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as "1". Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty).
*
* @schema JenkinsSpecMasterVolumesAwsElasticBlockStore#partition
*/
readonly partition?: number;
/**
* Specify "true" to force and set the ReadOnly property in VolumeMounts to "true". If omitted, the default is "false". More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore
*
* @schema JenkinsSpecMasterVolumesAwsElasticBlockStore#readOnly
*/
readonly readOnly?: boolean;
/**
* Unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore
*
* @schema JenkinsSpecMasterVolumesAwsElasticBlockStore#volumeID
*/
readonly volumeId: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesAwsElasticBlockStore' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesAwsElasticBlockStore(obj: JenkinsSpecMasterVolumesAwsElasticBlockStore | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'partition': obj.partition,
'readOnly': obj.readOnly,
'volumeID': obj.volumeId,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.
*
* @schema JenkinsSpecMasterVolumesAzureDisk
*/
export interface JenkinsSpecMasterVolumesAzureDisk {
/**
* Host Caching mode: None, Read Only, Read Write.
*
* @schema JenkinsSpecMasterVolumesAzureDisk#cachingMode
*/
readonly cachingMode?: string;
/**
* The Name of the data disk in the blob storage
*
* @schema JenkinsSpecMasterVolumesAzureDisk#diskName
*/
readonly diskName: string;
/**
* The URI the data disk in the blob storage
*
* @schema JenkinsSpecMasterVolumesAzureDisk#diskURI
*/
readonly diskUri: string;
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
*
* @schema JenkinsSpecMasterVolumesAzureDisk#fsType
*/
readonly fsType?: string;
/**
* Expected values Shared: multiple blob disks per storage account Dedicated: single blob disk per storage account Managed: azure managed data disk (only in managed availability set). defaults to shared
*
* @schema JenkinsSpecMasterVolumesAzureDisk#kind
*/
readonly kind?: string;
/**
* Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
* @schema JenkinsSpecMasterVolumesAzureDisk#readOnly
*/
readonly readOnly?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesAzureDisk' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesAzureDisk(obj: JenkinsSpecMasterVolumesAzureDisk | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'cachingMode': obj.cachingMode,
'diskName': obj.diskName,
'diskURI': obj.diskUri,
'fsType': obj.fsType,
'kind': obj.kind,
'readOnly': obj.readOnly,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* AzureFile represents an Azure File Service mount on the host and bind mount to the pod.
*
* @schema JenkinsSpecMasterVolumesAzureFile
*/
export interface JenkinsSpecMasterVolumesAzureFile {
/**
* Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
* @schema JenkinsSpecMasterVolumesAzureFile#readOnly
*/
readonly readOnly?: boolean;
/**
* the name of secret that contains Azure Storage Account Name and Key
*
* @schema JenkinsSpecMasterVolumesAzureFile#secretName
*/
readonly secretName: string;
/**
* Share Name
*
* @schema JenkinsSpecMasterVolumesAzureFile#shareName
*/
readonly shareName: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesAzureFile' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesAzureFile(obj: JenkinsSpecMasterVolumesAzureFile | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'readOnly': obj.readOnly,
'secretName': obj.secretName,
'shareName': obj.shareName,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* CephFS represents a Ceph FS mount on the host that shares a pod's lifetime
*
* @schema JenkinsSpecMasterVolumesCephfs
*/
export interface JenkinsSpecMasterVolumesCephfs {
/**
* Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it
*
* @schema JenkinsSpecMasterVolumesCephfs#monitors
*/
readonly monitors: string[];
/**
* Optional: Used as the mounted root, rather than the full Ceph tree, default is /
*
* @schema JenkinsSpecMasterVolumesCephfs#path
*/
readonly path?: string;
/**
* Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it
* @schema JenkinsSpecMasterVolumesCephfs#readOnly
*/
readonly readOnly?: boolean;
/**
* Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it
*
* @schema JenkinsSpecMasterVolumesCephfs#secretFile
*/
readonly secretFile?: string;
/**
* Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it
*
* @schema JenkinsSpecMasterVolumesCephfs#secretRef
*/
readonly secretRef?: JenkinsSpecMasterVolumesCephfsSecretRef;
/**
* Optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it
*
* @schema JenkinsSpecMasterVolumesCephfs#user
*/
readonly user?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesCephfs' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesCephfs(obj: JenkinsSpecMasterVolumesCephfs | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'monitors': obj.monitors?.map(y => y),
'path': obj.path,
'readOnly': obj.readOnly,
'secretFile': obj.secretFile,
'secretRef': toJson_JenkinsSpecMasterVolumesCephfsSecretRef(obj.secretRef),
'user': obj.user,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md
*
* @schema JenkinsSpecMasterVolumesCinder
*/
export interface JenkinsSpecMasterVolumesCinder {
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md
*
* @schema JenkinsSpecMasterVolumesCinder#fsType
*/
readonly fsType?: string;
/**
* Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md
* @schema JenkinsSpecMasterVolumesCinder#readOnly
*/
readonly readOnly?: boolean;
/**
* Optional: points to a secret object containing parameters used to connect to OpenStack.
*
* @schema JenkinsSpecMasterVolumesCinder#secretRef
*/
readonly secretRef?: JenkinsSpecMasterVolumesCinderSecretRef;
/**
* volume id used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md
*
* @schema JenkinsSpecMasterVolumesCinder#volumeID
*/
readonly volumeId: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesCinder' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesCinder(obj: JenkinsSpecMasterVolumesCinder | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'readOnly': obj.readOnly,
'secretRef': toJson_JenkinsSpecMasterVolumesCinderSecretRef(obj.secretRef),
'volumeID': obj.volumeId,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ConfigMap represents a configMap that should populate this volume
*
* @schema JenkinsSpecMasterVolumesConfigMap
*/
export interface JenkinsSpecMasterVolumesConfigMap {
/**
* Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @default 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
* @schema JenkinsSpecMasterVolumesConfigMap#defaultMode
*/
readonly defaultMode?: number;
/**
* If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.
*
* @schema JenkinsSpecMasterVolumesConfigMap#items
*/
readonly items?: JenkinsSpecMasterVolumesConfigMapItems[];
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesConfigMap#name
*/
readonly name?: string;
/**
* Specify whether the ConfigMap or its keys must be defined
*
* @schema JenkinsSpecMasterVolumesConfigMap#optional
*/
readonly optional?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesConfigMap' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesConfigMap(obj: JenkinsSpecMasterVolumesConfigMap | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'defaultMode': obj.defaultMode,
'items': obj.items?.map(y => toJson_JenkinsSpecMasterVolumesConfigMapItems(y)),
'name': obj.name,
'optional': obj.optional,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* CSI (Container Storage Interface) represents storage that is handled by an external CSI driver (Alpha feature).
*
* @schema JenkinsSpecMasterVolumesCsi
*/
export interface JenkinsSpecMasterVolumesCsi {
/**
* Driver is the name of the CSI driver that handles this volume. Consult with your admin for the correct name as registered in the cluster.
*
* @schema JenkinsSpecMasterVolumesCsi#driver
*/
readonly driver: string;
/**
* Filesystem type to mount. Ex. "ext4", "xfs", "ntfs". If not provided, the empty value is passed to the associated CSI driver which will determine the default filesystem to apply.
*
* @schema JenkinsSpecMasterVolumesCsi#fsType
*/
readonly fsType?: string;
/**
* NodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secret references are passed.
*
* @schema JenkinsSpecMasterVolumesCsi#nodePublishSecretRef
*/
readonly nodePublishSecretRef?: JenkinsSpecMasterVolumesCsiNodePublishSecretRef;
/**
* Specifies a read-only configuration for the volume. Defaults to false (read/write).
*
* @default false (read/write).
* @schema JenkinsSpecMasterVolumesCsi#readOnly
*/
readonly readOnly?: boolean;
/**
* VolumeAttributes stores driver-specific properties that are passed to the CSI driver. Consult your driver's documentation for supported values.
*
* @schema JenkinsSpecMasterVolumesCsi#volumeAttributes
*/
readonly volumeAttributes?: { [key: string]: string };
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesCsi' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesCsi(obj: JenkinsSpecMasterVolumesCsi | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'driver': obj.driver,
'fsType': obj.fsType,
'nodePublishSecretRef': toJson_JenkinsSpecMasterVolumesCsiNodePublishSecretRef(obj.nodePublishSecretRef),
'readOnly': obj.readOnly,
'volumeAttributes': ((obj.volumeAttributes) === undefined) ? undefined : (Object.entries(obj.volumeAttributes).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* DownwardAPI represents downward API about the pod that should populate this volume
*
* @schema JenkinsSpecMasterVolumesDownwardApi
*/
export interface JenkinsSpecMasterVolumesDownwardApi {
/**
* Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @default 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
* @schema JenkinsSpecMasterVolumesDownwardApi#defaultMode
*/
readonly defaultMode?: number;
/**
* Items is a list of downward API volume file
*
* @schema JenkinsSpecMasterVolumesDownwardApi#items
*/
readonly items?: JenkinsSpecMasterVolumesDownwardApiItems[];
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesDownwardApi' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesDownwardApi(obj: JenkinsSpecMasterVolumesDownwardApi | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'defaultMode': obj.defaultMode,
'items': obj.items?.map(y => toJson_JenkinsSpecMasterVolumesDownwardApiItems(y)),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* EmptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir
*
* @schema JenkinsSpecMasterVolumesEmptyDir
*/
export interface JenkinsSpecMasterVolumesEmptyDir {
/**
* What type of storage medium should back this directory. The default is "" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir
*
* @schema JenkinsSpecMasterVolumesEmptyDir#medium
*/
readonly medium?: string;
/**
* Total amount of local storage required for this EmptyDir volume. The size limit is also applicable for memory medium. The maximum usage on memory medium EmptyDir would be the minimum value between the SizeLimit specified here and the sum of memory limits of all containers in a pod. The default is nil which means that the limit is undefined. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir
*
* @schema JenkinsSpecMasterVolumesEmptyDir#sizeLimit
*/
readonly sizeLimit?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesEmptyDir' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesEmptyDir(obj: JenkinsSpecMasterVolumesEmptyDir | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'medium': obj.medium,
'sizeLimit': obj.sizeLimit,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* FC represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.
*
* @schema JenkinsSpecMasterVolumesFc
*/
export interface JenkinsSpecMasterVolumesFc {
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. TODO: how do we prevent errors in the filesystem from compromising the machine
*
* @schema JenkinsSpecMasterVolumesFc#fsType
*/
readonly fsType?: string;
/**
* Optional: FC target lun number
*
* @schema JenkinsSpecMasterVolumesFc#lun
*/
readonly lun?: number;
/**
* Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
* @schema JenkinsSpecMasterVolumesFc#readOnly
*/
readonly readOnly?: boolean;
/**
* Optional: FC target worldwide names (WWNs)
*
* @schema JenkinsSpecMasterVolumesFc#targetWWNs
*/
readonly targetWwNs?: string[];
/**
* Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.
*
* @schema JenkinsSpecMasterVolumesFc#wwids
*/
readonly wwids?: string[];
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesFc' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesFc(obj: JenkinsSpecMasterVolumesFc | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'lun': obj.lun,
'readOnly': obj.readOnly,
'targetWWNs': obj.targetWwNs?.map(y => y),
'wwids': obj.wwids?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.
*
* @schema JenkinsSpecMasterVolumesFlexVolume
*/
export interface JenkinsSpecMasterVolumesFlexVolume {
/**
* Driver is the name of the driver to use for this volume.
*
* @schema JenkinsSpecMasterVolumesFlexVolume#driver
*/
readonly driver: string;
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". The default filesystem depends on FlexVolume script.
*
* @schema JenkinsSpecMasterVolumesFlexVolume#fsType
*/
readonly fsType?: string;
/**
* Optional: Extra command options if any.
*
* @schema JenkinsSpecMasterVolumesFlexVolume#options
*/
readonly options?: { [key: string]: string };
/**
* Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
* @schema JenkinsSpecMasterVolumesFlexVolume#readOnly
*/
readonly readOnly?: boolean;
/**
* Optional: SecretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.
*
* @schema JenkinsSpecMasterVolumesFlexVolume#secretRef
*/
readonly secretRef?: JenkinsSpecMasterVolumesFlexVolumeSecretRef;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesFlexVolume' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesFlexVolume(obj: JenkinsSpecMasterVolumesFlexVolume | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'driver': obj.driver,
'fsType': obj.fsType,
'options': ((obj.options) === undefined) ? undefined : (Object.entries(obj.options).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {})),
'readOnly': obj.readOnly,
'secretRef': toJson_JenkinsSpecMasterVolumesFlexVolumeSecretRef(obj.secretRef),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running
*
* @schema JenkinsSpecMasterVolumesFlocker
*/
export interface JenkinsSpecMasterVolumesFlocker {
/**
* Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated
*
* @schema JenkinsSpecMasterVolumesFlocker#datasetName
*/
readonly datasetName?: string;
/**
* UUID of the dataset. This is unique identifier of a Flocker dataset
*
* @schema JenkinsSpecMasterVolumesFlocker#datasetUUID
*/
readonly datasetUuid?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesFlocker' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesFlocker(obj: JenkinsSpecMasterVolumesFlocker | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'datasetName': obj.datasetName,
'datasetUUID': obj.datasetUuid,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
*
* @schema JenkinsSpecMasterVolumesGcePersistentDisk
*/
export interface JenkinsSpecMasterVolumesGcePersistentDisk {
/**
* Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk TODO: how do we prevent errors in the filesystem from compromising the machine
*
* @schema JenkinsSpecMasterVolumesGcePersistentDisk#fsType
*/
readonly fsType?: string;
/**
* The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as "1". Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty). More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
*
* @schema JenkinsSpecMasterVolumesGcePersistentDisk#partition
*/
readonly partition?: number;
/**
* Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
*
* @schema JenkinsSpecMasterVolumesGcePersistentDisk#pdName
*/
readonly pdName: string;
/**
* ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
*
* @default false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
* @schema JenkinsSpecMasterVolumesGcePersistentDisk#readOnly
*/
readonly readOnly?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesGcePersistentDisk' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesGcePersistentDisk(obj: JenkinsSpecMasterVolumesGcePersistentDisk | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'partition': obj.partition,
'pdName': obj.pdName,
'readOnly': obj.readOnly,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* GitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.
*
* @schema JenkinsSpecMasterVolumesGitRepo
*/
export interface JenkinsSpecMasterVolumesGitRepo {
/**
* Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.
*
* @schema JenkinsSpecMasterVolumesGitRepo#directory
*/
readonly directory?: string;
/**
* Repository URL
*
* @schema JenkinsSpecMasterVolumesGitRepo#repository
*/
readonly repository: string;
/**
* Commit hash for the specified revision.
*
* @schema JenkinsSpecMasterVolumesGitRepo#revision
*/
readonly revision?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesGitRepo' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesGitRepo(obj: JenkinsSpecMasterVolumesGitRepo | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'directory': obj.directory,
'repository': obj.repository,
'revision': obj.revision,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md
*
* @schema JenkinsSpecMasterVolumesGlusterfs
*/
export interface JenkinsSpecMasterVolumesGlusterfs {
/**
* EndpointsName is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod
*
* @schema JenkinsSpecMasterVolumesGlusterfs#endpoints
*/
readonly endpoints: string;
/**
* Path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod
*
* @schema JenkinsSpecMasterVolumesGlusterfs#path
*/
readonly path: string;
/**
* ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod
*
* @default false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod
* @schema JenkinsSpecMasterVolumesGlusterfs#readOnly
*/
readonly readOnly?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesGlusterfs' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesGlusterfs(obj: JenkinsSpecMasterVolumesGlusterfs | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'endpoints': obj.endpoints,
'path': obj.path,
'readOnly': obj.readOnly,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath --- TODO(jonesdl) We need to restrict who can use host directory mounts and who can/can not mount host directories as read/write.
*
* @schema JenkinsSpecMasterVolumesHostPath
*/
export interface JenkinsSpecMasterVolumesHostPath {
/**
* Path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath
*
* @schema JenkinsSpecMasterVolumesHostPath#path
*/
readonly path: string;
/**
* Type for HostPath Volume Defaults to "" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath
*
* @default More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath
* @schema JenkinsSpecMasterVolumesHostPath#type
*/
readonly type?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesHostPath' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesHostPath(obj: JenkinsSpecMasterVolumesHostPath | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'path': obj.path,
'type': obj.type,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md
*
* @schema JenkinsSpecMasterVolumesIscsi
*/
export interface JenkinsSpecMasterVolumesIscsi {
/**
* whether support iSCSI Discovery CHAP authentication
*
* @schema JenkinsSpecMasterVolumesIscsi#chapAuthDiscovery
*/
readonly chapAuthDiscovery?: boolean;
/**
* whether support iSCSI Session CHAP authentication
*
* @schema JenkinsSpecMasterVolumesIscsi#chapAuthSession
*/
readonly chapAuthSession?: boolean;
/**
* Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi TODO: how do we prevent errors in the filesystem from compromising the machine
*
* @schema JenkinsSpecMasterVolumesIscsi#fsType
*/
readonly fsType?: string;
/**
* Custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface <target portal>:<volume name> will be created for the connection.
*
* @schema JenkinsSpecMasterVolumesIscsi#initiatorName
*/
readonly initiatorName?: string;
/**
* Target iSCSI Qualified Name.
*
* @schema JenkinsSpecMasterVolumesIscsi#iqn
*/
readonly iqn: string;
/**
* iSCSI Interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).
*
* @default default' (tcp).
* @schema JenkinsSpecMasterVolumesIscsi#iscsiInterface
*/
readonly iscsiInterface?: string;
/**
* iSCSI Target Lun number.
*
* @schema JenkinsSpecMasterVolumesIscsi#lun
*/
readonly lun: number;
/**
* iSCSI Target Portal List. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).
*
* @schema JenkinsSpecMasterVolumesIscsi#portals
*/
readonly portals?: string[];
/**
* ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.
*
* @default false.
* @schema JenkinsSpecMasterVolumesIscsi#readOnly
*/
readonly readOnly?: boolean;
/**
* CHAP Secret for iSCSI target and initiator authentication
*
* @schema JenkinsSpecMasterVolumesIscsi#secretRef
*/
readonly secretRef?: JenkinsSpecMasterVolumesIscsiSecretRef;
/**
* iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).
*
* @schema JenkinsSpecMasterVolumesIscsi#targetPortal
*/
readonly targetPortal: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesIscsi' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesIscsi(obj: JenkinsSpecMasterVolumesIscsi | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'chapAuthDiscovery': obj.chapAuthDiscovery,
'chapAuthSession': obj.chapAuthSession,
'fsType': obj.fsType,
'initiatorName': obj.initiatorName,
'iqn': obj.iqn,
'iscsiInterface': obj.iscsiInterface,
'lun': obj.lun,
'portals': obj.portals?.map(y => y),
'readOnly': obj.readOnly,
'secretRef': toJson_JenkinsSpecMasterVolumesIscsiSecretRef(obj.secretRef),
'targetPortal': obj.targetPortal,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* NFS represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
*
* @schema JenkinsSpecMasterVolumesNfs
*/
export interface JenkinsSpecMasterVolumesNfs {
/**
* Path that is exported by the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
*
* @schema JenkinsSpecMasterVolumesNfs#path
*/
readonly path: string;
/**
* ReadOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
*
* @default false. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
* @schema JenkinsSpecMasterVolumesNfs#readOnly
*/
readonly readOnly?: boolean;
/**
* Server is the hostname or IP address of the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
*
* @schema JenkinsSpecMasterVolumesNfs#server
*/
readonly server: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesNfs' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesNfs(obj: JenkinsSpecMasterVolumesNfs | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'path': obj.path,
'readOnly': obj.readOnly,
'server': obj.server,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
*
* @schema JenkinsSpecMasterVolumesPersistentVolumeClaim
*/
export interface JenkinsSpecMasterVolumesPersistentVolumeClaim {
/**
* ClaimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
*
* @schema JenkinsSpecMasterVolumesPersistentVolumeClaim#claimName
*/
readonly claimName: string;
/**
* Will force the ReadOnly setting in VolumeMounts. Default false.
*
* @schema JenkinsSpecMasterVolumesPersistentVolumeClaim#readOnly
*/
readonly readOnly?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesPersistentVolumeClaim' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesPersistentVolumeClaim(obj: JenkinsSpecMasterVolumesPersistentVolumeClaim | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'claimName': obj.claimName,
'readOnly': obj.readOnly,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* PhotonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine
*
* @schema JenkinsSpecMasterVolumesPhotonPersistentDisk
*/
export interface JenkinsSpecMasterVolumesPhotonPersistentDisk {
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
*
* @schema JenkinsSpecMasterVolumesPhotonPersistentDisk#fsType
*/
readonly fsType?: string;
/**
* ID that identifies Photon Controller persistent disk
*
* @schema JenkinsSpecMasterVolumesPhotonPersistentDisk#pdID
*/
readonly pdId: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesPhotonPersistentDisk' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesPhotonPersistentDisk(obj: JenkinsSpecMasterVolumesPhotonPersistentDisk | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'pdID': obj.pdId,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* PortworxVolume represents a portworx volume attached and mounted on kubelets host machine
*
* @schema JenkinsSpecMasterVolumesPortworxVolume
*/
export interface JenkinsSpecMasterVolumesPortworxVolume {
/**
* FSType represents the filesystem type to mount Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs". Implicitly inferred to be "ext4" if unspecified.
*
* @schema JenkinsSpecMasterVolumesPortworxVolume#fsType
*/
readonly fsType?: string;
/**
* Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
* @schema JenkinsSpecMasterVolumesPortworxVolume#readOnly
*/
readonly readOnly?: boolean;
/**
* VolumeID uniquely identifies a Portworx volume
*
* @schema JenkinsSpecMasterVolumesPortworxVolume#volumeID
*/
readonly volumeId: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesPortworxVolume' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesPortworxVolume(obj: JenkinsSpecMasterVolumesPortworxVolume | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'readOnly': obj.readOnly,
'volumeID': obj.volumeId,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Items for all in one resources secrets, configmaps, and downward API
*
* @schema JenkinsSpecMasterVolumesProjected
*/
export interface JenkinsSpecMasterVolumesProjected {
/**
* Mode bits to use on created files by default. Must be a value between 0 and 0777. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @schema JenkinsSpecMasterVolumesProjected#defaultMode
*/
readonly defaultMode?: number;
/**
* list of volume projections
*
* @schema JenkinsSpecMasterVolumesProjected#sources
*/
readonly sources: JenkinsSpecMasterVolumesProjectedSources[];
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjected' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjected(obj: JenkinsSpecMasterVolumesProjected | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'defaultMode': obj.defaultMode,
'sources': obj.sources?.map(y => toJson_JenkinsSpecMasterVolumesProjectedSources(y)),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Quobyte represents a Quobyte mount on the host that shares a pod's lifetime
*
* @schema JenkinsSpecMasterVolumesQuobyte
*/
export interface JenkinsSpecMasterVolumesQuobyte {
/**
* Group to map volume access to Default is no group
*
* @default no group
* @schema JenkinsSpecMasterVolumesQuobyte#group
*/
readonly group?: string;
/**
* ReadOnly here will force the Quobyte volume to be mounted with read-only permissions. Defaults to false.
*
* @default false.
* @schema JenkinsSpecMasterVolumesQuobyte#readOnly
*/
readonly readOnly?: boolean;
/**
* Registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes
*
* @schema JenkinsSpecMasterVolumesQuobyte#registry
*/
readonly registry: string;
/**
* Tenant owning the given Quobyte volume in the Backend Used with dynamically provisioned Quobyte volumes, value is set by the plugin
*
* @schema JenkinsSpecMasterVolumesQuobyte#tenant
*/
readonly tenant?: string;
/**
* User to map volume access to Defaults to serivceaccount user
*
* @default serivceaccount user
* @schema JenkinsSpecMasterVolumesQuobyte#user
*/
readonly user?: string;
/**
* Volume is a string that references an already created Quobyte volume by name.
*
* @schema JenkinsSpecMasterVolumesQuobyte#volume
*/
readonly volume: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesQuobyte' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesQuobyte(obj: JenkinsSpecMasterVolumesQuobyte | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'group': obj.group,
'readOnly': obj.readOnly,
'registry': obj.registry,
'tenant': obj.tenant,
'user': obj.user,
'volume': obj.volume,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md
*
* @schema JenkinsSpecMasterVolumesRbd
*/
export interface JenkinsSpecMasterVolumesRbd {
/**
* Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd TODO: how do we prevent errors in the filesystem from compromising the machine
*
* @schema JenkinsSpecMasterVolumesRbd#fsType
*/
readonly fsType?: string;
/**
* The rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @schema JenkinsSpecMasterVolumesRbd#image
*/
readonly image: string;
/**
* Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @default etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
* @schema JenkinsSpecMasterVolumesRbd#keyring
*/
readonly keyring?: string;
/**
* A collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @schema JenkinsSpecMasterVolumesRbd#monitors
*/
readonly monitors: string[];
/**
* The rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @default rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
* @schema JenkinsSpecMasterVolumesRbd#pool
*/
readonly pool?: string;
/**
* ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @default false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
* @schema JenkinsSpecMasterVolumesRbd#readOnly
*/
readonly readOnly?: boolean;
/**
* SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @default nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
* @schema JenkinsSpecMasterVolumesRbd#secretRef
*/
readonly secretRef?: JenkinsSpecMasterVolumesRbdSecretRef;
/**
* The rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @default admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
* @schema JenkinsSpecMasterVolumesRbd#user
*/
readonly user?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesRbd' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesRbd(obj: JenkinsSpecMasterVolumesRbd | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'image': obj.image,
'keyring': obj.keyring,
'monitors': obj.monitors?.map(y => y),
'pool': obj.pool,
'readOnly': obj.readOnly,
'secretRef': toJson_JenkinsSpecMasterVolumesRbdSecretRef(obj.secretRef),
'user': obj.user,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* ScaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.
*
* @schema JenkinsSpecMasterVolumesScaleIo
*/
export interface JenkinsSpecMasterVolumesScaleIo {
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Default is "xfs".
*
* @default xfs".
* @schema JenkinsSpecMasterVolumesScaleIo#fsType
*/
readonly fsType?: string;
/**
* The host address of the ScaleIO API Gateway.
*
* @schema JenkinsSpecMasterVolumesScaleIo#gateway
*/
readonly gateway: string;
/**
* The name of the ScaleIO Protection Domain for the configured storage.
*
* @schema JenkinsSpecMasterVolumesScaleIo#protectionDomain
*/
readonly protectionDomain?: string;
/**
* Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
* @schema JenkinsSpecMasterVolumesScaleIo#readOnly
*/
readonly readOnly?: boolean;
/**
* SecretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail.
*
* @schema JenkinsSpecMasterVolumesScaleIo#secretRef
*/
readonly secretRef: JenkinsSpecMasterVolumesScaleIoSecretRef;
/**
* Flag to enable/disable SSL communication with Gateway, default false
*
* @schema JenkinsSpecMasterVolumesScaleIo#sslEnabled
*/
readonly sslEnabled?: boolean;
/**
* Indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.
*
* @default ThinProvisioned.
* @schema JenkinsSpecMasterVolumesScaleIo#storageMode
*/
readonly storageMode?: string;
/**
* The ScaleIO Storage Pool associated with the protection domain.
*
* @schema JenkinsSpecMasterVolumesScaleIo#storagePool
*/
readonly storagePool?: string;
/**
* The name of the storage system as configured in ScaleIO.
*
* @schema JenkinsSpecMasterVolumesScaleIo#system
*/
readonly system: string;
/**
* The name of a volume already created in the ScaleIO system that is associated with this volume source.
*
* @schema JenkinsSpecMasterVolumesScaleIo#volumeName
*/
readonly volumeName?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesScaleIo' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesScaleIo(obj: JenkinsSpecMasterVolumesScaleIo | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'gateway': obj.gateway,
'protectionDomain': obj.protectionDomain,
'readOnly': obj.readOnly,
'secretRef': toJson_JenkinsSpecMasterVolumesScaleIoSecretRef(obj.secretRef),
'sslEnabled': obj.sslEnabled,
'storageMode': obj.storageMode,
'storagePool': obj.storagePool,
'system': obj.system,
'volumeName': obj.volumeName,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret
*
* @schema JenkinsSpecMasterVolumesSecret
*/
export interface JenkinsSpecMasterVolumesSecret {
/**
* Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @default 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
* @schema JenkinsSpecMasterVolumesSecret#defaultMode
*/
readonly defaultMode?: number;
/**
* If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.
*
* @schema JenkinsSpecMasterVolumesSecret#items
*/
readonly items?: JenkinsSpecMasterVolumesSecretItems[];
/**
* Specify whether the Secret or its keys must be defined
*
* @schema JenkinsSpecMasterVolumesSecret#optional
*/
readonly optional?: boolean;
/**
* Name of the secret in the pod's namespace to use. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret
*
* @schema JenkinsSpecMasterVolumesSecret#secretName
*/
readonly secretName?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesSecret(obj: JenkinsSpecMasterVolumesSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'defaultMode': obj.defaultMode,
'items': obj.items?.map(y => toJson_JenkinsSpecMasterVolumesSecretItems(y)),
'optional': obj.optional,
'secretName': obj.secretName,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* StorageOS represents a StorageOS volume attached and mounted on Kubernetes nodes.
*
* @schema JenkinsSpecMasterVolumesStorageos
*/
export interface JenkinsSpecMasterVolumesStorageos {
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
*
* @schema JenkinsSpecMasterVolumesStorageos#fsType
*/
readonly fsType?: string;
/**
* Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
*
* @default false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.
* @schema JenkinsSpecMasterVolumesStorageos#readOnly
*/
readonly readOnly?: boolean;
/**
* SecretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted.
*
* @schema JenkinsSpecMasterVolumesStorageos#secretRef
*/
readonly secretRef?: JenkinsSpecMasterVolumesStorageosSecretRef;
/**
* VolumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.
*
* @schema JenkinsSpecMasterVolumesStorageos#volumeName
*/
readonly volumeName?: string;
/**
* VolumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to "default" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.
*
* @schema JenkinsSpecMasterVolumesStorageos#volumeNamespace
*/
readonly volumeNamespace?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesStorageos' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesStorageos(obj: JenkinsSpecMasterVolumesStorageos | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'readOnly': obj.readOnly,
'secretRef': toJson_JenkinsSpecMasterVolumesStorageosSecretRef(obj.secretRef),
'volumeName': obj.volumeName,
'volumeNamespace': obj.volumeNamespace,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* VsphereVolume represents a vSphere volume attached and mounted on kubelets host machine
*
* @schema JenkinsSpecMasterVolumesVsphereVolume
*/
export interface JenkinsSpecMasterVolumesVsphereVolume {
/**
* Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.
*
* @schema JenkinsSpecMasterVolumesVsphereVolume#fsType
*/
readonly fsType?: string;
/**
* Storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName.
*
* @schema JenkinsSpecMasterVolumesVsphereVolume#storagePolicyID
*/
readonly storagePolicyId?: string;
/**
* Storage Policy Based Management (SPBM) profile name.
*
* @schema JenkinsSpecMasterVolumesVsphereVolume#storagePolicyName
*/
readonly storagePolicyName?: string;
/**
* Path that identifies vSphere volume vmdk
*
* @schema JenkinsSpecMasterVolumesVsphereVolume#volumePath
*/
readonly volumePath: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesVsphereVolume' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesVsphereVolume(obj: JenkinsSpecMasterVolumesVsphereVolume | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fsType': obj.fsType,
'storagePolicyID': obj.storagePolicyId,
'storagePolicyName': obj.storagePolicyName,
'volumePath': obj.volumePath,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretKeySelector selects a key of a Secret.
*
* @schema JenkinsSpecNotificationsMailgunApiKeySecretKeySelector
*/
export interface JenkinsSpecNotificationsMailgunApiKeySecretKeySelector {
/**
* The key of the secret to select from. Must be a valid secret key.
*
* @schema JenkinsSpecNotificationsMailgunApiKeySecretKeySelector#key
*/
readonly key: string;
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsMailgunApiKeySecretKeySelector#secret
*/
readonly secret: JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsMailgunApiKeySecretKeySelector' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsMailgunApiKeySecretKeySelector(obj: JenkinsSpecNotificationsMailgunApiKeySecretKeySelector | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'secret': toJson_JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret(obj.secret),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The web hook URL to Slack App
*
* @schema JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector
*/
export interface JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector {
/**
* The key of the secret to select from. Must be a valid secret key.
*
* @schema JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector#key
*/
readonly key: string;
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector#secret
*/
readonly secret: JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector(obj: JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelector | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'secret': toJson_JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret(obj.secret),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretKeySelector selects a key of a Secret.
*
* @schema JenkinsSpecNotificationsSmtpPasswordSecretKeySelector
*/
export interface JenkinsSpecNotificationsSmtpPasswordSecretKeySelector {
/**
* The key of the secret to select from. Must be a valid secret key.
*
* @schema JenkinsSpecNotificationsSmtpPasswordSecretKeySelector#key
*/
readonly key: string;
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsSmtpPasswordSecretKeySelector#secret
*/
readonly secret: JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSmtpPasswordSecretKeySelector' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSmtpPasswordSecretKeySelector(obj: JenkinsSpecNotificationsSmtpPasswordSecretKeySelector | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'secret': toJson_JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret(obj.secret),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretKeySelector selects a key of a Secret.
*
* @schema JenkinsSpecNotificationsSmtpUsernameSecretKeySelector
*/
export interface JenkinsSpecNotificationsSmtpUsernameSecretKeySelector {
/**
* The key of the secret to select from. Must be a valid secret key.
*
* @schema JenkinsSpecNotificationsSmtpUsernameSecretKeySelector#key
*/
readonly key: string;
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsSmtpUsernameSecretKeySelector#secret
*/
readonly secret: JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSmtpUsernameSecretKeySelector' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSmtpUsernameSecretKeySelector(obj: JenkinsSpecNotificationsSmtpUsernameSecretKeySelector | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'secret': toJson_JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret(obj.secret),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The web hook URL to MicrosoftTeams App
*
* @schema JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector
*/
export interface JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector {
/**
* The key of the secret to select from. Must be a valid secret key.
*
* @schema JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector#key
*/
readonly key: string;
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector#secret
*/
readonly secret: JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector(obj: JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelector | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'secret': toJson_JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret(obj.secret),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Exec specifies the action to take.
*
* @schema JenkinsSpecRestoreActionExec
*/
export interface JenkinsSpecRestoreActionExec {
/**
* Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
*
* @schema JenkinsSpecRestoreActionExec#command
*/
readonly command?: string[];
}
/**
* Converts an object of type 'JenkinsSpecRestoreActionExec' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecRestoreActionExec(obj: JenkinsSpecRestoreActionExec | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'command': obj.command?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Source for the environment variable's value. Cannot be used if value is not empty.
*
* @schema JenkinsSpecMasterContainersEnvValueFrom
*/
export interface JenkinsSpecMasterContainersEnvValueFrom {
/**
* Selects a key of a ConfigMap.
*
* @schema JenkinsSpecMasterContainersEnvValueFrom#configMapKeyRef
*/
readonly configMapKeyRef?: JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef;
/**
* Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP.
*
* @schema JenkinsSpecMasterContainersEnvValueFrom#fieldRef
*/
readonly fieldRef?: JenkinsSpecMasterContainersEnvValueFromFieldRef;
/**
* Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported.
*
* @schema JenkinsSpecMasterContainersEnvValueFrom#resourceFieldRef
*/
readonly resourceFieldRef?: JenkinsSpecMasterContainersEnvValueFromResourceFieldRef;
/**
* Selects a key of a secret in the pod's namespace
*
* @schema JenkinsSpecMasterContainersEnvValueFrom#secretKeyRef
*/
readonly secretKeyRef?: JenkinsSpecMasterContainersEnvValueFromSecretKeyRef;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvValueFrom' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvValueFrom(obj: JenkinsSpecMasterContainersEnvValueFrom | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'configMapKeyRef': toJson_JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef(obj.configMapKeyRef),
'fieldRef': toJson_JenkinsSpecMasterContainersEnvValueFromFieldRef(obj.fieldRef),
'resourceFieldRef': toJson_JenkinsSpecMasterContainersEnvValueFromResourceFieldRef(obj.resourceFieldRef),
'secretKeyRef': toJson_JenkinsSpecMasterContainersEnvValueFromSecretKeyRef(obj.secretKeyRef),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The ConfigMap to select from
*
* @schema JenkinsSpecMasterContainersEnvFromConfigMapRef
*/
export interface JenkinsSpecMasterContainersEnvFromConfigMapRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterContainersEnvFromConfigMapRef#name
*/
readonly name?: string;
/**
* Specify whether the ConfigMap must be defined
*
* @schema JenkinsSpecMasterContainersEnvFromConfigMapRef#optional
*/
readonly optional?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvFromConfigMapRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvFromConfigMapRef(obj: JenkinsSpecMasterContainersEnvFromConfigMapRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'optional': obj.optional,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The Secret to select from
*
* @schema JenkinsSpecMasterContainersEnvFromSecretRef
*/
export interface JenkinsSpecMasterContainersEnvFromSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterContainersEnvFromSecretRef#name
*/
readonly name?: string;
/**
* Specify whether the Secret must be defined
*
* @schema JenkinsSpecMasterContainersEnvFromSecretRef#optional
*/
readonly optional?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvFromSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvFromSecretRef(obj: JenkinsSpecMasterContainersEnvFromSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'optional': obj.optional,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
*
* @schema JenkinsSpecMasterContainersLifecyclePostStart
*/
export interface JenkinsSpecMasterContainersLifecyclePostStart {
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStart#exec
*/
readonly exec?: JenkinsSpecMasterContainersLifecyclePostStartExec;
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStart#httpGet
*/
readonly httpGet?: JenkinsSpecMasterContainersLifecyclePostStartHttpGet;
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersLifecyclePostStart#tcpSocket
*/
readonly tcpSocket?: JenkinsSpecMasterContainersLifecyclePostStartTcpSocket;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePostStart' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePostStart(obj: JenkinsSpecMasterContainersLifecyclePostStart | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'exec': toJson_JenkinsSpecMasterContainersLifecyclePostStartExec(obj.exec),
'httpGet': toJson_JenkinsSpecMasterContainersLifecyclePostStartHttpGet(obj.httpGet),
'tcpSocket': toJson_JenkinsSpecMasterContainersLifecyclePostStartTcpSocket(obj.tcpSocket),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* PreStop is called immediately before a container is terminated due to an API request or management event such as liveness/startup probe failure, preemption, resource contention, etc. The handler is not called if the container crashes or exits. The reason for termination is passed to the handler. The Pod's termination grace period countdown begins before the PreStop hooked is executed. Regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period. Other management of the container blocks until the hook completes or until the termination grace period is reached. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
*
* @schema JenkinsSpecMasterContainersLifecyclePreStop
*/
export interface JenkinsSpecMasterContainersLifecyclePreStop {
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStop#exec
*/
readonly exec?: JenkinsSpecMasterContainersLifecyclePreStopExec;
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStop#httpGet
*/
readonly httpGet?: JenkinsSpecMasterContainersLifecyclePreStopHttpGet;
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersLifecyclePreStop#tcpSocket
*/
readonly tcpSocket?: JenkinsSpecMasterContainersLifecyclePreStopTcpSocket;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePreStop' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePreStop(obj: JenkinsSpecMasterContainersLifecyclePreStop | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'exec': toJson_JenkinsSpecMasterContainersLifecyclePreStopExec(obj.exec),
'httpGet': toJson_JenkinsSpecMasterContainersLifecyclePreStopHttpGet(obj.httpGet),
'tcpSocket': toJson_JenkinsSpecMasterContainersLifecyclePreStopTcpSocket(obj.tcpSocket),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersLivenessProbeExec
*/
export interface JenkinsSpecMasterContainersLivenessProbeExec {
/**
* Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
*
* @schema JenkinsSpecMasterContainersLivenessProbeExec#command
*/
readonly command?: string[];
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLivenessProbeExec' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLivenessProbeExec(obj: JenkinsSpecMasterContainersLivenessProbeExec | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'command': obj.command?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGet
*/
export interface JenkinsSpecMasterContainersLivenessProbeHttpGet {
/**
* Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGet#host
*/
readonly host?: string;
/**
* Custom headers to set in the request. HTTP allows repeated headers.
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGet#httpHeaders
*/
readonly httpHeaders?: JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders[];
/**
* Path to access on the HTTP server.
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGet#path
*/
readonly path?: string;
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGet#port
*/
readonly port: JenkinsSpecMasterContainersLivenessProbeHttpGetPort;
/**
* Scheme to use for connecting to the host. Defaults to HTTP.
*
* @default HTTP.
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGet#scheme
*/
readonly scheme?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLivenessProbeHttpGet' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLivenessProbeHttpGet(obj: JenkinsSpecMasterContainersLivenessProbeHttpGet | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'httpHeaders': obj.httpHeaders?.map(y => toJson_JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders(y)),
'path': obj.path,
'port': obj.port?.value,
'scheme': obj.scheme,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersLivenessProbeTcpSocket
*/
export interface JenkinsSpecMasterContainersLivenessProbeTcpSocket {
/**
* Optional: Host name to connect to, defaults to the pod IP.
*
* @schema JenkinsSpecMasterContainersLivenessProbeTcpSocket#host
*/
readonly host?: string;
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLivenessProbeTcpSocket#port
*/
readonly port: JenkinsSpecMasterContainersLivenessProbeTcpSocketPort;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLivenessProbeTcpSocket' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLivenessProbeTcpSocket(obj: JenkinsSpecMasterContainersLivenessProbeTcpSocket | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'port': obj.port?.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersReadinessProbeExec
*/
export interface JenkinsSpecMasterContainersReadinessProbeExec {
/**
* Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
*
* @schema JenkinsSpecMasterContainersReadinessProbeExec#command
*/
readonly command?: string[];
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersReadinessProbeExec' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersReadinessProbeExec(obj: JenkinsSpecMasterContainersReadinessProbeExec | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'command': obj.command?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGet
*/
export interface JenkinsSpecMasterContainersReadinessProbeHttpGet {
/**
* Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGet#host
*/
readonly host?: string;
/**
* Custom headers to set in the request. HTTP allows repeated headers.
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGet#httpHeaders
*/
readonly httpHeaders?: JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders[];
/**
* Path to access on the HTTP server.
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGet#path
*/
readonly path?: string;
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGet#port
*/
readonly port: JenkinsSpecMasterContainersReadinessProbeHttpGetPort;
/**
* Scheme to use for connecting to the host. Defaults to HTTP.
*
* @default HTTP.
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGet#scheme
*/
readonly scheme?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersReadinessProbeHttpGet' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersReadinessProbeHttpGet(obj: JenkinsSpecMasterContainersReadinessProbeHttpGet | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'httpHeaders': obj.httpHeaders?.map(y => toJson_JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders(y)),
'path': obj.path,
'port': obj.port?.value,
'scheme': obj.scheme,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersReadinessProbeTcpSocket
*/
export interface JenkinsSpecMasterContainersReadinessProbeTcpSocket {
/**
* Optional: Host name to connect to, defaults to the pod IP.
*
* @schema JenkinsSpecMasterContainersReadinessProbeTcpSocket#host
*/
readonly host?: string;
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersReadinessProbeTcpSocket#port
*/
readonly port: JenkinsSpecMasterContainersReadinessProbeTcpSocketPort;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersReadinessProbeTcpSocket' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersReadinessProbeTcpSocket(obj: JenkinsSpecMasterContainersReadinessProbeTcpSocket | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'port': obj.port?.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime.
*
* @default the default set of capabilities granted by the container runtime.
* @schema JenkinsSpecMasterContainersSecurityContextCapabilities
*/
export interface JenkinsSpecMasterContainersSecurityContextCapabilities {
/**
* Added capabilities
*
* @schema JenkinsSpecMasterContainersSecurityContextCapabilities#add
*/
readonly add?: string[];
/**
* Removed capabilities
*
* @schema JenkinsSpecMasterContainersSecurityContextCapabilities#drop
*/
readonly drop?: string[];
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersSecurityContextCapabilities' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersSecurityContextCapabilities(obj: JenkinsSpecMasterContainersSecurityContextCapabilities | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'add': obj.add?.map(y => y),
'drop': obj.drop?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterContainersSecurityContextSeLinuxOptions
*/
export interface JenkinsSpecMasterContainersSecurityContextSeLinuxOptions {
/**
* Level is SELinux level label that applies to the container.
*
* @schema JenkinsSpecMasterContainersSecurityContextSeLinuxOptions#level
*/
readonly level?: string;
/**
* Role is a SELinux role label that applies to the container.
*
* @schema JenkinsSpecMasterContainersSecurityContextSeLinuxOptions#role
*/
readonly role?: string;
/**
* Type is a SELinux type label that applies to the container.
*
* @schema JenkinsSpecMasterContainersSecurityContextSeLinuxOptions#type
*/
readonly type?: string;
/**
* User is a SELinux user label that applies to the container.
*
* @schema JenkinsSpecMasterContainersSecurityContextSeLinuxOptions#user
*/
readonly user?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersSecurityContextSeLinuxOptions' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersSecurityContextSeLinuxOptions(obj: JenkinsSpecMasterContainersSecurityContextSeLinuxOptions | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'level': obj.level,
'role': obj.role,
'type': obj.type,
'user': obj.user,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The Windows specific settings applied to all containers. If unspecified, the options from the PodSecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
*
* @schema JenkinsSpecMasterContainersSecurityContextWindowsOptions
*/
export interface JenkinsSpecMasterContainersSecurityContextWindowsOptions {
/**
* GMSACredentialSpec is where the GMSA admission webhook (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the GMSA credential spec named by the GMSACredentialSpecName field. This field is alpha-level and is only honored by servers that enable the WindowsGMSA feature flag.
*
* @schema JenkinsSpecMasterContainersSecurityContextWindowsOptions#gmsaCredentialSpec
*/
readonly gmsaCredentialSpec?: string;
/**
* GMSACredentialSpecName is the name of the GMSA credential spec to use. This field is alpha-level and is only honored by servers that enable the WindowsGMSA feature flag.
*
* @schema JenkinsSpecMasterContainersSecurityContextWindowsOptions#gmsaCredentialSpecName
*/
readonly gmsaCredentialSpecName?: string;
/**
* The UserName in Windows to run the entrypoint of the container process. Defaults to the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. This field is alpha-level and it is only honored by servers that enable the WindowsRunAsUserName feature flag.
*
* @default the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. This field is alpha-level and it is only honored by servers that enable the WindowsRunAsUserName feature flag.
* @schema JenkinsSpecMasterContainersSecurityContextWindowsOptions#runAsUserName
*/
readonly runAsUserName?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersSecurityContextWindowsOptions' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersSecurityContextWindowsOptions(obj: JenkinsSpecMasterContainersSecurityContextWindowsOptions | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'gmsaCredentialSpec': obj.gmsaCredentialSpec,
'gmsaCredentialSpecName': obj.gmsaCredentialSpecName,
'runAsUserName': obj.runAsUserName,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it
*
* @schema JenkinsSpecMasterVolumesCephfsSecretRef
*/
export interface JenkinsSpecMasterVolumesCephfsSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesCephfsSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesCephfsSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesCephfsSecretRef(obj: JenkinsSpecMasterVolumesCephfsSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Optional: points to a secret object containing parameters used to connect to OpenStack.
*
* @schema JenkinsSpecMasterVolumesCinderSecretRef
*/
export interface JenkinsSpecMasterVolumesCinderSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesCinderSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesCinderSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesCinderSecretRef(obj: JenkinsSpecMasterVolumesCinderSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Maps a string key to a path within a volume.
*
* @schema JenkinsSpecMasterVolumesConfigMapItems
*/
export interface JenkinsSpecMasterVolumesConfigMapItems {
/**
* The key to project.
*
* @schema JenkinsSpecMasterVolumesConfigMapItems#key
*/
readonly key: string;
/**
* Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @schema JenkinsSpecMasterVolumesConfigMapItems#mode
*/
readonly mode?: number;
/**
* The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.
*
* @schema JenkinsSpecMasterVolumesConfigMapItems#path
*/
readonly path: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesConfigMapItems' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesConfigMapItems(obj: JenkinsSpecMasterVolumesConfigMapItems | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'mode': obj.mode,
'path': obj.path,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* NodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secret references are passed.
*
* @schema JenkinsSpecMasterVolumesCsiNodePublishSecretRef
*/
export interface JenkinsSpecMasterVolumesCsiNodePublishSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesCsiNodePublishSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesCsiNodePublishSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesCsiNodePublishSecretRef(obj: JenkinsSpecMasterVolumesCsiNodePublishSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* DownwardAPIVolumeFile represents information to create the file containing the pod field
*
* @schema JenkinsSpecMasterVolumesDownwardApiItems
*/
export interface JenkinsSpecMasterVolumesDownwardApiItems {
/**
* Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.
*
* @schema JenkinsSpecMasterVolumesDownwardApiItems#fieldRef
*/
readonly fieldRef?: JenkinsSpecMasterVolumesDownwardApiItemsFieldRef;
/**
* Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @schema JenkinsSpecMasterVolumesDownwardApiItems#mode
*/
readonly mode?: number;
/**
* Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'
*
* @schema JenkinsSpecMasterVolumesDownwardApiItems#path
*/
readonly path: string;
/**
* Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.
*
* @schema JenkinsSpecMasterVolumesDownwardApiItems#resourceFieldRef
*/
readonly resourceFieldRef?: JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesDownwardApiItems' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesDownwardApiItems(obj: JenkinsSpecMasterVolumesDownwardApiItems | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fieldRef': toJson_JenkinsSpecMasterVolumesDownwardApiItemsFieldRef(obj.fieldRef),
'mode': obj.mode,
'path': obj.path,
'resourceFieldRef': toJson_JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef(obj.resourceFieldRef),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Optional: SecretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.
*
* @schema JenkinsSpecMasterVolumesFlexVolumeSecretRef
*/
export interface JenkinsSpecMasterVolumesFlexVolumeSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesFlexVolumeSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesFlexVolumeSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesFlexVolumeSecretRef(obj: JenkinsSpecMasterVolumesFlexVolumeSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* CHAP Secret for iSCSI target and initiator authentication
*
* @schema JenkinsSpecMasterVolumesIscsiSecretRef
*/
export interface JenkinsSpecMasterVolumesIscsiSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesIscsiSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesIscsiSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesIscsiSecretRef(obj: JenkinsSpecMasterVolumesIscsiSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Projection that may be projected along with other supported volume types
*
* @schema JenkinsSpecMasterVolumesProjectedSources
*/
export interface JenkinsSpecMasterVolumesProjectedSources {
/**
* information about the configMap data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSources#configMap
*/
readonly configMap?: JenkinsSpecMasterVolumesProjectedSourcesConfigMap;
/**
* information about the downwardAPI data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSources#downwardAPI
*/
readonly downwardApi?: JenkinsSpecMasterVolumesProjectedSourcesDownwardApi;
/**
* information about the secret data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSources#secret
*/
readonly secret?: JenkinsSpecMasterVolumesProjectedSourcesSecret;
/**
* information about the serviceAccountToken data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSources#serviceAccountToken
*/
readonly serviceAccountToken?: JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSources' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSources(obj: JenkinsSpecMasterVolumesProjectedSources | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'configMap': toJson_JenkinsSpecMasterVolumesProjectedSourcesConfigMap(obj.configMap),
'downwardAPI': toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApi(obj.downwardApi),
'secret': toJson_JenkinsSpecMasterVolumesProjectedSourcesSecret(obj.secret),
'serviceAccountToken': toJson_JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken(obj.serviceAccountToken),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
*
* @default nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it
* @schema JenkinsSpecMasterVolumesRbdSecretRef
*/
export interface JenkinsSpecMasterVolumesRbdSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesRbdSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesRbdSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesRbdSecretRef(obj: JenkinsSpecMasterVolumesRbdSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail.
*
* @schema JenkinsSpecMasterVolumesScaleIoSecretRef
*/
export interface JenkinsSpecMasterVolumesScaleIoSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesScaleIoSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesScaleIoSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesScaleIoSecretRef(obj: JenkinsSpecMasterVolumesScaleIoSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Maps a string key to a path within a volume.
*
* @schema JenkinsSpecMasterVolumesSecretItems
*/
export interface JenkinsSpecMasterVolumesSecretItems {
/**
* The key to project.
*
* @schema JenkinsSpecMasterVolumesSecretItems#key
*/
readonly key: string;
/**
* Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @schema JenkinsSpecMasterVolumesSecretItems#mode
*/
readonly mode?: number;
/**
* The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.
*
* @schema JenkinsSpecMasterVolumesSecretItems#path
*/
readonly path: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesSecretItems' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesSecretItems(obj: JenkinsSpecMasterVolumesSecretItems | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'mode': obj.mode,
'path': obj.path,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* SecretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted.
*
* @schema JenkinsSpecMasterVolumesStorageosSecretRef
*/
export interface JenkinsSpecMasterVolumesStorageosSecretRef {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesStorageosSecretRef#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesStorageosSecretRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesStorageosSecretRef(obj: JenkinsSpecMasterVolumesStorageosSecretRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret
*/
export interface JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret(obj: JenkinsSpecNotificationsMailgunApiKeySecretKeySelectorSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret
*/
export interface JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret(obj: JenkinsSpecNotificationsSlackWebHookUrlSecretKeySelectorSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret
*/
export interface JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret(obj: JenkinsSpecNotificationsSmtpPasswordSecretKeySelectorSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret
*/
export interface JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret(obj: JenkinsSpecNotificationsSmtpUsernameSecretKeySelectorSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* The name of the secret in the pod's namespace to select from.
*
* @schema JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret
*/
export interface JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret {
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret#name
*/
readonly name?: string;
}
/**
* Converts an object of type 'JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret(obj: JenkinsSpecNotificationsTeamsWebHookUrlSecretKeySelectorSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Selects a key of a ConfigMap.
*
* @schema JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef
*/
export interface JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef {
/**
* The key to select.
*
* @schema JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef#key
*/
readonly key: string;
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef#name
*/
readonly name?: string;
/**
* Specify whether the ConfigMap or its key must be defined
*
* @schema JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef#optional
*/
readonly optional?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef(obj: JenkinsSpecMasterContainersEnvValueFromConfigMapKeyRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'name': obj.name,
'optional': obj.optional,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP.
*
* @schema JenkinsSpecMasterContainersEnvValueFromFieldRef
*/
export interface JenkinsSpecMasterContainersEnvValueFromFieldRef {
/**
* Version of the schema the FieldPath is written in terms of, defaults to "v1".
*
* @schema JenkinsSpecMasterContainersEnvValueFromFieldRef#apiVersion
*/
readonly apiVersion?: string;
/**
* Path of the field to select in the specified API version.
*
* @schema JenkinsSpecMasterContainersEnvValueFromFieldRef#fieldPath
*/
readonly fieldPath: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvValueFromFieldRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvValueFromFieldRef(obj: JenkinsSpecMasterContainersEnvValueFromFieldRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'apiVersion': obj.apiVersion,
'fieldPath': obj.fieldPath,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported.
*
* @schema JenkinsSpecMasterContainersEnvValueFromResourceFieldRef
*/
export interface JenkinsSpecMasterContainersEnvValueFromResourceFieldRef {
/**
* Container name: required for volumes, optional for env vars
*
* @schema JenkinsSpecMasterContainersEnvValueFromResourceFieldRef#containerName
*/
readonly containerName?: string;
/**
* Specifies the output format of the exposed resources, defaults to "1"
*
* @schema JenkinsSpecMasterContainersEnvValueFromResourceFieldRef#divisor
*/
readonly divisor?: string;
/**
* Required: resource to select
*
* @schema JenkinsSpecMasterContainersEnvValueFromResourceFieldRef#resource
*/
readonly resource: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvValueFromResourceFieldRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvValueFromResourceFieldRef(obj: JenkinsSpecMasterContainersEnvValueFromResourceFieldRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'containerName': obj.containerName,
'divisor': obj.divisor,
'resource': obj.resource,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Selects a key of a secret in the pod's namespace
*
* @schema JenkinsSpecMasterContainersEnvValueFromSecretKeyRef
*/
export interface JenkinsSpecMasterContainersEnvValueFromSecretKeyRef {
/**
* The key of the secret to select from. Must be a valid secret key.
*
* @schema JenkinsSpecMasterContainersEnvValueFromSecretKeyRef#key
*/
readonly key: string;
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterContainersEnvValueFromSecretKeyRef#name
*/
readonly name?: string;
/**
* Specify whether the Secret or its key must be defined
*
* @schema JenkinsSpecMasterContainersEnvValueFromSecretKeyRef#optional
*/
readonly optional?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersEnvValueFromSecretKeyRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersEnvValueFromSecretKeyRef(obj: JenkinsSpecMasterContainersEnvValueFromSecretKeyRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'name': obj.name,
'optional': obj.optional,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartExec
*/
export interface JenkinsSpecMasterContainersLifecyclePostStartExec {
/**
* Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartExec#command
*/
readonly command?: string[];
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePostStartExec' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePostStartExec(obj: JenkinsSpecMasterContainersLifecyclePostStartExec | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'command': obj.command?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGet
*/
export interface JenkinsSpecMasterContainersLifecyclePostStartHttpGet {
/**
* Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGet#host
*/
readonly host?: string;
/**
* Custom headers to set in the request. HTTP allows repeated headers.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGet#httpHeaders
*/
readonly httpHeaders?: JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders[];
/**
* Path to access on the HTTP server.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGet#path
*/
readonly path?: string;
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGet#port
*/
readonly port: JenkinsSpecMasterContainersLifecyclePostStartHttpGetPort;
/**
* Scheme to use for connecting to the host. Defaults to HTTP.
*
* @default HTTP.
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGet#scheme
*/
readonly scheme?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePostStartHttpGet' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePostStartHttpGet(obj: JenkinsSpecMasterContainersLifecyclePostStartHttpGet | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'httpHeaders': obj.httpHeaders?.map(y => toJson_JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders(y)),
'path': obj.path,
'port': obj.port?.value,
'scheme': obj.scheme,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartTcpSocket
*/
export interface JenkinsSpecMasterContainersLifecyclePostStartTcpSocket {
/**
* Optional: Host name to connect to, defaults to the pod IP.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartTcpSocket#host
*/
readonly host?: string;
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartTcpSocket#port
*/
readonly port: JenkinsSpecMasterContainersLifecyclePostStartTcpSocketPort;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePostStartTcpSocket' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePostStartTcpSocket(obj: JenkinsSpecMasterContainersLifecyclePostStartTcpSocket | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'port': obj.port?.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* One and only one of the following should be specified. Exec specifies the action to take.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopExec
*/
export interface JenkinsSpecMasterContainersLifecyclePreStopExec {
/**
* Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopExec#command
*/
readonly command?: string[];
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePreStopExec' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePreStopExec(obj: JenkinsSpecMasterContainersLifecyclePreStopExec | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'command': obj.command?.map(y => y),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* HTTPGet specifies the http request to perform.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGet
*/
export interface JenkinsSpecMasterContainersLifecyclePreStopHttpGet {
/**
* Host name to connect to, defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGet#host
*/
readonly host?: string;
/**
* Custom headers to set in the request. HTTP allows repeated headers.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGet#httpHeaders
*/
readonly httpHeaders?: JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders[];
/**
* Path to access on the HTTP server.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGet#path
*/
readonly path?: string;
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGet#port
*/
readonly port: JenkinsSpecMasterContainersLifecyclePreStopHttpGetPort;
/**
* Scheme to use for connecting to the host. Defaults to HTTP.
*
* @default HTTP.
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGet#scheme
*/
readonly scheme?: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePreStopHttpGet' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePreStopHttpGet(obj: JenkinsSpecMasterContainersLifecyclePreStopHttpGet | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'httpHeaders': obj.httpHeaders?.map(y => toJson_JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders(y)),
'path': obj.path,
'port': obj.port?.value,
'scheme': obj.scheme,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported TODO: implement a realistic TCP lifecycle hook
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopTcpSocket
*/
export interface JenkinsSpecMasterContainersLifecyclePreStopTcpSocket {
/**
* Optional: Host name to connect to, defaults to the pod IP.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopTcpSocket#host
*/
readonly host?: string;
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopTcpSocket#port
*/
readonly port: JenkinsSpecMasterContainersLifecyclePreStopTcpSocketPort;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePreStopTcpSocket' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePreStopTcpSocket(obj: JenkinsSpecMasterContainersLifecyclePreStopTcpSocket | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'host': obj.host,
'port': obj.port?.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* HTTPHeader describes a custom header to be used in HTTP probes
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders
*/
export interface JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders {
/**
* The header field name
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders#name
*/
readonly name: string;
/**
* The header field value
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders#value
*/
readonly value: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders(obj: JenkinsSpecMasterContainersLivenessProbeHttpGetHttpHeaders | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'value': obj.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLivenessProbeHttpGetPort
*/
export class JenkinsSpecMasterContainersLivenessProbeHttpGetPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersLivenessProbeHttpGetPort {
return new JenkinsSpecMasterContainersLivenessProbeHttpGetPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersLivenessProbeHttpGetPort {
return new JenkinsSpecMasterContainersLivenessProbeHttpGetPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLivenessProbeTcpSocketPort
*/
export class JenkinsSpecMasterContainersLivenessProbeTcpSocketPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersLivenessProbeTcpSocketPort {
return new JenkinsSpecMasterContainersLivenessProbeTcpSocketPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersLivenessProbeTcpSocketPort {
return new JenkinsSpecMasterContainersLivenessProbeTcpSocketPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* HTTPHeader describes a custom header to be used in HTTP probes
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders
*/
export interface JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders {
/**
* The header field name
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders#name
*/
readonly name: string;
/**
* The header field value
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders#value
*/
readonly value: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders(obj: JenkinsSpecMasterContainersReadinessProbeHttpGetHttpHeaders | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'value': obj.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersReadinessProbeHttpGetPort
*/
export class JenkinsSpecMasterContainersReadinessProbeHttpGetPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersReadinessProbeHttpGetPort {
return new JenkinsSpecMasterContainersReadinessProbeHttpGetPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersReadinessProbeHttpGetPort {
return new JenkinsSpecMasterContainersReadinessProbeHttpGetPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersReadinessProbeTcpSocketPort
*/
export class JenkinsSpecMasterContainersReadinessProbeTcpSocketPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersReadinessProbeTcpSocketPort {
return new JenkinsSpecMasterContainersReadinessProbeTcpSocketPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersReadinessProbeTcpSocketPort {
return new JenkinsSpecMasterContainersReadinessProbeTcpSocketPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.
*
* @schema JenkinsSpecMasterVolumesDownwardApiItemsFieldRef
*/
export interface JenkinsSpecMasterVolumesDownwardApiItemsFieldRef {
/**
* Version of the schema the FieldPath is written in terms of, defaults to "v1".
*
* @schema JenkinsSpecMasterVolumesDownwardApiItemsFieldRef#apiVersion
*/
readonly apiVersion?: string;
/**
* Path of the field to select in the specified API version.
*
* @schema JenkinsSpecMasterVolumesDownwardApiItemsFieldRef#fieldPath
*/
readonly fieldPath: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesDownwardApiItemsFieldRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesDownwardApiItemsFieldRef(obj: JenkinsSpecMasterVolumesDownwardApiItemsFieldRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'apiVersion': obj.apiVersion,
'fieldPath': obj.fieldPath,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.
*
* @schema JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef
*/
export interface JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef {
/**
* Container name: required for volumes, optional for env vars
*
* @schema JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef#containerName
*/
readonly containerName?: string;
/**
* Specifies the output format of the exposed resources, defaults to "1"
*
* @schema JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef#divisor
*/
readonly divisor?: string;
/**
* Required: resource to select
*
* @schema JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef#resource
*/
readonly resource: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef(obj: JenkinsSpecMasterVolumesDownwardApiItemsResourceFieldRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'containerName': obj.containerName,
'divisor': obj.divisor,
'resource': obj.resource,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* information about the configMap data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMap
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesConfigMap {
/**
* If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMap#items
*/
readonly items?: JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems[];
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMap#name
*/
readonly name?: string;
/**
* Specify whether the ConfigMap or its keys must be defined
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMap#optional
*/
readonly optional?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesConfigMap' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesConfigMap(obj: JenkinsSpecMasterVolumesProjectedSourcesConfigMap | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'items': obj.items?.map(y => toJson_JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems(y)),
'name': obj.name,
'optional': obj.optional,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* information about the downwardAPI data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApi
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesDownwardApi {
/**
* Items is a list of DownwardAPIVolume file
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApi#items
*/
readonly items?: JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems[];
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesDownwardApi' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApi(obj: JenkinsSpecMasterVolumesProjectedSourcesDownwardApi | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'items': obj.items?.map(y => toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems(y)),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* information about the secret data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecret
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesSecret {
/**
* If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecret#items
*/
readonly items?: JenkinsSpecMasterVolumesProjectedSourcesSecretItems[];
/**
* Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecret#name
*/
readonly name?: string;
/**
* Specify whether the Secret or its key must be defined
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecret#optional
*/
readonly optional?: boolean;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesSecret' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesSecret(obj: JenkinsSpecMasterVolumesProjectedSourcesSecret | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'items': obj.items?.map(y => toJson_JenkinsSpecMasterVolumesProjectedSourcesSecretItems(y)),
'name': obj.name,
'optional': obj.optional,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* information about the serviceAccountToken data to project
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken {
/**
* Audience is the intended audience of the token. A recipient of a token must identify itself with an identifier specified in the audience of the token, and otherwise should reject the token. The audience defaults to the identifier of the apiserver.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken#audience
*/
readonly audience?: string;
/**
* ExpirationSeconds is the requested duration of validity of the service account token. As the token approaches expiration, the kubelet volume plugin will proactively rotate the service account token. The kubelet will start trying to rotate the token if the token is older than 80 percent of its time to live or if the token is older than 24 hours.Defaults to 1 hour and must be at least 10 minutes.
*
* @default 1 hour and must be at least 10 minutes.
* @schema JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken#expirationSeconds
*/
readonly expirationSeconds?: number;
/**
* Path is the path relative to the mount point of the file to project the token into.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken#path
*/
readonly path: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken(obj: JenkinsSpecMasterVolumesProjectedSourcesServiceAccountToken | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'audience': obj.audience,
'expirationSeconds': obj.expirationSeconds,
'path': obj.path,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* HTTPHeader describes a custom header to be used in HTTP probes
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders
*/
export interface JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders {
/**
* The header field name
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders#name
*/
readonly name: string;
/**
* The header field value
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders#value
*/
readonly value: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders(obj: JenkinsSpecMasterContainersLifecyclePostStartHttpGetHttpHeaders | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'value': obj.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartHttpGetPort
*/
export class JenkinsSpecMasterContainersLifecyclePostStartHttpGetPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersLifecyclePostStartHttpGetPort {
return new JenkinsSpecMasterContainersLifecyclePostStartHttpGetPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersLifecyclePostStartHttpGetPort {
return new JenkinsSpecMasterContainersLifecyclePostStartHttpGetPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePostStartTcpSocketPort
*/
export class JenkinsSpecMasterContainersLifecyclePostStartTcpSocketPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersLifecyclePostStartTcpSocketPort {
return new JenkinsSpecMasterContainersLifecyclePostStartTcpSocketPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersLifecyclePostStartTcpSocketPort {
return new JenkinsSpecMasterContainersLifecyclePostStartTcpSocketPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* HTTPHeader describes a custom header to be used in HTTP probes
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders
*/
export interface JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders {
/**
* The header field name
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders#name
*/
readonly name: string;
/**
* The header field value
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders#value
*/
readonly value: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders(obj: JenkinsSpecMasterContainersLifecyclePreStopHttpGetHttpHeaders | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'name': obj.name,
'value': obj.value,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopHttpGetPort
*/
export class JenkinsSpecMasterContainersLifecyclePreStopHttpGetPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersLifecyclePreStopHttpGetPort {
return new JenkinsSpecMasterContainersLifecyclePreStopHttpGetPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersLifecyclePreStopHttpGetPort {
return new JenkinsSpecMasterContainersLifecyclePreStopHttpGetPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.
*
* @schema JenkinsSpecMasterContainersLifecyclePreStopTcpSocketPort
*/
export class JenkinsSpecMasterContainersLifecyclePreStopTcpSocketPort {
public static fromNumber(value: number): JenkinsSpecMasterContainersLifecyclePreStopTcpSocketPort {
return new JenkinsSpecMasterContainersLifecyclePreStopTcpSocketPort(value);
}
public static fromString(value: string): JenkinsSpecMasterContainersLifecyclePreStopTcpSocketPort {
return new JenkinsSpecMasterContainersLifecyclePreStopTcpSocketPort(value);
}
private constructor(public readonly value: any) {
}
}
/**
* Maps a string key to a path within a volume.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems {
/**
* The key to project.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems#key
*/
readonly key: string;
/**
* Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems#mode
*/
readonly mode?: number;
/**
* The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems#path
*/
readonly path: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems(obj: JenkinsSpecMasterVolumesProjectedSourcesConfigMapItems | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'mode': obj.mode,
'path': obj.path,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* DownwardAPIVolumeFile represents information to create the file containing the pod field
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems {
/**
* Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems#fieldRef
*/
readonly fieldRef?: JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef;
/**
* Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems#mode
*/
readonly mode?: number;
/**
* Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems#path
*/
readonly path: string;
/**
* Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems#resourceFieldRef
*/
readonly resourceFieldRef?: JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems(obj: JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItems | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'fieldRef': toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef(obj.fieldRef),
'mode': obj.mode,
'path': obj.path,
'resourceFieldRef': toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef(obj.resourceFieldRef),
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Maps a string key to a path within a volume.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecretItems
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesSecretItems {
/**
* The key to project.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecretItems#key
*/
readonly key: string;
/**
* Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecretItems#mode
*/
readonly mode?: number;
/**
* The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesSecretItems#path
*/
readonly path: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesSecretItems' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesSecretItems(obj: JenkinsSpecMasterVolumesProjectedSourcesSecretItems | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'key': obj.key,
'mode': obj.mode,
'path': obj.path,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef {
/**
* Version of the schema the FieldPath is written in terms of, defaults to "v1".
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef#apiVersion
*/
readonly apiVersion?: string;
/**
* Path of the field to select in the specified API version.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef#fieldPath
*/
readonly fieldPath: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef(obj: JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsFieldRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'apiVersion': obj.apiVersion,
'fieldPath': obj.fieldPath,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */
/**
* Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef
*/
export interface JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef {
/**
* Container name: required for volumes, optional for env vars
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef#containerName
*/
readonly containerName?: string;
/**
* Specifies the output format of the exposed resources, defaults to "1"
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef#divisor
*/
readonly divisor?: string;
/**
* Required: resource to select
*
* @schema JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef#resource
*/
readonly resource: string;
}
/**
* Converts an object of type 'JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef' to JSON representation.
*/
/* eslint-disable max-len, quote-props */
export function toJson_JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef(obj: JenkinsSpecMasterVolumesProjectedSourcesDownwardApiItemsResourceFieldRef | undefined): Record<string, any> | undefined {
if (obj === undefined) { return undefined; }
const result = {
'containerName': obj.containerName,
'divisor': obj.divisor,
'resource': obj.resource,
};
// filter undefined values
return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
}
/* eslint-enable max-len, quote-props */ | the_stack |
import { TextStyleDefinition } from "@here/harp-datasource-protocol";
import { expect } from "chai";
import * as sinon from "sinon";
import * as THREE from "three";
import { TextElement } from "../lib/text/TextElement";
import { DEFAULT_FONT_CATALOG_NAME } from "../lib/text/TextElementsRenderer";
import { TextElementType } from "../lib/text/TextElementType";
import { PoiInfoBuilder } from "./PoiInfoBuilder";
import {
createPath,
DEF_PATH,
lineMarkerBuilder,
pathTextBuilder,
poiBuilder,
pointTextBuilder
} from "./TextElementBuilder";
import {
DEF_TEXT_HEIGHT,
DEF_TEXT_WIDTH,
SCREEN_HEIGHT,
SCREEN_WIDTH,
TestFixture,
WORLD_SCALE
} from "./TextElementsRendererTestFixture";
import {
builder,
FADE_2_CYCLES,
FADE_CYCLE,
FADE_IN,
FADE_IN_OUT,
FADE_OUT,
fadedIn,
fadedOut,
fadeIn,
fadeInAndFadedOut,
FadeState,
firstNFrames,
framesEnabled,
frameStates,
iconFrameStates,
INITIAL_TIME,
InputTextElement,
InputTile,
not
} from "./TextElementsRendererTestUtils";
// Mocha discourages using arrow functions, see https://mochajs.org/#arrow-functions
/**
* Definition of a test case for TextElementsRenderer, including input data (tiles, text elements,
* frame times...) and expected output (text element fade states at each frame).
*/
interface TestCase {
// Name of the test.
name: string;
// Input tiles.
tiles: InputTile[];
// Time in ms when each frame starts.
frameTimes: number[];
// For each frame, true if collision test is enabled, false otherwise. By default, collision
// test is enabled for all frames. Facilitates the setup of collision scenarios without changing
// camera settings.
collisionFrames?: boolean[];
}
const tests: TestCase[] = [
// SINGLE LABEL TEST CASES
{
name: "Newly visited, visible point text fades in",
tiles: [{ labels: [[pointTextBuilder(), FADE_IN]] }],
frameTimes: FADE_CYCLE
},
{
name: "Newly visited, visible poi fades in",
tiles: [{ labels: [[poiBuilder(), FADE_IN]] }],
frameTimes: FADE_CYCLE
},
{
name: "Newly visited, visible line marker fades in",
tiles: [{ labels: [[lineMarkerBuilder(WORLD_SCALE), [FADE_IN, FADE_IN], [], []]] }],
frameTimes: FADE_CYCLE
},
{
name: "Newly visited, visible path text fades in",
tiles: [{ labels: [[pathTextBuilder(WORLD_SCALE), FADE_IN]] }],
frameTimes: FADE_CYCLE
},
{
name: "Non-visited, persistent point text is not rendered",
tiles: [
{
labels: [[pointTextBuilder(), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Non-visited, persistent poi is not rendered",
tiles: [
{
labels: [[poiBuilder(), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Non-visited, persistent line marker is not rendered",
tiles: [
{
labels: [
[
lineMarkerBuilder(WORLD_SCALE),
[
fadeInAndFadedOut(FADE_2_CYCLES.length),
fadeInAndFadedOut(FADE_2_CYCLES.length)
],
[],
[]
]
],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Non-visited, persistent path text is not rendered",
tiles: [
{
labels: [[pathTextBuilder(WORLD_SCALE), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
}
],
frameTimes: FADE_2_CYCLES
},
// TRANSITORY LABEL GROUPS (ADDED/REMOVED AFTER FIRST FRAME).
{
name: "Poi added after first frames fades in",
tiles: [
{
labels: [
[
poiBuilder(),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
),
not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
]
]
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Two pois added in different frames to same tile fade in",
tiles: [
{
labels: [
[
poiBuilder("Marker 1")
.withMayOverlap(true)
.withPoiInfo(new PoiInfoBuilder().withMayOverlap(true)),
fadedOut(2).concat(fadeIn(FADE_2_CYCLES.length - 2)),
not(firstNFrames(FADE_2_CYCLES, 2))
],
[
poiBuilder("Marker 2")
.withMayOverlap(true)
.withPoiInfo(new PoiInfoBuilder().withMayOverlap(true)),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
),
not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
]
]
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Removed poi fades out",
tiles: [
{
labels: [
[
poiBuilder(),
FADE_IN.concat(fadedOut(FADE_2_CYCLES.length - FADE_IN.length)),
firstNFrames(FADE_2_CYCLES, FADE_IN.length)
]
]
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "From two pois in same tile, removed poi fades out, remaining poi is faded in",
tiles: [
{
labels: [
[
poiBuilder("Marker 1")
.withMayOverlap(true)
.withPoiInfo(new PoiInfoBuilder().withMayOverlap(true)),
fadeIn(FADE_2_CYCLES.length)
],
[
poiBuilder("Marker 2")
.withMayOverlap(true)
.withPoiInfo(new PoiInfoBuilder().withMayOverlap(true)),
FADE_IN.concat(fadedOut(FADE_2_CYCLES.length - FADE_IN.length)),
firstNFrames(FADE_2_CYCLES, FADE_IN.length)
]
]
}
],
frameTimes: FADE_2_CYCLES
},
// LABEL COLLISIONS
{
name: "Least prioritized from two colliding persistent point texts fades out",
tiles: [
{
labels: [
[pointTextBuilder("P0").withPriority(0), FADE_IN_OUT],
[pointTextBuilder("P1").withPriority(1), fadeIn(FADE_IN_OUT.length)]
]
}
],
frameTimes: FADE_2_CYCLES,
collisionFrames: not(firstNFrames(FADE_2_CYCLES, 3))
},
{
name: "Least prioritized from two colliding persistent pois fades out",
tiles: [
{
labels: [
[poiBuilder("P0").withPriority(0), FADE_IN_OUT],
[poiBuilder("P1").withPriority(1), fadeIn(FADE_IN_OUT.length)]
]
}
],
frameTimes: FADE_2_CYCLES,
collisionFrames: not(firstNFrames(FADE_2_CYCLES, 3))
},
{
// TODO: HARP-7649. Add fade out transitions for path labels.
name: "Least prioritized from two colliding persistent path texts fades out",
tiles: [
{
labels: [
[
pathTextBuilder(WORLD_SCALE, "P0").withPriority(0),
FADE_IN.slice(0, -1).concat(fadedOut(FADE_OUT.length + 1)) /*FADE_IN_OUT*/
],
[pathTextBuilder(WORLD_SCALE, "P1").withPriority(1), fadeIn(FADE_IN_OUT.length)]
]
}
],
frameTimes: FADE_2_CYCLES,
collisionFrames: not(firstNFrames(FADE_2_CYCLES, 3))
},
{
name: "Least prioritized from two colliding persistent line markers fades out",
tiles: [
{
labels: [
[
lineMarkerBuilder(WORLD_SCALE, "P0").withPriority(0),
[FADE_IN_OUT, FADE_IN_OUT],
[],
[]
],
[
lineMarkerBuilder(WORLD_SCALE, "P1").withPriority(1),
[fadeIn(FADE_IN_OUT.length), fadeIn(FADE_IN_OUT.length)],
[],
[]
]
]
}
],
frameTimes: FADE_2_CYCLES,
collisionFrames: not(firstNFrames(FADE_2_CYCLES, 3))
},
{
name: "Least prioritized from two persistent pois colliding on text fades out",
tiles: [
{
labels: [
[
poiBuilder("P0")
.withPriority(0)
.withPoiInfo(
new PoiInfoBuilder()
.withPoiTechnique()
.withIconOffset(SCREEN_WIDTH * 0.25, 0)
),
FADE_IN_OUT
],
[
poiBuilder("P1")
.withPriority(1)
.withPoiInfo(
new PoiInfoBuilder()
.withPoiTechnique()
.withIconOffset(-SCREEN_WIDTH * 0.25, 0)
),
fadeIn(FADE_IN_OUT.length)
]
]
}
],
frameTimes: FADE_2_CYCLES,
collisionFrames: not(firstNFrames(FADE_2_CYCLES, 3))
},
{
name: "Text is rendered although icon is invisible",
tiles: [
{
labels: [
[
poiBuilder("P0")
.withPriority(0)
.withPosition(
SCREEN_WIDTH / WORLD_SCALE / 2,
SCREEN_HEIGHT / WORLD_SCALE / 2
)
.withPoiInfo(
new PoiInfoBuilder()
.withPoiTechnique()
.withIconOffset(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5 + 10)
.withIconOptional(false)
),
fadeIn(FADE_IN_OUT.length),
[],
fadedOut(FADE_IN_OUT.length)
]
]
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Text is not rendered because the valid icon is rejected",
tiles: [
{
labels: [
[
poiBuilder("P1")
.withPriority(1)
.withPosition(0, 0)
.withPoiInfo(
new PoiInfoBuilder().withPoiTechnique().withIconOptional(false)
)
.withOffset(0, 20),
fadeIn(FADE_IN_OUT.length),
[],
fadeIn(FADE_IN_OUT.length)
],
[
poiBuilder("P0")
.withPriority(0)
// Manual testing and debugging showed that this position lets the icon
// area be covered by the first poi, while the text area is available.
.withPosition(0, 5)
.withPoiInfo(
new PoiInfoBuilder().withPoiTechnique().withIconOptional(false)
)
.withOffset(0, 20),
fadedOut(FADE_IN_OUT.length),
[],
fadedOut(FADE_IN_OUT.length)
]
]
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Text is rendered because the invalid and optional icon is rejected",
tiles: [
{
labels: [
[
poiBuilder("P1")
.withPriority(1)
.withPosition(0, 0)
.withPoiInfo(
new PoiInfoBuilder().withPoiTechnique().withIconOptional(false)
)
.withOffset(0, 20),
fadeIn(FADE_IN_OUT.length),
[],
fadeIn(FADE_IN_OUT.length)
],
[
poiBuilder("P0")
.withPriority(0)
// Manual testing and debugging showed that this position lets the icon
// area be covered by the first poi, while the text area is available.
// Same values as in test above.
.withPosition(0, 5)
.withPoiInfo(
new PoiInfoBuilder()
.withPoiTechnique()
.withIconOptional(true)
.withIconValid(false)
)
.withOffset(0, 20),
fadeIn(FADE_IN_OUT.length), // text should fade in
[],
fadedOut(FADE_IN_OUT.length) // icon should stay faded out
]
]
}
],
frameTimes: FADE_2_CYCLES
},
// DEDUPLICATION
{
name: "Second from two near, non-colliding point labels with same text never fades in",
tiles: [
{
labels: [
[
pointTextBuilder().withPosition(
(WORLD_SCALE * (4 * DEF_TEXT_WIDTH)) / SCREEN_WIDTH,
(WORLD_SCALE * (4 * DEF_TEXT_HEIGHT)) / SCREEN_HEIGHT
),
fadeIn(FADE_IN_OUT.length)
],
[pointTextBuilder(), fadedOut(FADE_IN_OUT.length)]
]
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Second from two near, non-colliding pois with same text never fades in",
tiles: [
{
labels: [
[
poiBuilder().withPosition(
(WORLD_SCALE * (4 * DEF_TEXT_WIDTH)) / SCREEN_WIDTH,
(WORLD_SCALE * (4 * DEF_TEXT_HEIGHT)) / SCREEN_HEIGHT
),
fadeIn(FADE_IN_OUT.length)
],
[poiBuilder(), fadedOut(FADE_IN_OUT.length)]
]
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Second from two pois with same text but far away is not a duplicate, so it fades in",
tiles: [
{
labels: [
[
poiBuilder().withPosition(WORLD_SCALE, WORLD_SCALE),
fadeIn(FADE_IN_OUT.length)
],
[poiBuilder(), fadeIn(FADE_IN_OUT.length)]
]
}
],
frameTimes: FADE_2_CYCLES
},
// PERSISTENCY ACROSS ZOOM LEVELS
{
name: "Poi replaces predecessor with same text and feature id without fading",
tiles: [
{
labels: [[poiBuilder().withFeatureId(1), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
},
{
labels: [
[
// location of replacement is disregarded when feature ids match.
poiBuilder().withFeatureId(1).withPosition(WORLD_SCALE, WORLD_SCALE),
fadedOut(FADE_IN.length).concat(
fadedIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
frames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Poi with same feature id but different text is not a replacement, so it fades in",
tiles: [
{
labels: [
[poiBuilder("A").withFeatureId(1), fadeInAndFadedOut(FADE_2_CYCLES.length)]
],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
},
{
labels: [
[
poiBuilder("B").withFeatureId(1),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
frames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Poi with same text but different feature id is not a replacement, so it fades in",
tiles: [
{
labels: [[poiBuilder().withFeatureId(1), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
},
{
labels: [
[
poiBuilder().withFeatureId(2),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
frames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Poi replaces predecessor with same text and nearby location without fading",
tiles: [
{
labels: [[poiBuilder(), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
},
{
labels: [
[
poiBuilder().withPosition(5, 0),
fadedOut(FADE_IN.length).concat(
fadedIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
frames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Poi with same text but far away location is not a replacement, so it fades in",
tiles: [
{
labels: [[poiBuilder(), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
},
{
labels: [
[
poiBuilder().withPosition(WORLD_SCALE, 0),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
frames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name:
"Longest path label with same text within distance tolerance replaces predecessor" +
" without fading",
tiles: [
{
labels: [[pathTextBuilder(WORLD_SCALE), fadeInAndFadedOut(FADE_2_CYCLES.length)]],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
},
{
labels: [
[
pathTextBuilder(WORLD_SCALE)
.withPathLengthSqr(10)
.withPath(
DEF_PATH.map((point: THREE.Vector3) =>
point
.clone()
.multiplyScalar(WORLD_SCALE)
.add(new THREE.Vector3(8, 0, 0))
)
),
fadedOut(FADE_IN.length).concat(
fadedOut(FADE_2_CYCLES.length - FADE_IN.length)
)
],
[
pathTextBuilder(WORLD_SCALE)
.withPathLengthSqr(50)
.withPath(
DEF_PATH.map((point: THREE.Vector3) =>
point
.clone()
.multiplyScalar(WORLD_SCALE)
.add(new THREE.Vector3(0, 8, 0))
)
),
fadedOut(FADE_IN.length).concat(
fadedIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
frames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Line marker replaces predecessor with same text and nearby location without fading",
tiles: [
{
labels: [
[
lineMarkerBuilder(WORLD_SCALE).withPath(
createPath(WORLD_SCALE, [
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0.3, 0.3, 0),
new THREE.Vector3(0.6, 0.6, 0)
])
),
[
fadeInAndFadedOut(FADE_2_CYCLES.length),
fadeInAndFadedOut(FADE_2_CYCLES.length),
fadeInAndFadedOut(FADE_2_CYCLES.length)
],
[], // all frames enabled
[] // same frame states for icons and text.
]
],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
},
{
labels: [
[
lineMarkerBuilder(WORLD_SCALE).withPath(
createPath(WORLD_SCALE, [
new THREE.Vector3(0.3, 0.3, 0),
new THREE.Vector3(0.9, 0.9, 0)
])
),
[
fadedOut(FADE_IN.length).concat(
fadedIn(FADE_2_CYCLES.length - FADE_IN.length)
),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
],
[], // all frames enabled
[] // same frame states for icons and text.
]
],
frames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
// TERRAIN OVERLAY TEST CASES
{
name: "Point text only fades in when terrain is available",
tiles: [
{
labels: [
[
pointTextBuilder(),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
terrainFrames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Poi only fades in when terrain is available",
tiles: [
{
labels: [
[
poiBuilder(),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
terrainFrames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Line marker only fades in when terrain is available",
tiles: [
{
labels: [
[
lineMarkerBuilder(WORLD_SCALE),
[
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
],
[],
[]
]
],
terrainFrames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Path text only fades in when terrain is available",
tiles: [
{
labels: [
[
pathTextBuilder(WORLD_SCALE),
fadedOut(FADE_IN.length).concat(
fadeIn(FADE_2_CYCLES.length - FADE_IN.length)
)
]
],
terrainFrames: not(firstNFrames(FADE_2_CYCLES, FADE_IN.length))
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Poi only fades in, if its inside frustum",
tiles: [
{
labels: [
[
poiBuilder("outside frustum marker").withPosition(
(WORLD_SCALE * (4 * DEF_TEXT_WIDTH)) / SCREEN_WIDTH,
(WORLD_SCALE * (40 * DEF_TEXT_HEIGHT)) / SCREEN_HEIGHT,
-WORLD_SCALE * 10
),
fadedOut(FADE_2_CYCLES.length)
]
],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
}
],
frameTimes: FADE_2_CYCLES
},
{
name: "Poi only fades in, if in front of camera",
tiles: [
{
labels: [
[
poiBuilder("behind camera marker").withPosition(
(WORLD_SCALE * (4 * DEF_TEXT_WIDTH)) / SCREEN_WIDTH,
(WORLD_SCALE * (4 * DEF_TEXT_HEIGHT)) / SCREEN_HEIGHT,
-1
),
fadedOut(FADE_2_CYCLES.length)
]
],
frames: firstNFrames(FADE_2_CYCLES, FADE_IN.length)
}
],
frameTimes: FADE_2_CYCLES
}
];
describe("TextElementsRenderer", function () {
const inNodeContext = typeof window === "undefined";
let fixture: TestFixture;
const sandbox = sinon.createSandbox();
beforeEach(async function () {
if (inNodeContext) {
(global as any).window = { location: { href: "http://harp.gl" } };
}
fixture = new TestFixture(sandbox);
await fixture.setUp();
});
afterEach(function () {
sandbox.restore();
if (inNodeContext) {
delete (global as any).window;
}
});
type ElementFrameStates = Array<[TextElement, FadeState[][], FadeState[][] | undefined]>;
function buildLabels(
inputElements: InputTextElement[] | undefined,
elementFrameStates: ElementFrameStates,
frameCount: number
): TextElement[] {
if (!inputElements) {
return [];
}
return inputElements.map((inputElement: InputTextElement) => {
let textFrameStates = frameStates(inputElement);
let iconStates = iconFrameStates(inputElement);
expect(textFrameStates).not.empty;
if (!Array.isArray(textFrameStates[0])) {
textFrameStates = [textFrameStates as FadeState[]];
if (iconStates !== undefined) {
iconStates = [iconStates as FadeState[]];
}
} else if (iconStates && iconStates.length > 0) {
expect(iconStates).has.lengthOf(textFrameStates.length);
}
textFrameStates.forEach((e: any) =>
expect(e).lengthOf(frameCount, "one state per frame required")
);
iconStates?.forEach((e: any) =>
expect(e).lengthOf(frameCount, "one state per frame required")
);
// Only used to identify some text elements for testing purposes.
const dummyUserData = {};
const element = builder(inputElement).withUserData(dummyUserData).build();
elementFrameStates.push([
element,
textFrameStates as FadeState[][],
iconStates as FadeState[][]
]);
return element;
});
}
async function initTest(
test: TestCase
): Promise<{
elementFrameStates: ElementFrameStates;
prevOpacities: Array<[number, number]>;
}> {
// Array with all text elements and their corresponding expected frame states.
const elementFrameStates: ElementFrameStates = new Array();
let enableElevation = false;
const allTileIndices: number[] = [];
// For each tile, build all its text elements and add them together with their expected
// frame states to an array.
test.tiles.forEach((tile: InputTile, tileIndex: number) => {
if (tile.frames !== undefined) {
expect(tile.frames.length).equal(
test.frameTimes.length,
"frames length is the same"
);
}
if (tile.terrainFrames !== undefined) {
expect(tile.terrainFrames.length).equal(
test.frameTimes.length,
"terrainFrames length is the same"
);
enableElevation = true;
}
const labels = buildLabels(tile.labels, elementFrameStates, test.frameTimes.length);
allTileIndices.push(tileIndex);
fixture.addTile(labels);
});
// Keeps track of the opacity that text elements had in the previous frame.
const prevOpacities = new Array(elementFrameStates.length).fill([0, 0]);
// Extra frame including all tiles to set the glyph loading state of all text elements
// to initialized.
await fixture.renderFrame(INITIAL_TIME, allTileIndices, []);
fixture.setElevationProvider(enableElevation);
return { elementFrameStates, prevOpacities };
}
// Returns an array with the indices for all tiles that are visible in the specified frame.
function getFrameTileIndices(
frameIdx: number,
tiles: InputTile[]
): { tileIdcs: number[]; terrainTileIdcs: number[] } {
const tileIdcs: number[] = [];
const terrainTileIdcs: number[] = [];
for (let i = 0; i < tiles.length; ++i) {
const tile = tiles[i];
if (!tile.frames || tile.frames[frameIdx]) {
tileIdcs.push(i);
}
if (tile.terrainFrames && tile.terrainFrames[frameIdx]) {
terrainTileIdcs.push(i);
}
}
return { tileIdcs, terrainTileIdcs };
}
function prepareTextElements(frameIdx: number, tiles: InputTile[], tileIndices: number[]) {
for (const tileIndex of tileIndices) {
const tile = tiles[tileIndex];
const elementsEnabled = tile.labels.map(
label => framesEnabled(label)?.[frameIdx] ?? true
);
fixture.setTileTextElements(tileIndex, elementsEnabled);
}
}
for (const test of tests) {
it(test.name, async function () {
const { elementFrameStates, prevOpacities } = await initTest(test);
for (let frameIdx = 0; frameIdx < test.frameTimes.length; ++frameIdx) {
const { tileIdcs, terrainTileIdcs } = getFrameTileIndices(frameIdx, test.tiles);
const frameTime = test.frameTimes[frameIdx];
const collisionEnabled =
test.collisionFrames === undefined ? true : test.collisionFrames[frameIdx];
prepareTextElements(frameIdx, test.tiles, tileIdcs);
await fixture.renderFrame(frameTime, tileIdcs, terrainTileIdcs, collisionEnabled);
let opacityIdx = 0;
for (const [
textElement,
expectedStates,
expectedIconStates
] of elementFrameStates) {
let stateIdx = 0;
for (const textState of expectedStates) {
const elementNewOpacities = fixture.checkTextElementState(
textElement,
textState[frameIdx],
expectedIconStates?.[stateIdx][frameIdx],
prevOpacities[opacityIdx],
textElement.type === TextElementType.LineMarker ? stateIdx : undefined
);
prevOpacities[opacityIdx] = elementNewOpacities;
opacityIdx++;
stateIdx++;
}
}
}
});
}
it("updates FontCatalogs", async function () {
expect(fixture.loadCatalogStub.calledOnce, "default catalog was set").to.be.true;
await fixture.textRenderer.updateFontCatalogs([
{
name: "catalog1",
url: "some-url-1"
},
{
name: "catalog2",
url: "some-url-2"
}
]);
expect(fixture.loadCatalogStub.calledThrice).to.be.true;
await fixture.textRenderer.updateFontCatalogs([
{
name: "catalog1",
url: "some-url-1"
},
{
name: "catalog2",
url: "some-other-url-2"
}
]);
expect(fixture.loadCatalogStub.calledThrice, "no new catalog added").to.be.true;
await fixture.textRenderer.updateFontCatalogs([
{
name: "catalog1",
url: "some-url-1"
},
{
name: "catalog3",
url: "some-url-3"
}
]);
expect(fixture.loadCatalogStub.callCount, "adds catalog3").to.equal(4);
await fixture.textRenderer.updateFontCatalogs([
{
name: "catalog2",
url: "some-url-2"
}
]);
expect(
fixture.loadCatalogStub.callCount,
"adds catalog2 back, removed in last step"
).to.equal(5);
await fixture.textRenderer.updateFontCatalogs([]);
expect(fixture.loadCatalogStub.callCount).to.equal(5);
await fixture.textRenderer.updateFontCatalogs([
{
name: DEFAULT_FONT_CATALOG_NAME,
url: "some-url"
}
]);
expect(fixture.loadCatalogStub.callCount).to.equal(6);
await fixture.textRenderer.updateFontCatalogs([
{
name: DEFAULT_FONT_CATALOG_NAME,
url: "some-other-url"
}
]);
expect(fixture.loadCatalogStub.callCount).to.equal(7);
});
it("updates TextStyles", async function () {
const style1: TextStyleDefinition = {
name: "style-1",
fontCatalogName: "catalog-1"
};
const style2: TextStyleDefinition = {
name: "style-2",
fontCatalogName: "catalog-2"
};
const style3: TextStyleDefinition = {
name: "style-3",
fontCatalogName: "catalog-3"
};
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-1").name).to.equal(
"default"
);
await fixture.textRenderer.updateTextStyles();
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-1").name).to.equal(
"default"
);
await fixture.textRenderer.updateTextStyles([]);
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-1").name).to.equal(
"default"
);
await fixture.textRenderer.updateTextStyles([], style2);
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-1").fontCatalog).to.equal(
"catalog-2",
"the new default is using style-2"
);
await fixture.textRenderer.updateTextStyles([]);
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-1").name).to.equal(
"default",
"the default is reset to 'default'"
);
await fixture.textRenderer.updateTextStyles([style1, style2]);
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-1").name).to.equal(
"style-1",
"the style is found in the list"
);
await fixture.textRenderer.updateTextStyles([style3, style2]);
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-1").name).to.equal(
"default",
"style-1 was removed, using default instead"
);
expect(fixture.textRenderer.styleCache.getTextElementStyle("style-3").name).to.equal(
"style-3",
"the style is found in the list"
);
});
}); | the_stack |
import {
Application,
ApplicationConfig,
Binding,
BindingAddress,
Constructor,
Context,
Provider,
Server,
} from '@loopback/core';
import {
ExpressMiddlewareFactory,
ExpressRequestHandler,
Middleware,
MiddlewareBindingOptions,
} from '@loopback/express';
import {OpenApiSpec, OperationObject} from '@loopback/openapi-v3';
import {PathParams} from 'express-serve-static-core';
import {ServeStaticOptions} from 'serve-static';
import {format} from 'util';
import {BodyParser} from './body-parsers';
import {RestBindings} from './keys';
import {RestComponent} from './rest.component';
import {HttpRequestListener, HttpServerLike, RestServer} from './rest.server';
import {ControllerClass, ControllerFactory, RouteEntry} from './router';
import {RouterSpec} from './router/router-spec';
import {SequenceFunction, SequenceHandler} from './sequence';
export const ERR_NO_MULTI_SERVER = format(
'RestApplication does not support multiple servers!',
'To create your own server bindings, please extend the Application class.',
);
// To help cut down on verbosity!
export const SequenceActions = RestBindings.SequenceActions;
/**
* An implementation of the Application class that automatically provides
* an instance of a REST server. This application class is intended to be
* a single-server implementation. Any attempt to bind additional servers
* will throw an error.
*
*/
export class RestApplication extends Application implements HttpServerLike {
/**
* The main REST server instance providing REST API for this application.
*/
get restServer(): RestServer {
// FIXME(kjdelisle): I attempted to mimic the pattern found in RestServer
// with no success, so until I've got a better way, this is functional.
return this.getSync<RestServer>('servers.RestServer');
}
/**
* Handle incoming HTTP(S) request by invoking the corresponding
* Controller method via the configured Sequence.
*
* @example
*
* ```ts
* const app = new RestApplication();
* // setup controllers, etc.
*
* const server = http.createServer(app.requestHandler);
* server.listen(3000);
* ```
*
* @param req - The request.
* @param res - The response.
*/
get requestHandler(): HttpRequestListener {
return this.restServer.requestHandler;
}
/**
* Create a REST application with the given parent context
* @param parent - Parent context
*/
constructor(parent: Context);
/**
* Create a REST application with the given configuration and parent context
* @param config - Application configuration
* @param parent - Parent context
*/
constructor(config?: ApplicationConfig, parent?: Context);
constructor(configOrParent?: ApplicationConfig | Context, parent?: Context) {
super(configOrParent, parent);
this.component(RestComponent);
}
server(server: Constructor<Server>, name?: string): Binding {
if (this.findByTag('server').length > 0) {
throw new Error(ERR_NO_MULTI_SERVER);
}
return super.server(server, name);
}
sequence(sequence: Constructor<SequenceHandler>): Binding {
return this.restServer.sequence(sequence);
}
handler(handlerFn: SequenceFunction) {
this.restServer.handler(handlerFn);
}
/**
* Mount static assets to the REST server.
* See https://expressjs.com/en/4x/api.html#express.static
* @param path - The path(s) to serve the asset.
* See examples at https://expressjs.com/en/4x/api.html#path-examples
* To avoid performance penalty, `/` is not allowed for now.
* @param rootDir - The root directory from which to serve static assets
* @param options - Options for serve-static
*/
static(path: PathParams, rootDir: string, options?: ServeStaticOptions) {
this.restServer.static(path, rootDir, options);
}
/**
* Bind a body parser to the server context
* @param parserClass - Body parser class
* @param address - Optional binding address
*/
bodyParser(
bodyParserClass: Constructor<BodyParser>,
address?: BindingAddress<BodyParser>,
): Binding<BodyParser> {
return this.restServer.bodyParser(bodyParserClass, address);
}
/**
* Configure the `basePath` for the rest server
* @param path - Base path
*/
basePath(path = '') {
this.restServer.basePath(path);
}
/**
* Bind an Express middleware to this server context
*
* @example
* ```ts
* import myExpressMiddlewareFactory from 'my-express-middleware';
* const myExpressMiddlewareConfig= {};
* const myExpressMiddleware = myExpressMiddlewareFactory(myExpressMiddlewareConfig);
* server.expressMiddleware('middleware.express.my', myExpressMiddleware);
* ```
* @param key - Middleware binding key
* @param middleware - Express middleware handler function(s)
*
*/
expressMiddleware(
key: BindingAddress,
middleware: ExpressRequestHandler | ExpressRequestHandler[],
options?: MiddlewareBindingOptions,
): Binding<Middleware>;
/**
* Bind an Express middleware to this server context
*
* @example
* ```ts
* import myExpressMiddlewareFactory from 'my-express-middleware';
* const myExpressMiddlewareConfig= {};
* server.expressMiddleware(myExpressMiddlewareFactory, myExpressMiddlewareConfig);
* ```
* @param middlewareFactory - Middleware module name or factory function
* @param middlewareConfig - Middleware config
* @param options - Options for registration
*
* @typeParam CFG - Configuration type
*/
expressMiddleware<CFG>(
middlewareFactory: ExpressMiddlewareFactory<CFG>,
middlewareConfig?: CFG,
options?: MiddlewareBindingOptions,
): Binding<Middleware>;
expressMiddleware<CFG>(
factoryOrKey: ExpressMiddlewareFactory<CFG> | BindingAddress<Middleware>,
configOrHandlers: CFG | ExpressRequestHandler | ExpressRequestHandler[],
options: MiddlewareBindingOptions = {},
): Binding<Middleware> {
return this.restServer.expressMiddleware(
factoryOrKey,
configOrHandlers,
options,
);
}
/**
* Register a middleware function or provider class
*
* @example
* ```ts
* const log: Middleware = async (requestCtx, next) {
* // ...
* }
* server.middleware(log);
* ```
*
* @param middleware - Middleware function or provider class
* @param options - Middleware binding options
*/
middleware(
middleware: Middleware | Constructor<Provider<Middleware>>,
options: MiddlewareBindingOptions = {},
): Binding<Middleware> {
return this.restServer.middleware(middleware, options);
}
/**
* Register a new Controller-based route.
*
* @example
* ```ts
* class MyController {
* greet(name: string) {
* return `hello ${name}`;
* }
* }
* app.route('get', '/greet', operationSpec, MyController, 'greet');
* ```
*
* @param verb - HTTP verb of the endpoint
* @param path - URL path of the endpoint
* @param spec - The OpenAPI spec describing the endpoint (operation)
* @param controllerCtor - Controller constructor
* @param controllerFactory - A factory function to create controller instance
* @param methodName - The name of the controller method
*/
route<T>(
verb: string,
path: string,
spec: OperationObject,
controllerCtor: ControllerClass<T>,
controllerFactory: ControllerFactory<T>,
methodName: string,
): Binding;
/**
* Register a new route invoking a handler function.
*
* @example
* ```ts
* function greet(name: string) {
* return `hello ${name}`;
* }
* app.route('get', '/', operationSpec, greet);
* ```
*
* @param verb - HTTP verb of the endpoint
* @param path - URL path of the endpoint
* @param spec - The OpenAPI spec describing the endpoint (operation)
* @param handler - The function to invoke with the request parameters
* described in the spec.
*/
route(
verb: string,
path: string,
spec: OperationObject,
handler: Function,
): Binding;
/**
* Register a new route.
*
* @example
* ```ts
* function greet(name: string) {
* return `hello ${name}`;
* }
* const route = new Route('get', '/', operationSpec, greet);
* app.route(route);
* ```
*
* @param route - The route to add.
*/
route(route: RouteEntry): Binding;
/**
* Register a new route.
*
* @example
* ```ts
* function greet(name: string) {
* return `hello ${name}`;
* }
* app.route('get', '/', operationSpec, greet);
* ```
*/
route(
verb: string,
path: string,
spec: OperationObject,
handler: Function,
): Binding;
route<T>(
routeOrVerb: RouteEntry | string,
path?: string,
spec?: OperationObject,
controllerCtorOrHandler?: ControllerClass<T> | Function,
controllerFactory?: ControllerFactory<T>,
methodName?: string,
): Binding {
const server = this.restServer;
if (typeof routeOrVerb === 'object') {
return server.route(routeOrVerb);
} else if (arguments.length === 4) {
return server.route(
routeOrVerb,
path!,
spec!,
controllerCtorOrHandler as Function,
);
} else {
return server.route(
routeOrVerb,
path!,
spec!,
controllerCtorOrHandler as ControllerClass<T>,
controllerFactory!,
methodName!,
);
}
}
/**
* Register a route redirecting callers to a different URL.
*
* @example
* ```ts
* app.redirect('/explorer', '/explorer/');
* ```
*
* @param fromPath - URL path of the redirect endpoint
* @param toPathOrUrl - Location (URL path or full URL) where to redirect to.
* If your server is configured with a custom `basePath`, then the base path
* is prepended to the target location.
* @param statusCode - HTTP status code to respond with,
* defaults to 303 (See Other).
*/
redirect(
fromPath: string,
toPathOrUrl: string,
statusCode?: number,
): Binding {
return this.restServer.redirect(fromPath, toPathOrUrl, statusCode);
}
/**
* Set the OpenAPI specification that defines the REST API schema for this
* application. All routes, parameter definitions and return types will be
* defined in this way.
*
* Note that this will override any routes defined via decorators at the
* controller level (this function takes precedent).
*
* @param spec - The OpenAPI specification, as an object.
* @returns Binding for the api spec
*/
api(spec: OpenApiSpec): Binding {
return this.restServer.bind(RestBindings.API_SPEC).to(spec);
}
/**
* Mount an Express router to expose additional REST endpoints handled
* via legacy Express-based stack.
*
* @param basePath - Path where to mount the router at, e.g. `/` or `/api`.
* @param router - The Express router to handle the requests.
* @param spec - A partial OpenAPI spec describing endpoints provided by the
* router. LoopBack will prepend `basePath` to all endpoints automatically.
* This argument is optional. You can leave it out if you don't want to
* document the routes.
*/
mountExpressRouter(
basePath: string,
router: ExpressRequestHandler,
spec?: RouterSpec,
): void {
this.restServer.mountExpressRouter(basePath, router, spec);
}
/**
* Export the OpenAPI spec to the given json or yaml file
* @param outFile - File name for the spec. The extension of the file
* determines the format of the file.
* - `yaml` or `yml`: YAML
* - `json` or other: JSON
* If the outFile is not provided or its value is `''` or `'-'`, the spec is
* written to the console using the `log` function.
* @param log - Log function, default to `console.log`
*/
async exportOpenApiSpec(outFile = '', log = console.log): Promise<void> {
return this.restServer.exportOpenApiSpec(outFile, log);
}
} | the_stack |
import {
DATA_SOURCE_ENUM,
ENGINE_SOURCE_TYPE_ENUM,
FLINK_VERSIONS,
ID_COLLECTIONS,
KAFKA_DATA_TYPE,
RDB_TYPE_ARRAY,
} from '@/constant';
import type { UniqueId } from '@dtinsight/molecule/esm/common/types';
/**
* 是否需要 schema
*/
export const isSchemaRequired = (type?: DATA_SOURCE_ENUM) => {
return !!(
type &&
[
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
].includes(type)
);
};
/**
* 是否为 kafka
*/
export function isKafka(type?: DATA_SOURCE_ENUM) {
return (
type &&
[
DATA_SOURCE_ENUM.KAFKA,
DATA_SOURCE_ENUM.KAFKA_2X,
DATA_SOURCE_ENUM.KAFKA_11,
DATA_SOURCE_ENUM.KAFKA_09,
DATA_SOURCE_ENUM.KAFKA_10,
DATA_SOURCE_ENUM.TBDS_KAFKA,
DATA_SOURCE_ENUM.KAFKA_HUAWEI,
DATA_SOURCE_ENUM.KAFKA_CONFLUENT,
].includes(type)
);
}
/**
* 是否拥有字段列的权限
*/
export function isHaveTableColumn(type?: DATA_SOURCE_ENUM) {
return (
type &&
[
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.POLAR_DB_For_MySQL,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.CLICKHOUSE,
DATA_SOURCE_ENUM.KUDU,
DATA_SOURCE_ENUM.IMPALA,
DATA_SOURCE_ENUM.TIDB,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
DATA_SOURCE_ENUM.HIVE,
DATA_SOURCE_ENUM.INCEPTOR,
].includes(type)
);
}
/**
* 是否拥有 Topic 的列
*/
export function isHaveTopic(type?: DATA_SOURCE_ENUM) {
return (
type &&
[
DATA_SOURCE_ENUM.KAFKA,
DATA_SOURCE_ENUM.KAFKA_11,
DATA_SOURCE_ENUM.KAFKA_09,
DATA_SOURCE_ENUM.KAFKA_10,
DATA_SOURCE_ENUM.KAFKA_2X,
DATA_SOURCE_ENUM.TBDS_KAFKA,
DATA_SOURCE_ENUM.KAFKA_HUAWEI,
DATA_SOURCE_ENUM.KAFKA_CONFLUENT,
].includes(type)
);
}
/**
* 是否拥有分区
*/
export function isHavePartition(type?: DATA_SOURCE_ENUM) {
const list = [DATA_SOURCE_ENUM.IMPALA, DATA_SOURCE_ENUM.HIVE, DATA_SOURCE_ENUM.INCEPTOR];
return type && list.includes(type);
}
/**
* 是否拥有 Schema
*/
export function isHaveSchema(type?: DATA_SOURCE_ENUM) {
const list = [
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
];
return type && list.includes(type);
}
/**
* 是否拥有表字段
* S3 数据源的 Bucket 下拉框用的也是 TableList 的接口,表单字段也不是 table 是 bucket 。。
*/
export function isHaveTableList(type?: DATA_SOURCE_ENUM) {
const list = [
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.POLAR_DB_For_MySQL,
DATA_SOURCE_ENUM.HBASE,
DATA_SOURCE_ENUM.TBDS_HBASE,
DATA_SOURCE_ENUM.HBASE_HUAWEI,
DATA_SOURCE_ENUM.MONGODB,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.KUDU,
DATA_SOURCE_ENUM.IMPALA,
DATA_SOURCE_ENUM.TIDB,
DATA_SOURCE_ENUM.CLICKHOUSE,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.S3,
DATA_SOURCE_ENUM.CSP_S3,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
DATA_SOURCE_ENUM.HIVE,
DATA_SOURCE_ENUM.INCEPTOR,
];
return type && list.includes(type);
}
/**
* 是否拥有主键列的权限
*/
export function isHavePrimaryKey(
type?: DATA_SOURCE_ENUM,
version: string = FLINK_VERSIONS.FLINK_1_12,
) {
const list = [
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.POLAR_DB_For_MySQL,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.CLICKHOUSE,
DATA_SOURCE_ENUM.DB2,
DATA_SOURCE_ENUM.TIDB,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
];
return (
type && (list.includes(type) || (version === FLINK_VERSIONS.FLINK_1_12 && isKafka(type)))
);
}
/** 是否拥有数据预览 */
export function isHaveDataPreview(type?: DATA_SOURCE_ENUM) {
const list = [
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.REDIS,
DATA_SOURCE_ENUM.UPRedis,
DATA_SOURCE_ENUM.ES,
DATA_SOURCE_ENUM.ES6,
DATA_SOURCE_ENUM.ES7,
DATA_SOURCE_ENUM.HBASE,
DATA_SOURCE_ENUM.HBASE_HUAWEI,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
DATA_SOURCE_ENUM.HIVE,
DATA_SOURCE_ENUM.INCEPTOR,
];
return type && list.includes(type);
}
/**
* 是否拥有 collection
*/
export function isHaveCollection(type?: DATA_SOURCE_ENUM) {
return type && [DATA_SOURCE_ENUM.SOLR].includes(type);
}
/**
* 是否渲染 Bucket
*/
export function isShowBucket(type?: DATA_SOURCE_ENUM) {
return type && [DATA_SOURCE_ENUM.S3, DATA_SOURCE_ENUM.CSP_S3].includes(type);
}
/**
* 是否展示 offsetReset 的 time 列
*/
export function isShowTimeForOffsetReset(type?: DATA_SOURCE_ENUM) {
return (
type &&
[
DATA_SOURCE_ENUM.KAFKA,
DATA_SOURCE_ENUM.KAFKA_2X,
DATA_SOURCE_ENUM.KAFKA_10,
DATA_SOURCE_ENUM.KAFKA_11,
DATA_SOURCE_ENUM.TBDS_KAFKA,
DATA_SOURCE_ENUM.KAFKA_HUAWEI,
DATA_SOURCE_ENUM.KAFKA_CONFLUENT,
].includes(type)
);
}
/**
* 是否展示 schema
*/
export function isShowSchema(type?: DATA_SOURCE_ENUM) {
const list = [DATA_SOURCE_ENUM.ORACLE, DATA_SOURCE_ENUM.POSTGRESQL, DATA_SOURCE_ENUM.KINGBASE8];
return type && (isSqlServer(type) || list.includes(type));
}
/**
* 是否有更新模式
*/
export function isHaveUpdateMode(type?: DATA_SOURCE_ENUM) {
return (
type &&
![
DATA_SOURCE_ENUM.S3,
DATA_SOURCE_ENUM.CSP_S3,
DATA_SOURCE_ENUM.SOLR,
DATA_SOURCE_ENUM.HIVE,
DATA_SOURCE_ENUM.INCEPTOR,
].includes(type)
);
}
/**
* 是否允许更新模式切换
*/
export function isHaveUpsert(type?: DATA_SOURCE_ENUM, version: string = FLINK_VERSIONS.FLINK_1_12) {
const list = [
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.POLAR_DB_For_MySQL,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.CLICKHOUSE,
DATA_SOURCE_ENUM.KUDU,
DATA_SOURCE_ENUM.DB2,
DATA_SOURCE_ENUM.TIDB,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
];
return (
type && (list.includes(type) || (version === FLINK_VERSIONS.FLINK_1_12 && isKafka(type)))
);
}
/**
* 更新模式为更新时,是否可以选择更新策略
*/
export function isHaveUpdateStrategy(type?: DATA_SOURCE_ENUM) {
const list = [
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.TIDB,
];
return type && list.includes(type);
}
/**
* 是否展示并行度
*/
export function isHaveParallelism(type?: DATA_SOURCE_ENUM) {
return type && ![DATA_SOURCE_ENUM.HIVE, DATA_SOURCE_ENUM.INCEPTOR].includes(type);
}
/**
* 缓存策略是否只允许 ALL
*/
export function isCacheOnlyAll(type?: DATA_SOURCE_ENUM) {
return type && [DATA_SOURCE_ENUM.INCEPTOR].includes(type);
}
/**
* 不支持 LRU 的情况(包含支持 None 的情况)
*/
export function isCacheExceptLRU(type?: DATA_SOURCE_ENUM) {
return (type && [DATA_SOURCE_ENUM.HBASE_HUAWEI].includes(type)) || isCacheOnlyAll(type);
}
/**
* 是否展示异步线程池
*/
export function isHaveAsyncPoolSize(type?: DATA_SOURCE_ENUM) {
const list = [
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.TIDB,
DATA_SOURCE_ENUM.POLAR_DB_For_MySQL,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.CLICKHOUSE,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.IMPALA,
DATA_SOURCE_ENUM.INCEPTOR,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
DATA_SOURCE_ENUM.SOLR,
];
return type && list.includes(type);
}
/**
* 是否可以添加自定义参数
* @param type
* @returns
*/
export function isHaveCustomParams(type?: DATA_SOURCE_ENUM) {
const list = [
DATA_SOURCE_ENUM.REDIS,
DATA_SOURCE_ENUM.UPRedis,
DATA_SOURCE_ENUM.MONGODB,
DATA_SOURCE_ENUM.ES,
DATA_SOURCE_ENUM.HBASE,
DATA_SOURCE_ENUM.HBASE_HUAWEI,
DATA_SOURCE_ENUM.KUDU,
];
return type && list.includes(type);
}
/**
* 是否为 Mysql 类型数据源
*/
export function isMysqlTypeSource(type?: DATA_SOURCE_ENUM) {
return (
type &&
[
DATA_SOURCE_ENUM.MYSQL,
DATA_SOURCE_ENUM.UPDRDB,
DATA_SOURCE_ENUM.POLAR_DB_For_MySQL,
DATA_SOURCE_ENUM.ORACLE,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
DATA_SOURCE_ENUM.POSTGRESQL,
].includes(type)
);
}
/**
* 是否为 Hbase 类型
*/
export function isHbase(type?: DATA_SOURCE_ENUM) {
return (
type &&
[
DATA_SOURCE_ENUM.HBASE,
DATA_SOURCE_ENUM.TBDS_HBASE,
DATA_SOURCE_ENUM.HBASE_HUAWEI,
].includes(type)
);
}
/**
* 是否为 ES 类型
*/
export function isES(type: DATA_SOURCE_ENUM) {
return type && [DATA_SOURCE_ENUM.ES, DATA_SOURCE_ENUM.ES6, DATA_SOURCE_ENUM.ES7].includes(type);
}
/**
* 是否为低版本的 ES
*/
export function isLowerES(type?: DATA_SOURCE_ENUM) {
return type && [DATA_SOURCE_ENUM.ES, DATA_SOURCE_ENUM.ES6].includes(type);
}
/**
* 是否为 Redis 类型
*/
export function isRedis(type?: DATA_SOURCE_ENUM) {
return type && [DATA_SOURCE_ENUM.REDIS, DATA_SOURCE_ENUM.UPRedis].includes(type);
}
/**
* 是否为 Hive 类型
*/
export function isHive(type?: DATA_SOURCE_ENUM) {
return type === DATA_SOURCE_ENUM.HIVE;
}
/**
* 是否为 S3 数据源
*/
export function isS3(type?: DATA_SOURCE_ENUM) {
return type && [DATA_SOURCE_ENUM.S3, DATA_SOURCE_ENUM.CSP_S3].includes(type);
}
/**
* 是否为 SqlServer 类型
*/
export function isSqlServer(type?: DATA_SOURCE_ENUM) {
return (
type && [DATA_SOURCE_ENUM.SQLSERVER, DATA_SOURCE_ENUM.SQLSERVER_2017_LATER].includes(type)
);
}
/**
* 是否为 kafak 和 confluent 的输入输出类型 avro 和 avro-confluent
*/
export function isAvro(type?: KAFKA_DATA_TYPE) {
return type && [KAFKA_DATA_TYPE.TYPE_AVRO, KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT].includes(type);
}
/**
* 是否为 HDFS 类型
*/
export function isHdfsType(type?: DATA_SOURCE_ENUM) {
return DATA_SOURCE_ENUM.HDFS === type;
}
/**
* 是否是 Hadoop 引擎
*/
export function isSparkEngine(engineType?: numOrStr) {
return ENGINE_SOURCE_TYPE_ENUM.HADOOP.toString() === engineType?.toString();
}
/**
* 是否是 Oracle 引擎
*/
export function isOracleEngine(engineType: numOrStr) {
return ENGINE_SOURCE_TYPE_ENUM.ORACLE.toString() === engineType.toString();
}
/**
* 是否属于关系型数据源
*/
export function isRDB(type?: DATA_SOURCE_ENUM) {
return !!(type && RDB_TYPE_ARRAY.includes(type));
}
/**
* 根据任务 ID 来区分是否是任务 Tab
*/
export function isTaskTab(id?: UniqueId) {
if (id === undefined) return false;
if (typeof id === 'number') return true;
const NON_TASK_TAB = [
ID_COLLECTIONS.CREATE_DATASOURCE_PREFIX,
ID_COLLECTIONS.EDIT_DATASOURCE_PREFIX,
ID_COLLECTIONS.CREATE_TASK_PREFIX,
ID_COLLECTIONS.EDIT_TASK_PREFIX,
ID_COLLECTIONS.EDIT_FOLDER_PREFIX,
];
return !NON_TASK_TAB.some((prefix) => id.startsWith(prefix));
} | the_stack |
import {
artifacts as assetProxyArtifacts,
encodeERC20AssetData,
encodeERC721AssetData,
encodeMultiAssetData,
encodeStaticCallAssetData,
TestStaticCallTargetContract,
} from '@0x/contracts-asset-proxy';
import { DummyERC20TokenContract } from '@0x/contracts-erc20';
import { DummyERC721TokenContract } from '@0x/contracts-erc721';
import { artifacts as exchangeArtifacts, ExchangeContract } from '@0x/contracts-exchange';
import { artifacts, ExchangeForwarderRevertErrors, ForwarderContract } from '@0x/contracts-exchange-forwarder';
import { MixinWethUtilsRevertErrors } from '@0x/contracts-extensions';
import {
blockchainTests,
constants,
expect,
getLatestBlockTimestampAsync,
randomAddress,
toBaseUnitAmount,
} from '@0x/contracts-test-utils';
import { BigNumber } from '@0x/utils';
import { Actor } from '../framework/actors/base';
import { FeeRecipient } from '../framework/actors/fee_recipient';
import { Maker } from '../framework/actors/maker';
import { Taker } from '../framework/actors/taker';
import { actorAddressesByName } from '../framework/actors/utils';
import { BlockchainBalanceStore } from '../framework/balances/blockchain_balance_store';
import { LocalBalanceStore } from '../framework/balances/local_balance_store';
import { DeploymentManager } from '../framework/deployment_manager';
import { deployForwarderAsync } from './deploy_forwarder';
import { ForwarderTestFactory } from './forwarder_test_factory';
blockchainTests('Forwarder integration tests', env => {
let deployment: DeploymentManager;
let forwarder: ForwarderContract;
let balanceStore: BlockchainBalanceStore;
let testFactory: ForwarderTestFactory;
let makerToken: DummyERC20TokenContract;
let makerFeeToken: DummyERC20TokenContract;
let anotherErc20Token: DummyERC20TokenContract;
let erc721Token: DummyERC721TokenContract;
let nftId: BigNumber;
let wethAssetData: string;
let makerAssetData: string;
let staticCallSuccessAssetData: string;
let staticCallFailureAssetData: string;
let maker: Maker;
let taker: Taker;
let orderFeeRecipient: FeeRecipient;
let forwarderFeeRecipient: FeeRecipient;
before(async () => {
deployment = await DeploymentManager.deployAsync(env, {
numErc20TokensToDeploy: 3,
numErc721TokensToDeploy: 1,
numErc1155TokensToDeploy: 0,
});
forwarder = await deployForwarderAsync(deployment, env);
const staticCallTarget = await TestStaticCallTargetContract.deployFrom0xArtifactAsync(
assetProxyArtifacts.TestStaticCallTarget,
env.provider,
env.txDefaults,
assetProxyArtifacts,
);
[makerToken, makerFeeToken, anotherErc20Token] = deployment.tokens.erc20;
[erc721Token] = deployment.tokens.erc721;
wethAssetData = encodeERC20AssetData(deployment.tokens.weth.address);
makerAssetData = encodeERC20AssetData(makerToken.address);
staticCallSuccessAssetData = encodeStaticCallAssetData(
staticCallTarget.address,
staticCallTarget.assertEvenNumber(new BigNumber(2)).getABIEncodedTransactionData(),
constants.KECCAK256_NULL,
);
staticCallFailureAssetData = encodeStaticCallAssetData(
staticCallTarget.address,
staticCallTarget.assertEvenNumber(new BigNumber(1)).getABIEncodedTransactionData(),
constants.KECCAK256_NULL,
);
taker = new Taker({ name: 'Taker', deployment });
orderFeeRecipient = new FeeRecipient({
name: 'Order fee recipient',
deployment,
});
forwarderFeeRecipient = new FeeRecipient({
name: 'Forwarder fee recipient',
deployment,
});
maker = new Maker({
name: 'Maker',
deployment,
orderConfig: {
feeRecipientAddress: orderFeeRecipient.address,
makerAssetAmount: toBaseUnitAmount(2),
takerAssetAmount: toBaseUnitAmount(1),
makerAssetData,
takerAssetData: wethAssetData,
takerFee: constants.ZERO_AMOUNT,
makerFeeAssetData: encodeERC20AssetData(makerFeeToken.address),
takerFeeAssetData: wethAssetData,
},
});
await maker.configureERC20TokenAsync(makerToken);
await maker.configureERC20TokenAsync(makerFeeToken);
await maker.configureERC20TokenAsync(anotherErc20Token);
await forwarder.approveMakerAssetProxy(makerAssetData).awaitTransactionSuccessAsync();
[nftId] = await maker.configureERC721TokenAsync(erc721Token);
const tokenOwners = {
...actorAddressesByName([maker, taker, orderFeeRecipient, forwarderFeeRecipient]),
Forwarder: forwarder.address,
StakingProxy: deployment.staking.stakingProxy.address,
};
const tokenContracts = {
erc20: { makerToken, makerFeeToken, anotherErc20Token, wETH: deployment.tokens.weth },
erc721: { erc721Token },
};
const tokenIds = { erc721: { [erc721Token.address]: [nftId] } };
balanceStore = new BlockchainBalanceStore(tokenOwners, tokenContracts, tokenIds);
testFactory = new ForwarderTestFactory(forwarder, deployment, balanceStore, taker);
});
after(async () => {
Actor.reset();
});
blockchainTests.resets('constructor', () => {
it('should revert if assetProxy is unregistered', async () => {
const chainId = await env.getChainIdAsync();
const exchange = await ExchangeContract.deployFrom0xArtifactAsync(
exchangeArtifacts.Exchange,
env.provider,
env.txDefaults,
{},
new BigNumber(chainId),
);
const deployForwarder = ForwarderContract.deployFrom0xArtifactAsync(
artifacts.Forwarder,
env.provider,
env.txDefaults,
{},
exchange.address,
constants.NULL_ADDRESS,
deployment.tokens.weth.address,
);
await expect(deployForwarder).to.revertWith(
new ExchangeForwarderRevertErrors.UnregisteredAssetProxyError(),
);
});
});
blockchainTests.resets('marketSellOrdersWithEth without extra fees', () => {
it('should fill a single order without a taker fee', async () => {
const orderWithoutFee = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([orderWithoutFee], 0.78);
});
it('should fill multiple orders without taker fees', async () => {
const firstOrder = await maker.signOrderAsync();
const secondOrder = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(285),
takerAssetAmount: toBaseUnitAmount(21),
});
const orders = [firstOrder, secondOrder];
await testFactory.marketSellTestAsync(orders, 1.51);
});
it('should fill a single order with a percentage fee', async () => {
const orderWithPercentageFee = await maker.signOrderAsync({
takerFee: toBaseUnitAmount(1),
takerFeeAssetData: makerAssetData,
});
await testFactory.marketSellTestAsync([orderWithPercentageFee], 0.58);
});
it('should fill multiple orders with percentage fees', async () => {
const firstOrder = await maker.signOrderAsync({
takerFee: toBaseUnitAmount(1),
takerFeeAssetData: makerAssetData,
});
const secondOrder = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(190),
takerAssetAmount: toBaseUnitAmount(31),
takerFee: toBaseUnitAmount(2),
takerFeeAssetData: makerAssetData,
});
const orders = [firstOrder, secondOrder];
await testFactory.marketSellTestAsync(orders, 1.34);
});
it('should fail to fill an order with a percentage fee if the asset proxy is not yet approved', async () => {
const unapprovedAsset = encodeERC20AssetData(anotherErc20Token.address);
const order = await maker.signOrderAsync({
makerAssetData: unapprovedAsset,
takerFee: toBaseUnitAmount(2),
takerFeeAssetData: unapprovedAsset,
});
await balanceStore.updateBalancesAsync();
// Execute test case
const tx = await forwarder
.marketSellOrdersWithEth([order], [order.signature], [], [])
.awaitTransactionSuccessAsync({
value: order.takerAssetAmount.plus(DeploymentManager.protocolFee),
from: taker.address,
});
const expectedBalances = LocalBalanceStore.create(balanceStore);
expectedBalances.burnGas(tx.from, DeploymentManager.gasPrice.times(tx.gasUsed));
// Verify balances
await balanceStore.updateBalancesAsync();
balanceStore.assertEquals(expectedBalances);
});
it('should fill a single order with a WETH fee', async () => {
const orderWithWethFee = await maker.signOrderAsync({
takerFee: toBaseUnitAmount(1),
takerFeeAssetData: wethAssetData,
});
await testFactory.marketSellTestAsync([orderWithWethFee], 0.13);
});
it('should fill multiple orders with WETH fees', async () => {
const firstOrder = await maker.signOrderAsync({
takerFee: toBaseUnitAmount(1),
takerFeeAssetData: wethAssetData,
});
const secondOrderWithWethFee = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(97),
takerAssetAmount: toBaseUnitAmount(33),
takerFee: toBaseUnitAmount(2),
takerFeeAssetData: wethAssetData,
});
const orders = [firstOrder, secondOrderWithWethFee];
await testFactory.marketSellTestAsync(orders, 1.25);
});
it('should refund remaining ETH if amount is greater than takerAssetAmount', async () => {
const order = await maker.signOrderAsync();
const ethValue = order.takerAssetAmount.plus(DeploymentManager.protocolFee).plus(2);
const takerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(taker.address);
const tx = await forwarder
.marketSellOrdersWithEth([order], [order.signature], [], [])
.awaitTransactionSuccessAsync({
value: ethValue,
from: taker.address,
});
const takerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(taker.address);
const totalEthSpent = order.takerAssetAmount
.plus(DeploymentManager.protocolFee)
.plus(DeploymentManager.gasPrice.times(tx.gasUsed));
expect(takerEthBalanceAfter).to.be.bignumber.equal(takerEthBalanceBefore.minus(totalEthSpent));
});
it('should fill orders with different makerAssetData', async () => {
const firstOrder = await maker.signOrderAsync();
const secondOrderMakerAssetData = encodeERC20AssetData(anotherErc20Token.address);
const secondOrder = await maker.signOrderAsync({
makerAssetData: secondOrderMakerAssetData,
});
await forwarder.approveMakerAssetProxy(secondOrderMakerAssetData).awaitTransactionSuccessAsync();
const orders = [firstOrder, secondOrder];
await testFactory.marketSellTestAsync(orders, 1.5);
});
it('should fail to fill an order with a fee denominated in an asset other than makerAsset or WETH', async () => {
const takerFeeAssetData = encodeERC20AssetData(anotherErc20Token.address);
const order = await maker.signOrderAsync({
takerFeeAssetData,
takerFee: toBaseUnitAmount(1),
});
const revertError = new ExchangeForwarderRevertErrors.UnsupportedFeeError(takerFeeAssetData);
await testFactory.marketSellTestAsync([order], 0.5, {
revertError,
});
});
it('should fill a partially-filled order without a taker fee', async () => {
const order = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([order], 0.3);
await testFactory.marketSellTestAsync([order], 0.8);
});
it('should skip over an order with an invalid maker asset amount', async () => {
const unfillableOrder = await maker.signOrderAsync({
makerAssetAmount: constants.ZERO_AMOUNT,
});
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([unfillableOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over an order with an invalid taker asset amount', async () => {
const unfillableOrder = await maker.signOrderAsync({
takerAssetAmount: constants.ZERO_AMOUNT,
});
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([unfillableOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over an expired order', async () => {
const currentTimestamp = await getLatestBlockTimestampAsync();
const expiredOrder = await maker.signOrderAsync({
expirationTimeSeconds: new BigNumber(currentTimestamp).minus(10),
});
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([expiredOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over a fully filled order', async () => {
const fullyFilledOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([fullyFilledOrder], 1);
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([fullyFilledOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over a cancelled order', async () => {
const cancelledOrder = await maker.signOrderAsync();
await maker.cancelOrderAsync(cancelledOrder);
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([cancelledOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
for (const orderAssetData of ['makerAssetData', 'makerFeeAssetData']) {
it(`should fill an order with StaticCall ${orderAssetData} if the StaticCall succeeds`, async () => {
const staticCallOrder = await maker.signOrderAsync({
[orderAssetData]: staticCallSuccessAssetData,
});
const nonStaticCallOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([staticCallOrder, nonStaticCallOrder], 1.5);
});
it(`should not fill an order with StaticCall ${orderAssetData} if the StaticCall fails`, async () => {
const staticCallOrder = await maker.signOrderAsync({
[orderAssetData]: staticCallFailureAssetData,
});
const nonStaticCallOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([staticCallOrder, nonStaticCallOrder], 1.5, { noopOrders: [0] });
});
}
it('should fill an order with multiAsset makerAssetData', async () => {
const multiAssetData = encodeMultiAssetData([new BigNumber(2)], [makerAssetData]);
const multiAssetOrder = await maker.signOrderAsync({
makerAssetData: multiAssetData,
});
const nonMultiAssetOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([multiAssetOrder, nonMultiAssetOrder], 1.3);
});
it('should fill an order with multiAsset makerAssetData (nested StaticCall succeeds)', async () => {
const multiAssetData = encodeMultiAssetData(
[new BigNumber(2), new BigNumber(3)],
[makerAssetData, staticCallSuccessAssetData],
);
const multiAssetOrder = await maker.signOrderAsync({
makerAssetData: multiAssetData,
});
const nonMultiAssetOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([multiAssetOrder, nonMultiAssetOrder], 1.3);
});
it('should skip over an order with multiAsset makerAssetData where the nested StaticCall fails', async () => {
const multiAssetData = encodeMultiAssetData(
[new BigNumber(2), new BigNumber(3)],
[makerAssetData, staticCallFailureAssetData],
);
const multiAssetOrder = await maker.signOrderAsync({
makerAssetData: multiAssetData,
});
const nonMultiAssetOrder = await maker.signOrderAsync();
await testFactory.marketSellTestAsync([multiAssetOrder, nonMultiAssetOrder], 1.3, { noopOrders: [0] });
});
});
blockchainTests.resets('marketSellOrdersWithEth with extra fees', () => {
it('should fill the order and send fee to feeRecipient', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(157),
takerAssetAmount: toBaseUnitAmount(36),
});
await testFactory.marketSellTestAsync([order], 0.67, {
forwarderFeeAmounts: [toBaseUnitAmount(0.2)],
forwarderFeeRecipientAddresses: [forwarderFeeRecipient.address],
});
});
it('should fill the order and send the same fees to different feeRecipient addresses', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(157),
takerAssetAmount: toBaseUnitAmount(36),
});
await testFactory.marketSellTestAsync([order], 0.67, {
forwarderFeeAmounts: [toBaseUnitAmount(0.2), toBaseUnitAmount(0.2)],
forwarderFeeRecipientAddresses: [randomAddress(), randomAddress()],
});
});
it('should fill the order and send different fees to different feeRecipient addresses', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(157),
takerAssetAmount: toBaseUnitAmount(36),
});
await testFactory.marketSellTestAsync([order], 0.67, {
forwarderFeeAmounts: [toBaseUnitAmount(0.2), toBaseUnitAmount(0.1)],
forwarderFeeRecipientAddresses: [randomAddress(), randomAddress()],
});
});
it('should fill the order and send the same fees to multiple instances of the same feeRecipient address', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(157),
takerAssetAmount: toBaseUnitAmount(36),
});
const feeRecipient = randomAddress();
await testFactory.marketSellTestAsync([order], 0.67, {
forwarderFeeAmounts: [toBaseUnitAmount(0.2), toBaseUnitAmount(0.2)],
forwarderFeeRecipientAddresses: [feeRecipient, feeRecipient],
});
});
it('should fill the order and send different fees to multiple instances of the same feeRecipient address', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(157),
takerAssetAmount: toBaseUnitAmount(36),
});
const feeRecipient = randomAddress();
await testFactory.marketSellTestAsync([order], 0.67, {
forwarderFeeAmounts: [toBaseUnitAmount(0.2), toBaseUnitAmount(0.1)],
forwarderFeeRecipientAddresses: [feeRecipient, feeRecipient],
});
});
it('should fail if ethFeeAmounts is longer than feeRecipients', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(157),
takerAssetAmount: toBaseUnitAmount(36),
});
const forwarderFeeAmounts = [toBaseUnitAmount(0.2)];
const forwarderFeeRecipientAddresses: string[] = [];
const revertError = new MixinWethUtilsRevertErrors.EthFeeLengthMismatchError(
new BigNumber(forwarderFeeAmounts.length),
new BigNumber(forwarderFeeRecipientAddresses.length),
);
await testFactory.marketSellTestAsync([order], 0.67, {
forwarderFeeAmounts,
forwarderFeeRecipientAddresses,
revertError,
});
});
it('should fail if feeRecipients is longer than ethFeeAmounts', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(157),
takerAssetAmount: toBaseUnitAmount(36),
});
const forwarderFeeAmounts: BigNumber[] = [];
const forwarderFeeRecipientAddresses = [randomAddress()];
const revertError = new MixinWethUtilsRevertErrors.EthFeeLengthMismatchError(
new BigNumber(forwarderFeeAmounts.length),
new BigNumber(forwarderFeeRecipientAddresses.length),
);
await testFactory.marketSellTestAsync([order], 0.67, {
forwarderFeeAmounts,
forwarderFeeRecipientAddresses,
revertError,
});
});
});
blockchainTests.resets('marketSellAmountWithEth', () => {
it('should fail if the supplied amount is not sold', async () => {
const order = await maker.signOrderAsync();
const ethSellAmount = order.takerAssetAmount;
const revertError = new ExchangeForwarderRevertErrors.CompleteSellFailedError(
ethSellAmount,
order.takerAssetAmount.times(0.5).plus(DeploymentManager.protocolFee),
);
await testFactory.marketSellAmountTestAsync([order], ethSellAmount, 0.5, {
revertError,
});
});
it('should sell the supplied amount', async () => {
const order = await maker.signOrderAsync();
const ethSellAmount = order.takerAssetAmount;
await testFactory.marketSellAmountTestAsync([order], ethSellAmount, 1);
});
});
blockchainTests.resets('marketBuyOrdersWithEth without extra fees', () => {
it('should buy the exact amount of makerAsset in a single order', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(131),
takerAssetAmount: toBaseUnitAmount(20),
});
await testFactory.marketBuyTestAsync([order], 0.62);
});
it('should buy the exact amount of makerAsset in multiple orders', async () => {
const firstOrder = await maker.signOrderAsync();
const secondOrder = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(77),
takerAssetAmount: toBaseUnitAmount(11),
});
const orders = [firstOrder, secondOrder];
await testFactory.marketBuyTestAsync(orders, 1.96);
});
it('should buy exactly makerAssetBuyAmount in orders with different makerAssetData', async () => {
const firstOrder = await maker.signOrderAsync();
const secondOrderMakerAssetData = encodeERC20AssetData(anotherErc20Token.address);
const secondOrder = await maker.signOrderAsync({
makerAssetData: secondOrderMakerAssetData,
});
await forwarder.approveMakerAssetProxy(secondOrderMakerAssetData).awaitTransactionSuccessAsync();
const orders = [firstOrder, secondOrder];
await testFactory.marketBuyTestAsync(orders, 1.5);
});
it('should buy the exact amount of makerAsset and return excess ETH', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(80),
takerAssetAmount: toBaseUnitAmount(17),
});
await testFactory.marketBuyTestAsync([order], 0.57, {
ethValueAdjustment: 2,
});
});
it('should buy the exact amount of makerAsset from a single order with a WETH fee', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(79),
takerAssetAmount: toBaseUnitAmount(16),
takerFee: toBaseUnitAmount(1),
takerFeeAssetData: wethAssetData,
});
await testFactory.marketBuyTestAsync([order], 0.38);
});
it('should buy the exact amount of makerAsset from a single order with a percentage fee', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(80),
takerAssetAmount: toBaseUnitAmount(17),
takerFee: toBaseUnitAmount(1),
takerFeeAssetData: makerAssetData,
});
await testFactory.marketBuyTestAsync([order], 0.52);
});
it('should revert if the amount of ETH sent is too low to fill the makerAssetAmount', async () => {
const order = await maker.signOrderAsync();
const revertError = new ExchangeForwarderRevertErrors.CompleteBuyFailedError(
order.makerAssetAmount.times(0.5),
constants.ZERO_AMOUNT,
);
await testFactory.marketBuyTestAsync([order], 0.5, {
ethValueAdjustment: -2,
revertError,
});
});
it('should buy an ERC721 asset from a single order', async () => {
const erc721Order = await maker.signOrderAsync({
makerAssetAmount: new BigNumber(1),
makerAssetData: encodeERC721AssetData(erc721Token.address, nftId),
takerFeeAssetData: wethAssetData,
});
await testFactory.marketBuyTestAsync([erc721Order], 1);
});
it('should buy an ERC721 asset and pay a WETH fee', async () => {
const erc721orderWithWethFee = await maker.signOrderAsync({
makerAssetAmount: new BigNumber(1),
makerAssetData: encodeERC721AssetData(erc721Token.address, nftId),
takerFee: toBaseUnitAmount(1),
takerFeeAssetData: wethAssetData,
});
await testFactory.marketBuyTestAsync([erc721orderWithWethFee], 1);
});
it('should fail to fill an order with a fee denominated in an asset other than makerAsset or WETH', async () => {
const takerFeeAssetData = encodeERC20AssetData(anotherErc20Token.address);
const order = await maker.signOrderAsync({
takerFeeAssetData,
takerFee: toBaseUnitAmount(1),
});
const revertError = new ExchangeForwarderRevertErrors.UnsupportedFeeError(takerFeeAssetData);
await testFactory.marketBuyTestAsync([order], 0.5, {
revertError,
});
});
it('should fill a partially-filled order without a taker fee', async () => {
const order = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([order], 0.3);
await testFactory.marketBuyTestAsync([order], 0.8);
});
it('should skip over an order with an invalid maker asset amount', async () => {
const unfillableOrder = await maker.signOrderAsync({
makerAssetAmount: constants.ZERO_AMOUNT,
});
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([unfillableOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over an order with an invalid taker asset amount', async () => {
const unfillableOrder = await maker.signOrderAsync({
takerAssetAmount: constants.ZERO_AMOUNT,
});
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([unfillableOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over an expired order', async () => {
const currentTimestamp = await getLatestBlockTimestampAsync();
const expiredOrder = await maker.signOrderAsync({
expirationTimeSeconds: new BigNumber(currentTimestamp).minus(10),
});
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([expiredOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over a fully filled order', async () => {
const fullyFilledOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([fullyFilledOrder], 1);
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([fullyFilledOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('should skip over a cancelled order', async () => {
const cancelledOrder = await maker.signOrderAsync();
await maker.cancelOrderAsync(cancelledOrder);
const fillableOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([cancelledOrder, fillableOrder], 1.5, { noopOrders: [0] });
});
it('Should buy slightly greater makerAsset when exchange rate is rounded', async () => {
// The 0x Protocol contracts round the exchange rate in favor of the Maker.
// In this case, the taker must round up how much they're going to spend, which
// in turn increases the amount of MakerAsset being purchased.
// Example:
// The taker wants to buy 5 units of the MakerAsset at a rate of 3M/2T.
// For every 2 units of TakerAsset, the taker will receive 3 units of MakerAsset.
// To purchase 5 units, the taker must spend 10/3 = 3.33 units of TakerAssset.
// However, the Taker can only spend whole units.
// Spending floor(10/3) = 3 units will yield a profit of Floor(3*3/2) = Floor(4.5) = 4 units of MakerAsset.
// Spending ceil(10/3) = 4 units will yield a profit of Floor(4*3/2) = 6 units of MakerAsset.
//
// The forwarding contract will opt for the second option, which overbuys, to ensure the taker
// receives at least the amount of MakerAsset they requested.
//
// Construct test case using values from example above
const order = await maker.signOrderAsync({
makerAssetAmount: new BigNumber('30'),
takerAssetAmount: new BigNumber('20'),
makerFee: new BigNumber(0),
takerFee: new BigNumber(0),
});
const desiredMakerAssetFillAmount = new BigNumber('5');
const makerAssetFillAmount = new BigNumber('6');
const primaryTakerAssetFillAmount = new BigNumber('4');
const ethValue = primaryTakerAssetFillAmount.plus(DeploymentManager.protocolFee);
await balanceStore.updateBalancesAsync();
// Execute test case
const tx = await forwarder
.marketBuyOrdersWithEth([order], desiredMakerAssetFillAmount, [order.signature], [], [])
.awaitTransactionSuccessAsync({
value: ethValue,
from: taker.address,
});
// Compute expected balances
const expectedBalances = LocalBalanceStore.create(balanceStore);
expectedBalances.transferAsset(maker.address, taker.address, makerAssetFillAmount, makerAssetData);
expectedBalances.wrapEth(taker.address, deployment.tokens.weth.address, ethValue);
expectedBalances.transferAsset(taker.address, maker.address, primaryTakerAssetFillAmount, wethAssetData);
expectedBalances.transferAsset(
taker.address,
deployment.staking.stakingProxy.address,
DeploymentManager.protocolFee,
wethAssetData,
);
expectedBalances.burnGas(tx.from, DeploymentManager.gasPrice.times(tx.gasUsed));
// Verify balances
await balanceStore.updateBalancesAsync();
balanceStore.assertEquals(expectedBalances);
});
it('Should buy slightly greater MakerAsset when exchange rate is rounded (Regression Test)', async () => {
// Order taken from a transaction on mainnet that failed due to a rounding error.
const order = await maker.signOrderAsync({
makerAssetAmount: new BigNumber('268166666666666666666'),
takerAssetAmount: new BigNumber('219090625878836371'),
makerFee: new BigNumber(0),
takerFee: new BigNumber(0),
});
// The taker will receive more than the desired amount of makerAsset due to rounding
const desiredMakerAssetFillAmount = new BigNumber('5000000000000000000');
const takerAssetFillAmount = new BigNumber('4084971271824171');
const makerAssetFillAmount = takerAssetFillAmount
.times(order.makerAssetAmount)
.dividedToIntegerBy(order.takerAssetAmount);
await balanceStore.updateBalancesAsync();
// Execute test case
const tx = await forwarder
.marketBuyOrdersWithEth([order], desiredMakerAssetFillAmount, [order.signature], [], [])
.awaitTransactionSuccessAsync({
value: takerAssetFillAmount.plus(DeploymentManager.protocolFee),
from: taker.address,
});
// Compute expected balances
const expectedBalances = LocalBalanceStore.create(balanceStore);
expectedBalances.transferAsset(maker.address, taker.address, makerAssetFillAmount, makerAssetData);
expectedBalances.wrapEth(
taker.address,
deployment.tokens.weth.address,
takerAssetFillAmount.plus(DeploymentManager.protocolFee),
);
expectedBalances.transferAsset(taker.address, maker.address, takerAssetFillAmount, wethAssetData);
expectedBalances.transferAsset(
taker.address,
deployment.staking.stakingProxy.address,
DeploymentManager.protocolFee,
wethAssetData,
);
expectedBalances.burnGas(tx.from, DeploymentManager.gasPrice.times(tx.gasUsed));
// Verify balances
await balanceStore.updateBalancesAsync();
balanceStore.assertEquals(expectedBalances);
});
for (const orderAssetData of ['makerAssetData', 'makerFeeAssetData', 'takerFeeAssetData']) {
it(`should fill an order with StaticCall ${orderAssetData} if the StaticCall succeeds`, async () => {
const staticCallOrder = await maker.signOrderAsync({
[orderAssetData]: staticCallSuccessAssetData,
});
const nonStaticCallOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([staticCallOrder, nonStaticCallOrder], 1.5);
});
it(`should not fill an order with StaticCall ${orderAssetData} if the StaticCall fails`, async () => {
const staticCallOrder = await maker.signOrderAsync({
[orderAssetData]: staticCallFailureAssetData,
});
const nonStaticCallOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([staticCallOrder, nonStaticCallOrder], 1.5, { noopOrders: [0] });
});
}
it('should fill an order with multiAsset makerAssetData', async () => {
const multiAssetData = encodeMultiAssetData([new BigNumber(2)], [makerAssetData]);
const multiAssetOrder = await maker.signOrderAsync({
makerAssetData: multiAssetData,
});
const nonMultiAssetOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([multiAssetOrder, nonMultiAssetOrder], 1.3);
});
it('should fill an order with multiAsset makerAssetData (nested StaticCall succeeds)', async () => {
const multiAssetData = encodeMultiAssetData(
[new BigNumber(2), new BigNumber(3)],
[makerAssetData, staticCallSuccessAssetData],
);
const multiAssetOrder = await maker.signOrderAsync({
makerAssetData: multiAssetData,
});
const nonMultiAssetOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([multiAssetOrder, nonMultiAssetOrder], 1.3);
});
it('should skip over an order with multiAsset makerAssetData where the nested StaticCall fails', async () => {
const multiAssetData = encodeMultiAssetData(
[new BigNumber(2), new BigNumber(3)],
[makerAssetData, staticCallFailureAssetData],
);
const multiAssetOrder = await maker.signOrderAsync({
makerAssetData: multiAssetData,
});
const nonMultiAssetOrder = await maker.signOrderAsync();
await testFactory.marketBuyTestAsync([multiAssetOrder, nonMultiAssetOrder], 1.3, { noopOrders: [0] });
});
});
blockchainTests.resets('marketBuyOrdersWithEth with extra fees', () => {
it('should buy the asset and send fee to feeRecipient', async () => {
const order = await maker.signOrderAsync({
makerAssetAmount: toBaseUnitAmount(125),
takerAssetAmount: toBaseUnitAmount(11),
});
await testFactory.marketBuyTestAsync([order], 0.33, {
forwarderFeeAmounts: [toBaseUnitAmount(0.2)],
forwarderFeeRecipientAddresses: [randomAddress()],
});
});
it('should fail if there is not enough ETH remaining to complete the fill', async () => {
const order = await maker.signOrderAsync();
const forwarderFeeAmounts = [toBaseUnitAmount(1)];
const revertError = new ExchangeForwarderRevertErrors.CompleteBuyFailedError(
order.takerAssetAmount,
constants.ZERO_AMOUNT,
);
await testFactory.marketBuyTestAsync([order], 0.5, {
ethValueAdjustment: -1,
forwarderFeeAmounts,
forwarderFeeRecipientAddresses: [randomAddress()],
revertError,
});
});
it('should fail if there is not enough ETH remaining to pay the fee', async () => {
const order = await maker.signOrderAsync();
const forwarderFeeAmounts = [toBaseUnitAmount(1)];
const value = forwarderFeeAmounts[0].minus(1);
const revertError = new MixinWethUtilsRevertErrors.InsufficientEthForFeeError(
forwarderFeeAmounts[0],
value,
);
await testFactory.marketBuyTestAsync([order], 0, {
revertError,
ethValueAdjustment: -1,
forwarderFeeAmounts,
forwarderFeeRecipientAddresses: [randomAddress()],
});
});
});
});
// tslint:disable:max-file-line-count | the_stack |
import type { b64string } from '@tanker/crypto';
import { tcrypto, utils } from '@tanker/crypto';
import { TankerError, DeviceRevoked, InternalError, InvalidArgument, InvalidVerification, OperationCanceled, PreconditionFailed } from '@tanker/errors';
import { fetch, retry, exponentialDelayGenerator } from '@tanker/http-utils';
import type { DelayGenerator } from '@tanker/http-utils';
import { PromiseWrapper } from '../PromiseWrapper';
import { TaskQueue } from '../TaskQueue';
import { signChallenge } from './Authenticator';
import { genericErrorHandler } from './ErrorHandler';
import { b64RequestObject, urlize } from './utils';
import type { ProvisionalKeysRequest, VerificationRequest } from '../LocalUser/requests';
import type { PublicProvisionalIdentityTarget } from '../Identity/identity';
import type {
FileUploadURLResponse, FileDownloadURLResponse,
TankerProvisionalIdentityResponse, VerificationMethodResponse,
} from './types';
export const defaultApiEndpoint = 'https://api.tanker.io';
export type ClientOptions = {
instanceInfo: { id: string; };
sdkInfo: { type: string; version: string; };
url?: string;
};
export type ServerPublicProvisionalIdentity = {
app_id: b64string;
target: PublicProvisionalIdentityTarget;
value: string;
public_signature_key: b64string;
public_encryption_key: b64string;
};
export type PublicProvisionalIdentityResults = {
hashedEmails: Record<string, ServerPublicProvisionalIdentity>;
hashedPhoneNumbers: Record<string, ServerPublicProvisionalIdentity>;
};
export type PullOptions = {
isLight?: boolean;
};
const MAX_CONCURRENCY = 5;
const MAX_QUERY_STRING_ITEMS = 100;
function unique(vals: Array<string>): Array<string> {
return Array.from(new Set(vals));
}
/**
* Network communication
*/
export class Client {
declare _accessToken: string;
declare _apiEndpoint: string;
declare _apiRootPath: string;
declare _appId: Uint8Array;
declare _authenticating: Promise<void> | null;
declare _cancelationHandle: PromiseWrapper<void>;
declare _deviceId: Uint8Array | null;
declare _deviceSignatureKeyPair: tcrypto.SodiumKeyPair | null;
declare _fetchQueue: TaskQueue;
declare _instanceId: string;
declare _isRevoked: boolean;
declare _retryDelayGenerator: DelayGenerator;
declare _sdkType: string;
declare _sdkVersion: string;
declare _userId: Uint8Array;
constructor(appId: Uint8Array, userId: Uint8Array, options: ClientOptions) {
const { instanceInfo, sdkInfo, url } = { url: defaultApiEndpoint, ...options };
this._accessToken = '';
this._apiEndpoint = url.replace(/\/+$/, '');
this._apiRootPath = `/v2/apps/${urlize(appId)}`;
this._appId = appId;
this._cancelationHandle = new PromiseWrapper<void>();
this._deviceId = null;
this._deviceSignatureKeyPair = null;
this._fetchQueue = new TaskQueue(MAX_CONCURRENCY);
this._instanceId = instanceInfo.id;
this._isRevoked = false;
this._retryDelayGenerator = exponentialDelayGenerator;
this._sdkType = sdkInfo.type;
this._sdkVersion = sdkInfo.version;
this._userId = userId;
}
_cancelable = <R>(fun: (...args: Array<any>) => Promise<R>) => (...args: Array<any>) => {
// cancelationHandle.promise always rejects. Its returned type doesn't matter
if (this._cancelationHandle.settled) {
return this._cancelationHandle.promise as any as Promise<R>;
}
return Promise.race([this._cancelationHandle.promise as any as Promise<R>, fun(...args)]);
};
// Simple fetch wrapper with limited concurrency
_fetch = (input: RequestInfo, init?: RequestInit): Promise<Response> => {
const fn = () => fetch(input, init);
return this._fetchQueue.enqueue(fn);
};
// Simple _fetch wrapper with:
// - proper headers set (sdk info and authorization)
// - generic error handling
_baseApiCall = async (path: string, init?: RequestInit): Promise<any> => {
try {
if (!path || path[0] !== '/') {
throw new InvalidArgument('"path" should be non empty and start with "/"');
}
const headers = (init?.headers ? init.headers : {}) as Record<string, string>;
headers['X-Tanker-Instanceid'] = this._instanceId;
headers['X-Tanker-Sdktype'] = this._sdkType;
headers['X-Tanker-Sdkversion'] = this._sdkVersion;
if (this._accessToken) {
headers['Authorization'] = `Bearer ${this._accessToken}`; // eslint-disable-line dot-notation
}
const url = `${this._apiEndpoint}${this._apiRootPath}${path}`;
const response = await this._fetch(url, { ...init, headers });
if (response.status === 204) { // no-content: no JSON response to parse
return;
}
if (response.ok) {
// Keep the await here to benefit from the enclosing try/catch
// and common error handling
const responseJSON = await response.json();
return responseJSON;
}
// We use response.text() and manual JSON parsing here as the response
// may come from the load balancer (e.g. 502 errors), and thus not
// contain the common JSON format used in all our API responses
const responseText = await response.text();
let error;
try {
({ error } = JSON.parse(responseText));
} catch (_) {} // eslint-disable-line no-empty
if (!error) {
const details = responseText ? `response body: "${responseText}"` : 'empty response body';
const message = `"${response.status} ${response.statusText}" status with ${details}`;
error = { code: '<unknown>', message, status: response.status, trace_id: '<unknown>' };
}
const apiMethod = init && init.method || 'GET';
genericErrorHandler(apiMethod, url, error);
} catch (err) {
const e = err as Error;
if (e instanceof DeviceRevoked) this._isRevoked = true;
if (e instanceof TankerError) throw e;
throw new InternalError(e.toString());
}
};
// Advanced _baseApiCall wrapper with additional capabilities:
// - await authentication if in progress
// - smart retry on authentication failure (e.g. expired token)
// - call in progress can be canceled if close() called
_apiCall = this._cancelable(async (path: string, init?: RequestInit): Promise<any> => {
if (this._authenticating) {
await this._authenticating;
}
const accessToken = this._accessToken;
const retryOptions = {
delayGenerator: this._retryDelayGenerator,
retries: 1,
retryCondition: async (error: Error) => {
if (error instanceof PreconditionFailed && error.apiCode === 'invalid_token') {
// The access token we are using is invalid/expired.
//
// We could be in one of the following situations:
//
// 1. Another API call is already trying to re-authenticate
if (this._authenticating) {
await this._authenticating;
// 2. This is the first API call to attempt a re-authentication. This
// is also the recovery process when this API call occurs after a
// previous re-authentication failure (i.e. access token is '')
} else if (this._accessToken === accessToken) {
await this._authenticate();
}
// (else)
// 3. Another API call already completed a re-authentication
// We can safely retry now
return true;
}
return false;
},
};
return retry(() => this._baseApiCall(path, init), retryOptions);
});
_authenticate = this._cancelable((): Promise<void> => {
if (this._authenticating) {
return this._authenticating;
}
this._accessToken = '';
if (!this._deviceId)
throw new InternalError('Assertion error: trying to authenticate without a device id');
const deviceId = this._deviceId;
if (!this._deviceSignatureKeyPair)
throw new InternalError('Assertion error: trying to sign a challenge without a signature key pair');
const deviceSignatureKeyPair = this._deviceSignatureKeyPair;
const auth = async () => {
const { challenge } = await this._cancelable(
() => this._baseApiCall(`/devices/${urlize(deviceId)}/challenges`, { method: 'POST' }),
)();
const signature = signChallenge(deviceSignatureKeyPair, challenge);
const signaturePublicKey = deviceSignatureKeyPair.publicKey;
const { access_token: accessToken, is_revoked: isRevoked } = await this._cancelable(
() => this._baseApiCall(`/devices/${urlize(deviceId)}/sessions`, {
method: 'POST',
body: JSON.stringify(b64RequestObject({ signature, challenge, signature_public_key: signaturePublicKey })),
headers: { 'Content-Type': 'application/json' },
}),
)();
this._accessToken = accessToken;
this._isRevoked = isRevoked;
};
this._authenticating = auth().finally(() => {
this._authenticating = null;
});
return this._authenticating;
});
authenticateDevice = async (deviceId: Uint8Array, signatureKeyPair: tcrypto.SodiumKeyPair) => {
this._deviceId = deviceId;
this._deviceSignatureKeyPair = signatureKeyPair;
return this._authenticate().then(() => {
if (this._isRevoked) {
throw new DeviceRevoked();
}
});
};
getUser = async (): Promise<unknown | null> => {
const path = `/users/${urlize(this._userId)}`;
try {
const { user } = await this._apiCall(path);
return user;
} catch (e) {
if (e instanceof TankerError) {
if (e.apiCode === 'app_not_found') throw new PreconditionFailed(e);
if (e.apiCode === 'user_not_found') return null;
}
throw e;
}
};
getVerificationKey = async (body: any): Promise<Uint8Array> => {
const path = `/users/${urlize(this._userId)}/verification-key`;
const options = {
method: 'POST',
body: JSON.stringify(b64RequestObject(body)),
headers: { 'Content-Type': 'application/json' },
};
const { encrypted_verification_key: key } = await this._apiCall(path, options);
return utils.fromBase64(key);
};
getEncryptionKey = async (ghostDevicePublicSignatureKey: Uint8Array) => {
const query = `ghost_device_public_signature_key=${urlize(ghostDevicePublicSignatureKey)}`;
const path = `/users/${urlize(this._userId)}/encryption-key?${query}`;
try {
const { encrypted_user_private_encryption_key: key, ghost_device_id: id } = await this._apiCall(path);
return {
encryptedPrivateUserKey: utils.fromBase64(key),
deviceId: utils.fromBase64(id),
};
} catch (e) {
if (e instanceof TankerError) {
if (e.apiCode === 'device_not_found') throw new InvalidVerification(e);
}
throw e;
}
};
createUser = async (deviceId: Uint8Array, deviceSignatureKeyPair: tcrypto.SodiumKeyPair, body: any): Promise<void> => {
const path = `/users/${urlize(this._userId)}`;
const options = {
method: 'POST',
body: JSON.stringify(b64RequestObject(body)),
headers: { 'Content-Type': 'application/json' },
};
const { access_token: accessToken } = await this._apiCall(path, options);
this._accessToken = accessToken;
this._deviceId = deviceId;
this._deviceSignatureKeyPair = deviceSignatureKeyPair;
};
createDevice = async (deviceId: Uint8Array, deviceSignatureKeyPair: tcrypto.SodiumKeyPair, body: any): Promise<void> => {
const options = {
method: 'POST',
body: JSON.stringify(b64RequestObject(body)),
headers: { 'Content-Type': 'application/json' },
};
const { access_token: accessToken } = await this._apiCall('/devices', options);
this._accessToken = accessToken;
this._deviceId = deviceId;
this._deviceSignatureKeyPair = deviceSignatureKeyPair;
};
getUserHistories = async (query: string): Promise<{
root: b64string;
histories: Array<b64string>;
}> => {
const path = `/user-histories?${query}`;
const {
root,
histories,
} = await this._apiCall(path);
return {
root,
histories,
};
};
getRevokedDeviceHistory = async (): Promise<{ root: b64string; histories: Array<b64string>; }> => {
if (!this._deviceId)
throw new InternalError('Assertion error: trying to get revoked device history without a device id');
const deviceId = this._deviceId;
const { root, history: histories } = await this._apiCall(`/devices/${urlize(deviceId)}/revoked-device-history`);
return { root, histories };
};
getUserHistoriesByUserIds = async (userIds: Array<Uint8Array>, options: PullOptions) => {
const urlizedUserIds = unique(userIds.map(userId => urlize(userId)));
const result = { root: '' as b64string, histories: [] as Array<b64string> };
for (let i = 0; i < urlizedUserIds.length; i += MAX_QUERY_STRING_ITEMS) {
const query = `is_light=${options.isLight ? 'true' : 'false'}&user_ids[]=${urlizedUserIds.slice(i, i + MAX_QUERY_STRING_ITEMS).join('&user_ids[]=')}`;
const response = await this.getUserHistories(query);
result.root = response.root;
result.histories = result.histories.concat(response.histories);
}
return result;
};
getUserHistoriesByDeviceIds = async (deviceIds: Array<Uint8Array>, options: PullOptions) => {
if (!this._deviceId)
throw new InternalError('Assertion error: trying to get user histories without a device id');
if (this._isRevoked && deviceIds.length === 1 && utils.equalArray(deviceIds[0]!, this._deviceId)) {
return this.getRevokedDeviceHistory();
}
const urlizedDeviceIds = unique(deviceIds.map(deviceId => urlize(deviceId)));
const result: { root: b64string; histories: Array<b64string>; } = { root: '', histories: [] };
const gotBlocks = new Set();
for (let i = 0; i < urlizedDeviceIds.length; i += MAX_QUERY_STRING_ITEMS) {
const query = `is_light=${options.isLight ? 'true' : 'false'}&device_ids[]=${urlizedDeviceIds.slice(i, i + MAX_QUERY_STRING_ITEMS).join('&device_ids[]=')}`;
const response = await this.getUserHistories(query);
result.root = response.root;
// We may ask for the same user twice, but through two different device
// IDs. We can't use unique() here because we need to keep the order
// intact.
const withoutDuplicates = response.histories.filter(d => !gotBlocks.has(d));
result.histories = result.histories.concat(withoutDuplicates);
for (const block of withoutDuplicates)
gotBlocks.add(block);
}
return result;
};
getVerificationMethods = async (): Promise<VerificationMethodResponse> => {
const path = `/users/${urlize(this._userId)}/verification-methods`;
const { verification_methods: verificationMethods } = await this._apiCall(path);
return verificationMethods;
};
setVerificationMethod = async (body: any) => {
await this._apiCall(`/users/${urlize(this._userId)}/verification-methods`, {
method: 'POST',
body: JSON.stringify(b64RequestObject(body)),
headers: {
'Content-Type': 'application/json',
},
});
};
getResourceKey = async (resourceId: Uint8Array): Promise<b64string> => {
const query = `resource_ids[]=${urlize(resourceId)}`;
const { resource_keys: resourceKeys } = await this._apiCall(`/resource-keys?${query}`);
if (resourceKeys.length === 0) {
throw new InvalidArgument(`could not find key for resource: ${utils.toBase64(resourceId)}`);
}
return resourceKeys[0];
};
publishResourceKeys = async (body: any): Promise<void> => {
await this._apiCall('/resource-keys', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
};
revokeDevice = async (body: any): Promise<void> => {
await this._apiCall('/device-revocations', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
};
createGroup = async (body: any): Promise<void> => {
await this._apiCall('/user-groups', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
};
patchGroup = async (body: any): Promise<void> => {
await this._apiCall('/user-groups', {
method: 'PATCH',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
};
softUpdateGroup = async (body: any): Promise<void> => {
await this._apiCall('/user-groups/soft-update', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
};
getSessionToken = async (body: any): Promise<b64string> => {
const path = `/users/${urlize(this._userId)}/session-certificates`;
// eslint-disable-next-line camelcase
const { session_token: sessionToken } = await this._apiCall(path, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
return sessionToken;
};
getGroupHistories = (query: string): Promise<{ histories: Array<b64string>; }> => this._apiCall(`/user-group-histories?${query}&is_light=true`);
getGroupHistoriesByGroupIds = async (groupIds: Array<Uint8Array>): Promise<{ histories: Array<b64string>; }> => {
const result = { histories: [] as Array<b64string> };
for (let i = 0; i < groupIds.length; i += MAX_QUERY_STRING_ITEMS) {
const query = `user_group_ids[]=${groupIds.slice(i, i + MAX_QUERY_STRING_ITEMS).map(id => urlize(id)).join('&user_group_ids[]=')}`;
const response = await this.getGroupHistories(query);
result.histories = result.histories.concat(response.histories);
}
return result;
};
getGroupHistoriesByGroupPublicEncryptionKey = (groupPublicEncryptionKey: Uint8Array) => {
const query = `user_group_public_encryption_key=${urlize(groupPublicEncryptionKey)}`;
return this.getGroupHistories(query);
};
getFileUploadURL = (resourceId: Uint8Array, metadata: b64string, uploadContentLength: number): Promise<FileUploadURLResponse> => {
const query = `metadata=${urlize(metadata)}&upload_content_length=${uploadContentLength}`;
return this._apiCall(`/resources/${urlize(resourceId)}/upload-url?${query}`);
};
getFileDownloadURL = (resourceId: Uint8Array): Promise<FileDownloadURLResponse> => this._apiCall(`/resources/${urlize(resourceId)}/download-url`);
getPublicProvisionalIdentities = async (hashedEmails: Array<Uint8Array>, hashedPhoneNumbers: Array<Uint8Array>): Promise<PublicProvisionalIdentityResults> => {
const MAX_QUERY_ITEMS = 100; // This is probably route-specific, so doesn't need to be global
const result = {
hashedEmails: {},
hashedPhoneNumbers: {},
};
let done = 0;
while (done < hashedEmails.length + hashedPhoneNumbers.length) {
// First, get as many emails as we have left that can fit in one request
let hashedEmailsSlice: Array<Uint8Array> = [];
if (done < hashedEmails.length) {
const numEmailsToGet = Math.min(hashedEmails.length - done, MAX_QUERY_ITEMS);
hashedEmailsSlice = hashedEmails.slice(done, done + numEmailsToGet);
done += numEmailsToGet;
}
// If we had less than MAX_QUERY_ITEMS emails left, then there's room to start requesting phone numbers
let hashedPhoneNumbersSlice: Array<Uint8Array> = [];
if (hashedEmailsSlice.length < MAX_QUERY_ITEMS) {
const phonesDone = done - hashedEmails.length;
const numPhoneNumbersToGet = Math.min(hashedPhoneNumbers.length - phonesDone, MAX_QUERY_ITEMS - hashedEmailsSlice.length);
hashedPhoneNumbersSlice = hashedPhoneNumbers.slice(phonesDone, phonesDone + numPhoneNumbersToGet);
done += numPhoneNumbersToGet;
}
const options = {
method: 'POST',
body: JSON.stringify(b64RequestObject({
hashed_emails: hashedEmailsSlice,
hashed_phone_numbers: hashedPhoneNumbersSlice,
})),
headers: { 'Content-Type': 'application/json' },
};
const { public_provisional_identities: identitiesBatch } = await this._apiCall('/public-provisional-identities', options);
result.hashedEmails = { ...result.hashedEmails, ...identitiesBatch.hashed_emails };
result.hashedPhoneNumbers = { ...result.hashedPhoneNumbers, ...identitiesBatch.hashed_phone_numbers };
}
return result;
};
getProvisionalIdentityClaims = async (): Promise<Array<b64string>> => {
const path = `/users/${urlize(this._userId)}/provisional-identity-claims`;
const { provisional_identity_claims: claims } = await this._apiCall(path);
return claims;
};
getTankerProvisionalKeysFromSession = async (body: ProvisionalKeysRequest): Promise<TankerProvisionalIdentityResponse> => {
const path = `/users/${urlize(this._userId)}/tanker-provisional-keys`;
const options = {
method: 'POST',
body: JSON.stringify(b64RequestObject(body)),
headers: { 'Content-Type': 'application/json' },
};
const { tanker_provisional_keys: provisionalKeys } = await this._apiCall(path, options);
return provisionalKeys;
};
getTankerProvisionalKeysWithVerif = async (body: { verification: VerificationRequest }): Promise<TankerProvisionalIdentityResponse> => {
const options = {
method: 'POST',
body: JSON.stringify(b64RequestObject(body)),
headers: { 'Content-Type': 'application/json' },
};
const { tanker_provisional_keys: provisionalKeys } = await this._apiCall('/tanker-provisional-keys', options);
return provisionalKeys;
};
claimProvisionalIdentity = async (body: any): Promise<void> => {
await this._apiCall('/provisional-identity-claims', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
};
close = async (reason?: Error): Promise<void> => {
this._cancelationHandle.reject(new OperationCanceled('Closing the client', reason));
if (this._accessToken && this._deviceId) {
const deviceId = this._deviceId;
const path = `/devices/${urlize(deviceId)}/sessions`;
// HTTP status:
// 204: session successfully deleted
// 401: session already expired
// other: something unexpected happened -> ignore and continue closing ¯\_(ツ)_/¯
await this._baseApiCall(path, { method: 'DELETE' }).catch((error: TankerError) => {
if (error.httpStatus !== 401) {
console.error('Error while closing the network client', error);
}
});
}
this._accessToken = '';
this._deviceId = null;
this._deviceSignatureKeyPair = null;
};
} | the_stack |
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { grey } from '@ant-design/colors';
import { Alert, Button, Divider, message, Typography } from 'antd';
import { useHistory } from 'react-router';
import { ApolloError } from '@apollo/client';
import styled from 'styled-components';
import { ChromePicker } from 'react-color';
import ColorHash from 'color-hash';
import { PlusOutlined } from '@ant-design/icons';
import { useGetTagQuery } from '../../graphql/tag.generated';
import { EntityType, FacetMetadata, Maybe, Scalars } from '../../types.generated';
import { ExpandedOwner } from '../entity/shared/components/styled/ExpandedOwner';
import { EMPTY_MESSAGES } from '../entity/shared/constants';
import { navigateToSearchUrl } from '../search/utils/navigateToSearchUrl';
import { useEntityRegistry } from '../useEntityRegistry';
import { useUpdateDescriptionMutation, useSetTagColorMutation } from '../../graphql/mutations.generated';
import { useGetSearchResultsForMultipleQuery } from '../../graphql/search.generated';
import analytics, { EventType, EntityActionType } from '../analytics';
import { GetSearchResultsParams, SearchResultInterface } from '../entity/shared/components/styled/search/types';
import { AddOwnersModal } from '../entity/shared/containers/profile/sidebar/Ownership/AddOwnersModal';
import CopyUrn from './CopyUrn';
import EntityDropdown from '../entity/shared/EntityDropdown';
import { EntityMenuItems } from '../entity/shared/EntityDropdown/EntityDropdown';
function useWrappedSearchResults(params: GetSearchResultsParams) {
const { data, loading, error } = useGetSearchResultsForMultipleQuery(params);
return { data: data?.searchAcrossEntities, loading, error };
}
type SearchResultsInterface = {
/** The offset of the result set */
start: Scalars['Int'];
/** The number of entities included in the result set */
count: Scalars['Int'];
/** The total number of search results matching the query and filters */
total: Scalars['Int'];
/** The search result entities */
searchResults: Array<SearchResultInterface>;
/** Candidate facet aggregations used for search filtering */
facets?: Maybe<Array<FacetMetadata>>;
};
const TitleLabel = styled(Typography.Text)`
&&& {
color: ${grey[2]};
font-size: 12px;
display: block;
line-height: 20px;
font-weight: 700;
}
`;
const TitleText = styled(Typography.Text)`
&&& {
color: ${grey[10]};
font-weight: 700;
font-size: 20px;
line-height: 28px;
display: inline-block;
margin: 0px 7px;
}
`;
const ColorPicker = styled.div`
position: relative;
display: inline-block;
`;
const ColorPickerButton = styled.div`
width: 16px;
height: 16px;
border: none;
border-radius: 50%;
`;
const ColorPickerPopOver = styled.div`
position: absolute;
z-index: 100;
`;
const DescriptionLabel = styled(Typography.Text)`
&&& {
text-align: left;
font-weight: bold;
font-size: 14px;
line-height: 28px;
color: rgb(38, 38, 38);
}
`;
export const EmptyValue = styled.div`
&:after {
content: 'None';
color: #b7b7b7;
font-style: italic;
font-weight: 100;
}
`;
const DetailsLayout = styled.div`
display: flex;
justify-content: space-between;
`;
const StatsBox = styled.div`
width: 180px;
justify-content: left;
`;
const StatsLabel = styled(Typography.Text)`
&&& {
color: ${grey[10]};
font-size: 14px;
font-weight: 700;
line-height: 28px;
}
`;
const StatsButton = styled(Button)`
padding: 0px 0px;
margin-top: 0px;
font-weight: 700;
font-size: 12px;
line-height: 20px;
`;
const EmptyStatsText = styled(Typography.Text)`
font-size: 15px;
font-style: italic;
`;
const OwnerButtonEmptyTitle = styled.span`
font-weight: 700;
font-size: 12px;
line-height: 20px;
color: ${grey[10]};
`;
const OwnerButtonTitle = styled.span`
font-weight: 500;
font-size: 12px;
line-height: 20px;
color: ${grey[10]};
`;
const TagName = styled.div`
display: flex;
align-items: center;
justify-content: left;
`;
const ActionButtons = styled.div`
display: flex;
`;
const TagHeader = styled.div`
display: flex;
justify-content: space-between;
align-items: top;
`;
const { Paragraph } = Typography;
type Props = {
urn: string;
useGetSearchResults?: (params: GetSearchResultsParams) => {
data: SearchResultsInterface | undefined | null;
loading: boolean;
error: ApolloError | undefined;
};
};
const generateColor = new ColorHash({
saturation: 0.9,
});
/**
* Responsible for displaying metadata about a tag
*/
export default function TagStyleEntity({ urn, useGetSearchResults = useWrappedSearchResults }: Props) {
const history = useHistory();
const entityRegistry = useEntityRegistry();
const { loading, error, data, refetch } = useGetTagQuery({ variables: { urn } });
const [updateDescription] = useUpdateDescriptionMutation();
const [setTagColorMutation] = useSetTagColorMutation();
const entityAndSchemaQuery = `tags:"${data?.tag?.name}" OR fieldTags:"${data?.tag?.name}" OR editedFieldTags:"${data?.tag?.name}"`;
const entityQuery = `tags:"${data?.tag?.name}"`;
const description = data?.tag?.properties?.description || '';
const [updatedDescription, setUpdatedDescription] = useState('');
const hexColor = data?.tag?.properties?.colorHex || generateColor.hex(urn);
const [displayColorPicker, setDisplayColorPicker] = useState(false);
const [colorValue, setColorValue] = useState('');
const ownersEmpty = !data?.tag?.ownership?.owners?.length;
const [showAddModal, setShowAddModal] = useState(false);
const [copiedUrn, setCopiedUrn] = useState(false);
useEffect(() => {
setUpdatedDescription(description);
}, [description]);
useEffect(() => {
setColorValue(hexColor);
}, [hexColor]);
const { data: facetData, loading: facetLoading } = useGetSearchResults({
variables: {
input: {
query: entityAndSchemaQuery,
start: 0,
count: 1,
filters: [],
},
},
});
const facets = facetData?.facets?.filter((facet) => facet?.field === 'entity') || [];
const aggregations = facets && facets[0]?.aggregations;
// Save Color Change
const saveColor = useCallback(async () => {
if (displayColorPicker) {
try {
await setTagColorMutation({
variables: {
urn,
colorHex: colorValue,
},
});
message.destroy();
message.success({ content: 'Color Saved!', duration: 2 });
setDisplayColorPicker(false);
} catch (e: unknown) {
message.destroy();
if (e instanceof Error) {
message.error({ content: `Failed to save tag color: \n ${e.message || ''}`, duration: 2 });
}
}
refetch?.();
}
}, [urn, colorValue, displayColorPicker, setTagColorMutation, setDisplayColorPicker, refetch]);
const colorPickerRef = useRef(null);
useEffect(() => {
/**
* Save Color if Clicked outside of the Color Picker
*/
function handleClickOutsideColorPicker(event) {
if (displayColorPicker) {
const { current }: any = colorPickerRef;
if (current) {
if (!current.contains(event.target)) {
setDisplayColorPicker(false);
saveColor();
}
}
}
}
// Bind the event listener
document.addEventListener('mousedown', handleClickOutsideColorPicker);
return () => {
// Unbind the event listener on clean up
document.removeEventListener('mousedown', handleClickOutsideColorPicker);
};
}, [colorPickerRef, displayColorPicker, saveColor]);
const handlePickerClick = () => {
setDisplayColorPicker(!displayColorPicker);
saveColor();
};
const handleColorChange = (color: any) => {
setColorValue(color?.hex);
};
// Update Description
const updateDescriptionValue = (desc: string) => {
setUpdatedDescription(desc);
return updateDescription({
variables: {
input: {
description: desc,
resourceUrn: urn,
},
},
});
};
// Save the description
const handleSaveDescription = async (desc: string) => {
message.loading({ content: 'Saving...' });
try {
await updateDescriptionValue(desc);
message.destroy();
message.success({ content: 'Description Updated', duration: 2 });
analytics.event({
type: EventType.EntityActionEvent,
actionType: EntityActionType.UpdateDescription,
entityType: EntityType.Tag,
entityUrn: urn,
});
} catch (e: unknown) {
message.destroy();
if (e instanceof Error) {
message.error({ content: `Failed to update description: \n ${e.message || ''}`, duration: 2 });
}
}
refetch?.();
};
if (error || (!loading && !error && !data)) {
return <Alert type="error" message={error?.message || 'Entity failed to load'} />;
}
return (
<>
{/* Tag Title */}
<TagHeader>
<div>
<TitleLabel>Tag</TitleLabel>
<TagName>
<ColorPicker>
<ColorPickerButton style={{ backgroundColor: colorValue }} onClick={handlePickerClick} />
</ColorPicker>
<TitleText>
{(data?.tag && entityRegistry.getDisplayName(EntityType.Tag, data?.tag)) || ''}
</TitleText>
</TagName>
</div>
<ActionButtons>
<CopyUrn urn={urn} isActive={copiedUrn} onClick={() => setCopiedUrn(true)} />
<EntityDropdown menuItems={new Set([EntityMenuItems.COPY_URL])} />
</ActionButtons>
{displayColorPicker && (
<ColorPickerPopOver ref={colorPickerRef}>
<ChromePicker color={colorValue} onChange={handleColorChange} />
</ColorPickerPopOver>
)}
</TagHeader>
<Divider />
{/* Tag Description */}
<DescriptionLabel>About</DescriptionLabel>
<Paragraph
style={{ fontSize: '12px', lineHeight: '15px', padding: '5px 0px' }}
editable={{ onChange: handleSaveDescription }}
ellipsis={{ rows: 2, expandable: true, symbol: 'Read more' }}
>
{updatedDescription || <EmptyValue />}
</Paragraph>
<Divider />
{/* Tag Charts, Datasets and Owners */}
<DetailsLayout>
<StatsBox>
<StatsLabel>Applied to</StatsLabel>
{facetLoading && (
<div>
<EmptyStatsText>Loading...</EmptyStatsText>
</div>
)}
{!facetLoading && aggregations && aggregations?.length === 0 && (
<div>
<EmptyStatsText>No entities</EmptyStatsText>
</div>
)}
{!facetLoading &&
aggregations &&
aggregations?.map((aggregation) => {
if (aggregation?.count === 0) {
return null;
}
return (
<div key={aggregation?.value}>
<StatsButton
onClick={() =>
navigateToSearchUrl({
type: aggregation?.value as EntityType,
query:
aggregation?.value === EntityType.Dataset
? entityAndSchemaQuery
: entityQuery,
history,
})
}
type="link"
>
<span data-testid={`stats-${aggregation?.value}`}>
{aggregation?.count}{' '}
{entityRegistry.getCollectionName(aggregation?.value as EntityType)} >
</span>
</StatsButton>
</div>
);
})}
</StatsBox>
<div>
<StatsLabel>Owners</StatsLabel>
<div>
{data?.tag?.ownership?.owners?.map((owner) => (
<ExpandedOwner entityUrn={urn} owner={owner} refetch={refetch} hidePopOver />
))}
{ownersEmpty && (
<Typography.Paragraph type="secondary">
{EMPTY_MESSAGES.owners.title}. {EMPTY_MESSAGES.owners.description}
</Typography.Paragraph>
)}
<Button type={ownersEmpty ? 'default' : 'text'} onClick={() => setShowAddModal(true)}>
<PlusOutlined />
{ownersEmpty ? (
<OwnerButtonEmptyTitle>Add Owners</OwnerButtonEmptyTitle>
) : (
<OwnerButtonTitle>Add Owners</OwnerButtonTitle>
)}
</Button>
</div>
<div>
<AddOwnersModal
hideOwnerType
visible={showAddModal}
refetch={refetch}
onCloseModal={() => {
setShowAddModal(false);
}}
urn={urn}
type={EntityType.Tag}
/>
</div>
</div>
</DetailsLayout>
</>
);
} | the_stack |
import {
Matrix4,
BufferAttribute,
BufferGeometry,
Vector2,
Vector4,
Quaternion,
Matrix3,
Mesh,
Object3D,
Vector3,
CustomBlending,
SrcAlphaFactor,
OneMinusSrcAlphaFactor,
AddEquation,
DoubleSide,
ShaderMaterial,
Scene
} from 'three'
/**
* @author Mark Kellogg - http://www.github.com/mkkellogg
*/
//=======================================
// Trail Renderer
//=======================================
const MaxHeadVertices = 128
const PositionComponentCount = 3
const UVComponentCount = 2
const IndicesPerFace = 3
const FacesPerQuad = 2
const tempPosition = new Vector3()
const tempMatrix4 = new Matrix4()
const LocalOrientationTangent = new Vector3(1, 0, 0)
const LocalHeadOrigin = new Vector3(0, 0, 0)
const tempQuaternion = new Quaternion()
const tempOffset = new Vector3()
const tempLocalHeadGeometry: Vector3[] = []
const tempMatrix3 = new Matrix3()
const worldOrientation = new Vector3()
const tempDirection = new Vector3()
const tempLocalHeadGeometry2: Vector3[] = []
for (let i = 0; i < MaxHeadVertices; i++) {
const vertex = new Vector3()
tempLocalHeadGeometry2.push(vertex)
}
function getMatrix3FromMatrix4(matrix3, matrix4) {
const e = matrix4.elements
matrix3.set(e[0], e[1], e[2], e[4], e[5], e[6], e[8], e[9], e[10])
}
for (let i = 0; i < MaxHeadVertices; i++) {
const vertex = new Vector3()
tempLocalHeadGeometry.push(vertex)
}
const returnObj = {
attribute: null,
offset: 0,
count: -1
}
const returnObj2 = {
attribute: null,
offset: 0,
count: -1
}
const BaseVertexVars = [
'attribute float nodeID;',
'attribute float nodeVertexID;',
'attribute vec3 nodeCenter;',
'uniform float minID;',
'uniform float maxID;',
'uniform float trailLength;',
'uniform float maxTrailLength;',
'uniform float verticesPerNode;',
'uniform vec2 textureTileFactor;',
'uniform vec4 headColor;',
'uniform vec4 tailColor;',
'varying vec4 vColor;'
].join('\n')
const TexturedVertexVars = [BaseVertexVars, 'varying vec2 vUV;', 'uniform float dragTexture;'].join('\n')
const BaseFragmentVars = ['varying vec4 vColor;', 'uniform sampler2D texture;'].join('\n')
const TexturedFragmentVars = [BaseFragmentVars, 'varying vec2 vUV;'].join('\n')
const VertexShaderCore = [
'float fraction = ( maxID - nodeID ) / ( maxID - minID );',
'vColor = ( 1.0 - fraction ) * headColor + fraction * tailColor;',
'vec4 realPosition = vec4( ( 1.0 - fraction ) * position.xyz + fraction * nodeCenter.xyz, 1.0 ); '
].join('\n')
const BaseVertexShader = [
BaseVertexVars,
'void main() { ',
VertexShaderCore,
'gl_Position = projectionMatrix * viewMatrix * realPosition;',
'}'
].join('\n')
const BaseFragmentShader = [BaseFragmentVars, 'void main() { ', 'gl_FragColor = vColor;', '}'].join('\n')
const TexturedVertexShader = [
TexturedVertexVars,
'void main() { ',
VertexShaderCore,
'float s = 0.0;',
'float t = 0.0;',
'if ( dragTexture == 1.0 ) { ',
' s = fraction * textureTileFactor.s; ',
' t = ( nodeVertexID / verticesPerNode ) * textureTileFactor.t;',
'} else { ',
' s = nodeID / maxTrailLength * textureTileFactor.s;',
' t = ( nodeVertexID / verticesPerNode ) * textureTileFactor.t;',
'}',
'vUV = vec2( s, t ); ',
'gl_Position = projectionMatrix * viewMatrix * realPosition;',
'}'
].join('\n')
const TexturedFragmentShader = [
TexturedFragmentVars,
'void main() { ',
'vec4 textureColor = texture2D( texture, vUV );',
'gl_FragColor = vColor * textureColor;',
'}'
].join('\n')
class TrailRenderer extends Mesh {
orientToMovement = false
mesh: Mesh
nodeCenters: Vector3[]
lastNodeCenter: Vector3
currentNodeCenter: Vector3
lastOrientationDir: Vector3
nodeIDs: number[]
currentLength = 0
currentEnd = 0
currentNodeID = 0
length = 200
localHeadGeometry: Vector3[]
// Test fix
VerticesPerNode = 10
vertexCount = 10
faceCount = 10
FacesPerNode = 10
FaceIndicesPerNode = 10
targetObject: Object3D
dragTexture = false
static createMaterial(vertexShader, fragmentShader, customUniforms: any = {}) {
customUniforms.trailLength = { type: 'f', value: null }
customUniforms.verticesPerNode = { type: 'f', value: null }
customUniforms.minID = { type: 'f', value: null }
customUniforms.maxID = { type: 'f', value: null }
customUniforms.dragTexture = { type: 'f', value: null }
customUniforms.maxTrailLength = { type: 'f', value: null }
customUniforms.textureTileFactor = { type: 'v2', value: null }
customUniforms.headColor = { type: 'v4', value: new Vector4(1, 0, 0, 1) }
customUniforms.tailColor = { type: 'v4', value: new Vector4(0, 0, 1, 1) }
vertexShader = vertexShader || BaseVertexShader
fragmentShader = fragmentShader || BaseFragmentShader
return new ShaderMaterial({
uniforms: customUniforms,
vertexShader: vertexShader,
fragmentShader: fragmentShader,
transparent: true,
alphaTest: 0.5,
blending: CustomBlending,
blendSrc: SrcAlphaFactor,
blendDst: OneMinusSrcAlphaFactor,
blendEquation: AddEquation,
depthTest: true,
depthWrite: false,
side: DoubleSide
})
}
static createBaseMaterial(customUniforms: any = {}) {
return TrailRenderer.createMaterial(BaseVertexShader, BaseFragmentShader, customUniforms)
}
static createTexturedMaterial(customUniforms: any = {}) {
customUniforms.texture = { type: 't', value: null }
return TrailRenderer.createMaterial(TexturedVertexShader, TexturedFragmentShader, customUniforms)
}
constructor(orientToMovement) {
super()
this.matrixAutoUpdate = false
this.frustumCulled = false
if (orientToMovement) this.orientToMovement = true
}
initialize(
material: ShaderMaterial,
length: number,
dragTexture: boolean,
localHeadWidth: number,
localHeadGeometry: Vector3[],
targetObject: any
) {
this.length = length > 0 ? length + 1 : 0
this.dragTexture = dragTexture
this.targetObject = targetObject
this.initializeLocalHeadGeometry(localHeadWidth, localHeadGeometry)
this.nodeIDs = []
this.nodeCenters = []
for (let i = 0; i < this.length; i++) {
this.nodeIDs[i] = -1
this.nodeCenters[i] = new Vector3()
}
this.material = material
this.initializeGeometry()
material.uniforms.trailLength.value = 0
material.uniforms.minID.value = 0
material.uniforms.maxID.value = 0
material.uniforms.dragTexture.value = this.dragTexture
material.uniforms.maxTrailLength.value = this.length
material.uniforms.verticesPerNode.value = this.VerticesPerNode
material.uniforms.textureTileFactor.value = new Vector2(1.0, 1.0)
this.reset()
}
initializeLocalHeadGeometry(localHeadWidth: number, localHeadGeometry: Vector3[]) {
this.localHeadGeometry = []
if (!localHeadGeometry) {
const halfWidth = (localHeadWidth || 1.0) / 2.0
this.localHeadGeometry.push(new Vector3(-halfWidth, 0, 0))
this.localHeadGeometry.push(new Vector3(halfWidth, 0, 0))
this.VerticesPerNode = 2
} else {
this.VerticesPerNode = 0
for (let i = 0; i < localHeadGeometry.length && i < MaxHeadVertices; i++) {
const vertex = localHeadGeometry[i]
if (vertex && vertex instanceof Vector3) {
const vertexCopy = new Vector3()
vertexCopy.copy(vertex)
this.localHeadGeometry.push(vertexCopy)
this.VerticesPerNode++
}
}
}
this.FacesPerNode = (this.VerticesPerNode - 1) * 2
this.FaceIndicesPerNode = this.FacesPerNode * 3
}
initializeGeometry() {
this.vertexCount = this.length * this.VerticesPerNode
this.faceCount = this.length * this.FacesPerNode
const geometry = new BufferGeometry()
const nodeIDs = new Float32Array(this.vertexCount)
const nodeVertexIDs = new Float32Array(this.vertexCount * this.VerticesPerNode)
const positions = new Float32Array(this.vertexCount * PositionComponentCount)
const nodeCenters = new Float32Array(this.vertexCount * PositionComponentCount)
const uvs = new Float32Array(this.vertexCount * UVComponentCount)
const indices = new Uint32Array(this.faceCount * IndicesPerFace)
const nodeIDAttribute = new BufferAttribute(nodeIDs, 1)
geometry.setAttribute('nodeID', nodeIDAttribute)
const nodeVertexIDAttribute = new BufferAttribute(nodeVertexIDs, 1)
geometry.setAttribute('nodeVertexID', nodeVertexIDAttribute)
const nodeCenterAttribute = new BufferAttribute(nodeCenters, PositionComponentCount)
geometry.setAttribute('nodeCenter', nodeCenterAttribute)
const positionAttribute = new BufferAttribute(positions, PositionComponentCount)
geometry.setAttribute('position', positionAttribute)
const uvAttribute = new BufferAttribute(uvs, UVComponentCount)
geometry.setAttribute('uv', uvAttribute)
const indexAttribute = new BufferAttribute(indices, 1)
geometry.setIndex(indexAttribute)
this.geometry = geometry
}
zeroVertices() {
const positions = this.geometry.getAttribute('position') as BufferAttribute
for (let i = 0; i < this.vertexCount; i++) {
const index = i
positions.setXYZ(index, 0, 0, 0)
}
positions.needsUpdate = true
positions.updateRange.count = -1
}
zeroIndices() {
const indices = this.geometry.getIndex()!
for (let i = 0; i < this.faceCount; i++) {
const index = i * 3
indices.setXYZ(index, 0, 0, 0)
}
indices.needsUpdate = true
indices.updateRange.count = -1
}
formInitialFaces() {
this.zeroIndices()
const indices = this.geometry.getIndex()!
for (let i = 0; i < this.length - 1; i++) {
this.connectNodes(i, i + 1)
}
indices.needsUpdate = true
indices.updateRange.count = -1
}
reset() {
this.currentLength = 0
this.currentEnd = -1
this.lastNodeCenter = null!
this.currentNodeCenter = null!
this.lastOrientationDir = null!
this.currentNodeID = 0
this.formInitialFaces()
this.zeroVertices()
this.geometry.setDrawRange(0, 0)
}
updateUniforms() {
const material = this.material as ShaderMaterial
if (this.currentLength < this.length) {
material.uniforms.minID.value = 0
} else {
material.uniforms.minID.value = this.currentNodeID - this.length
}
material.uniforms.maxID.value = this.currentNodeID
material.uniforms.trailLength.value = this.currentLength
material.uniforms.maxTrailLength.value = this.length
material.uniforms.verticesPerNode.value = this.VerticesPerNode
}
advance() {
this.targetObject.updateMatrixWorld()
tempMatrix4.copy(this.targetObject.matrixWorld)
this.advanceWithTransform(tempMatrix4)
this.updateUniforms()
}
advanceWithPositionAndOrientation(nextPosition, orientationTangent) {
this.advanceGeometry({ position: nextPosition, tangent: orientationTangent }, null)
}
advanceWithTransform(transformMatrix) {
this.advanceGeometry(null, transformMatrix)
}
advanceGeometry(positionAndOrientation, transformMatrix) {
const nextIndex = this.currentEnd + 1 >= this.length ? 0 : this.currentEnd + 1
if (transformMatrix) {
this.updateNodePositionsFromTransformMatrix(nextIndex, transformMatrix)
} else if (positionAndOrientation) {
this.updateNodePositionsFromOrientationTangent(
nextIndex,
positionAndOrientation.position,
positionAndOrientation.tangent
)
}
if (this.currentLength >= 1) {
this.connectNodes(this.currentEnd, nextIndex)
if (this.currentLength >= this.length) {
const disconnectIndex = this.currentEnd + 1 >= this.length ? 0 : this.currentEnd + 1
this.disconnectNodes(disconnectIndex)
}
}
if (this.currentLength < this.length) {
this.currentLength++
}
this.currentEnd++
if (this.currentEnd >= this.length) {
this.currentEnd = 0
}
if (this.currentLength >= 1) {
if (this.currentLength < this.length) {
this.geometry.setDrawRange(0, (this.currentLength - 1) * this.FaceIndicesPerNode)
} else {
this.geometry.setDrawRange(0, this.currentLength * this.FaceIndicesPerNode)
}
}
this.updateNodeID(this.currentEnd, this.currentNodeID)
this.currentNodeID++
}
updateHead() {
if (this.currentEnd < 0) return
this.targetObject.updateMatrixWorld()
tempMatrix4.copy(this.targetObject.matrixWorld)
this.updateNodePositionsFromTransformMatrix(this.currentEnd, tempMatrix4)
}
updateNodeID(nodeIndex, id) {
this.nodeIDs[nodeIndex] = id
const nodeIDs = this.geometry.getAttribute('nodeID') as BufferAttribute
const nodeVertexIDs = this.geometry.getAttribute('nodeVertexID') as BufferAttribute
// TODO: clean this up, use set properly rather than iterating
for (let i = 0; i < this.VerticesPerNode; i++) {
const baseIndex = nodeIndex * this.VerticesPerNode + i
nodeIDs.set([id], baseIndex)
nodeVertexIDs.set([i], baseIndex)
}
nodeIDs.needsUpdate = true
nodeVertexIDs.needsUpdate = true
nodeIDs.updateRange.offset = nodeIndex * this.VerticesPerNode
nodeIDs.updateRange.count = this.VerticesPerNode
nodeVertexIDs.updateRange.offset = nodeIndex * this.VerticesPerNode
nodeVertexIDs.updateRange.count = this.VerticesPerNode
}
updateNodeCenter(nodeIndex, nodeCenter) {
this.lastNodeCenter = this.currentNodeCenter
this.currentNodeCenter = this.nodeCenters[nodeIndex]
this.currentNodeCenter.copy(nodeCenter)
const nodeCenters = this.geometry.getAttribute('nodeCenter') as BufferAttribute
for (let i = 0; i < this.VerticesPerNode; i++) {
const baseIndex = nodeIndex * this.VerticesPerNode + i
nodeCenters.setXYZ(baseIndex, nodeCenter.x, nodeCenter.y, nodeCenter.z)
}
nodeCenters.needsUpdate = true
nodeCenters.updateRange.offset = nodeIndex * this.VerticesPerNode * PositionComponentCount
nodeCenters.updateRange.count = this.VerticesPerNode * PositionComponentCount
}
updateNodePositionsFromOrientationTangent(nodeIndex, nodeCenter, orientationTangent) {
const positions = this.geometry.getAttribute('position') as BufferAttribute
this.updateNodeCenter(nodeIndex, nodeCenter)
tempOffset.copy(nodeCenter)
tempOffset.sub(LocalHeadOrigin)
tempQuaternion.setFromUnitVectors(LocalOrientationTangent, orientationTangent)
for (let i = 0; i < this.localHeadGeometry.length; i++) {
const vertex = tempLocalHeadGeometry[i]
vertex.copy(this.localHeadGeometry[i])
vertex.applyQuaternion(tempQuaternion)
vertex.add(tempOffset)
}
for (let i = 0; i < this.localHeadGeometry.length; i++) {
const positionIndex = this.VerticesPerNode * nodeIndex + i
const transformedHeadVertex = tempLocalHeadGeometry[i]
positions.setXYZ(positionIndex, transformedHeadVertex.x, transformedHeadVertex.y, transformedHeadVertex.z)
}
positions.needsUpdate = true
}
updateNodePositionsFromTransformMatrix(nodeIndex, transformMatrix) {
const positions = this.geometry.getAttribute('position') as BufferAttribute
tempPosition.set(0, 0, 0)
tempPosition.applyMatrix4(transformMatrix)
this.updateNodeCenter(nodeIndex, tempPosition)
for (let i = 0; i < this.localHeadGeometry.length; i++) {
const vertex2 = tempLocalHeadGeometry2[i]
vertex2.copy(this.localHeadGeometry[i])
}
for (let i = 0; i < this.localHeadGeometry.length; i++) {
const vertex3 = tempLocalHeadGeometry2[i]
vertex3.applyMatrix4(transformMatrix)
}
if (this.lastNodeCenter && this.orientToMovement) {
getMatrix3FromMatrix4(tempMatrix3, transformMatrix)
worldOrientation.set(0, 0, -1)
worldOrientation.applyMatrix3(tempMatrix3)
tempDirection.copy(this.currentNodeCenter)
tempDirection.sub(this.lastNodeCenter)
tempDirection.normalize()
if (tempDirection.lengthSq() <= 0.0001 && this.lastOrientationDir) {
tempDirection.copy(this.lastOrientationDir)
}
if (tempDirection.lengthSq() > 0.0001) {
if (!this.lastOrientationDir) this.lastOrientationDir = new Vector3()
tempQuaternion.setFromUnitVectors(worldOrientation, tempDirection)
tempOffset.copy(this.currentNodeCenter)
for (let i = 0; i < this.localHeadGeometry.length; i++) {
const vertex4 = tempLocalHeadGeometry2[i]
vertex4.sub(tempOffset)
vertex4.applyQuaternion(tempQuaternion)
vertex4.add(tempOffset)
}
}
}
for (let i = 0; i < this.localHeadGeometry.length; i++) {
const positionIndex = this.VerticesPerNode * nodeIndex + i
const transformedHeadVertex = tempLocalHeadGeometry2[i]
positions.setXYZ(positionIndex, transformedHeadVertex.x, transformedHeadVertex.y, transformedHeadVertex.z)
}
positions.needsUpdate = true
positions.updateRange.offset = nodeIndex * this.VerticesPerNode * PositionComponentCount
positions.updateRange.count = this.VerticesPerNode * PositionComponentCount
}
connectNodes(srcNodeIndex, destNodeIndex) {
const indices = this.geometry.getIndex()!
for (let i = 0; i < this.localHeadGeometry.length - 1; i++) {
const srcVertexIndex = this.VerticesPerNode * srcNodeIndex + i
const destVertexIndex = this.VerticesPerNode * destNodeIndex + i
const faceIndex = (srcNodeIndex * this.FacesPerNode + i * FacesPerQuad) * IndicesPerFace
indices.set(
[srcVertexIndex, destVertexIndex, srcVertexIndex + 1, destVertexIndex, destVertexIndex + 1, srcVertexIndex + 1],
faceIndex
)
}
indices.needsUpdate = true
indices.updateRange.count = -1
// returnObj.attribute = indices
// returnObj.offset = srcNodeIndex * this.FacesPerNode * IndicesPerFace
// returnObj.count = this.FacesPerNode * IndicesPerFace
// return returnObj
}
disconnectNodes(srcNodeIndex) {
const indices = this.geometry.getIndex()!
for (let i = 0; i < this.localHeadGeometry.length - 1; i++) {
const faceIndex = (srcNodeIndex * this.FacesPerNode + i * FacesPerQuad) * IndicesPerFace
indices.set([0, 0, 0, 0, 0, 0], faceIndex)
}
indices.needsUpdate = true
indices.updateRange.count = -1
// returnObj2.attribute = indices
// returnObj2.offset = srcNodeIndex * this.FacesPerNode * IndicesPerFace
// returnObj2.count = this.FacesPerNode * IndicesPerFace
// return returnObj2
}
}
export default TrailRenderer | the_stack |
import {Injectable} from '@angular/core';
import {StreamService} from '../../shared/api/stream.service';
import {AppService} from '../../shared/api/app.service';
import {Stream, StreamDeployConfig} from '../../shared/model/stream.model';
import {forkJoin, Observable, of} from 'rxjs';
import {map, mergeMap} from 'rxjs/operators';
import {App, ApplicationType} from '../../shared/model/app.model';
import {Platform} from '../../shared/model/platform.model';
import {ConfigurationMetadataProperty, DetailedApp} from '../../shared/model/detailed-app.model';
import {Utils} from '../../flo/shared/support/utils';
import get from 'lodash.get';
import set from 'lodash.set';
import {ParserService} from '../../flo/shared/service/parser.service';
/**
* Provides {@link StreamDeployConfig} related services.
*
* @author Damien Vitrac
* @author Janne Valkealahti
*/
@Injectable()
export class StreamDeployService {
/**
* Platform key validation
*/
public static platform = {
is: (key: string): boolean => /^(spring\.cloud\.dataflow\.skipper\.platformName)$/.test(key)
};
/**
* Deployer key validation
*/
public static deployer = {
keyEdit: 'spring.cloud.deployer.',
is: (key: string): boolean => /^(deployer\.)/.test(key),
extract: (key: string): string => {
const result = key.split('.');
if (result.length < 3) {
return '';
}
return result.slice(2, result.length).join('.');
}
};
/**
* Version key validation
*/
public static version = {
keyEdit: 'version',
is: (key: string): boolean => /^(version\.)/.test(key)
};
/**
* App key validation
*/
public static app = {
is: (key: string): boolean => /^(app\.)/.test(key),
extract: (key: string): string => {
const result = key.split('.');
if (result.length < 3) {
return '';
}
return result.slice(2, result.length).join('.');
}
};
constructor(
private streamService: StreamService,
private appService: AppService,
private parserService: ParserService
) {}
/**
* Provide an observable of {@link StreamDeployConfig} for an ID stream passed in parameter
*
* @param {string} id Stream ID
* @returns {Observable<StreamDeployConfig>}
*/
config(id: string): Observable<StreamDeployConfig> {
return this.streamService
.getStream(id)
.pipe(
mergeMap((val: Stream) => {
const observablesApplications = this.parserService
.parseDsl(val.dslText as string, 'stream')
.lines[0].nodes.map(node =>
of({
origin: get(node, 'name'),
name: get(node, 'label') || get(node, 'name'),
type: node.type.toString(),
version: null,
options: null
}).pipe(
mergeMap((val1: any) =>
this.appService.getAppVersions(val1.origin, node.type as any).pipe(
map((val2: App[]) => {
val1.versions = val2;
const current = val2.find((a: App) => a.defaultVersion);
if (current) {
val1.version = current.version;
}
return val1;
})
)
)
)
);
return forkJoin([this.streamService.getPlatforms(), ...observablesApplications]).pipe(
map(val2 => ({
streamDefinition: val,
args: val2
}))
);
})
)
.pipe(
map(result => {
const config = new StreamDeployConfig();
config.id = id;
// Platform
const platforms = result.args[0] as Platform[];
(result.args as Array<any>).splice(0, 1);
config.platform = {
id: 'platform',
name: 'platform',
form: 'select',
type: 'java.lang.String',
defaultValue: '',
values: platforms.map((platform: Platform) => ({
key: platform.name,
name: platform.name,
type: platform.type,
options: platform.options
}))
};
// Applications
config.apps = (result.args as Array<any>).map((app: any) => ({
origin: app.origin,
name: app.name,
type: app.type,
version: app.version,
versions: app.versions,
options: null,
optionsState: {
isLoading: false,
isOnError: false,
isInvalid: false
}
}));
// Deployers
config.deployers = [
{
id: 'memory',
name: 'memory',
form: 'autocomplete',
type: 'java.lang.Integer',
value: null,
defaultValue: null,
suffix: 'MB'
},
{
id: 'cpu',
name: 'cpu',
form: 'autocomplete',
type: 'java.lang.Integer',
value: null,
defaultValue: null,
suffix: 'Core(s)'
},
{
id: 'disk',
name: 'disk',
form: 'autocomplete',
type: 'java.lang.Integer',
value: null,
defaultValue: null,
suffix: 'MB'
}
];
if (!(result.streamDefinition?.status !== 'UNDEPLOYED')) {
config.deployers.push({
id: 'count',
name: 'count',
form: 'autocomplete',
type: 'java.lang.Integer',
value: null,
defaultValue: null
});
}
return config;
})
);
}
/**
* Provide an observable of {@link StreamDeployConfig}
* Work around: copy code from Flo Project to inject options for select value
*
* @param {ApplicationType} type
* @param {string} name
* @param {string} version
* @returns {Observable<Array<any>>}
*/
appDetails(type: ApplicationType, name: string, version: string): Observable<Array<any>> {
return this.appService.getApp(name, type, version).pipe(
map((app: DetailedApp) =>
app.options.map((option: ConfigurationMetadataProperty) => {
const opt = {
id: option.id,
name: option.name,
description: option.description,
shortDescription: option.shortDescription,
deprecation: option.deprecation,
sourceType: option.sourceType,
isDeprecated: option.isDeprecated,
type: option.type,
defaultValue: option.defaultValue,
isSemantic: true
};
if (opt.sourceType === Utils.SCRIPTABLE_TRANSFORM_SOURCE_TYPE) {
switch (opt.name.toLowerCase()) {
case 'language':
set(opt, 'valueOptions', ['groovy', 'javascript', 'ruby', 'python']);
break;
case 'script':
set(opt, 'code', {langPropertyName: 'scriptable-transformer.language'});
break;
}
} else if (opt.sourceType === Utils.RX_JAVA_PROCESSOR_SOURCE_TYPE) {
if (opt.name.toLowerCase() === 'code') {
set(opt, 'code', {language: 'java'});
}
}
if (opt.type) {
switch (opt.type) {
case 'java.util.concurrent.TimeUnit':
set(opt, 'valueOptions', [
'NANOSECONDS',
'MICROSECONDS',
'MILLISECONDS',
'SECONDS',
'MINUTES',
'HOURS',
'DAYS'
]);
}
}
return opt;
})
)
);
}
deploymentProperties(name: string): Observable<any> {
return this.streamService.getDeploymentInfo(name, true).pipe(
map((deploymentInfo: Stream) => {
const properties = [];
const ignoreProperties = [];
// Deployer properties
if (deploymentInfo.deploymentProperties) {
Object.keys(deploymentInfo.deploymentProperties).map(app => {
Object.keys(deploymentInfo.deploymentProperties[app]).forEach((key: string) => {
const value = this.cleanValueProperties(deploymentInfo.deploymentProperties[app][key]);
if (key === StreamDeployService.version.keyEdit) {
properties.push(`version.${app}=${value}`);
} else if (key.startsWith(StreamDeployService.deployer.keyEdit)) {
const keyShort = key.substring(StreamDeployService.deployer.keyEdit.length, key.length);
if (keyShort !== 'group') {
properties.push(`deployer.${app}.${keyShort}=${value}`);
} else {
// this.loggerService.log(`${key} is bypassed (app: ${app}, value: ${value})`);
}
} else {
// this.loggerService.log(`${key} is bypassed (app: ${app}, value: ${value})`);
}
});
});
}
// Application properties
const dslTextParsed = this.parserService.parseDsl(deploymentInfo.dslText, 'stream');
dslTextParsed.lines[0].nodes.forEach(node => {
const app = get(node, 'label') || get(node, 'name');
const appType = get(node, 'name');
get(node, 'options', []).forEach((value, key) => {
value = this.cleanValueProperties(value);
let keyShort = key;
if (key.startsWith(`${appType}.`)) {
ignoreProperties.push(`app.${app}.${keyShort}=${value}`);
keyShort = key.substring(`${appType}.`.length, key.length);
}
properties.push(`app.${app}.${keyShort}=${value}`);
ignoreProperties.push(`app.${app}.${keyShort}=${value}`);
});
});
return {
properties,
ignoreProperties,
stream: deploymentInfo
};
})
);
}
/**
* Clean value properties
* @param {string} value
* @returns {string}
*/
cleanValueProperties(value: string): string {
if (value && value.length > 1 && value.startsWith('"') && value.endsWith('"')) {
return value.substring(1, value.length - 1);
}
if (value && value.length > 1 && value.startsWith("'") && value.endsWith("'")) {
return value.substring(1, value.length - 1);
}
return value;
}
} | the_stack |
import { ConfigurationChangeEvent, Disposable, workspace } from 'vscode';
import { IActionContext, parseError } from 'vscode-azureextensionui';
import { ProjectLanguage, projectTemplateKeySetting, TemplateFilter } from '../constants';
import { ext, TemplateSource } from '../extensionVariables';
import { FuncVersion } from '../FuncVersion';
import { localize } from '../localize';
import { delay } from '../utils/delay';
import { nonNullValue } from '../utils/nonNull';
import { requestUtils } from '../utils/requestUtils';
import { getWorkspaceSetting } from '../vsCodeConfig/settings';
import { DotnetTemplateProvider } from './dotnet/DotnetTemplateProvider';
import { getDotnetVerifiedTemplateIds } from './dotnet/getDotnetVerifiedTemplateIds';
import { IBindingTemplate } from './IBindingTemplate';
import { IFunctionTemplate, TemplateCategory } from './IFunctionTemplate';
import { ITemplates } from './ITemplates';
import { getJavaVerifiedTemplateIds } from './java/getJavaVerifiedTemplateIds';
import { JavaTemplateProvider } from './java/JavaTemplateProvider';
import { getScriptVerifiedTemplateIds } from './script/getScriptVerifiedTemplateIds';
import { IScriptFunctionTemplate } from './script/parseScriptTemplates';
import { ScriptBundleTemplateProvider } from './script/ScriptBundleTemplateProvider';
import { ScriptTemplateProvider } from './script/ScriptTemplateProvider';
import { TemplateProviderBase } from './TemplateProviderBase';
type CachedProviders = { providers: TemplateProviderBase[]; templatesTask?: Promise<ITemplates> }
export class CentralTemplateProvider implements Disposable {
public readonly templateSource: TemplateSource | undefined;
private readonly _providersMap = new Map<string, CachedProviders>();
private _disposables: Disposable[] = [];
public constructor(templateSource?: TemplateSource) {
this.templateSource = templateSource || getWorkspaceSetting('templateSource');
this._disposables.push(workspace.onDidChangeConfiguration(e => this.onConfigChanged(e)));
}
public dispose(): void {
const allProviders: TemplateProviderBase[] = [];
for (const p of this._providersMap.values()) {
allProviders.push(...p.providers);
}
Disposable.from(...allProviders, ...this._disposables).dispose();
this._providersMap.clear();
}
public static getProviders(projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion, projectTemplateKey: string | undefined): TemplateProviderBase[] {
const providers: TemplateProviderBase[] = [];
switch (language) {
case ProjectLanguage.CSharp:
case ProjectLanguage.FSharp:
providers.push(new DotnetTemplateProvider(version, projectPath, language, projectTemplateKey));
break;
case ProjectLanguage.Java:
providers.push(new JavaTemplateProvider(version, projectPath, language, projectTemplateKey));
break;
default:
providers.push(new ScriptTemplateProvider(version, projectPath, language, projectTemplateKey));
if (version !== FuncVersion.v1) {
providers.push(new ScriptBundleTemplateProvider(version, projectPath, language, projectTemplateKey));
}
break;
}
return providers;
}
public async getFunctionTemplates(context: IActionContext, projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion, templateFilter: TemplateFilter, projectTemplateKey: string | undefined): Promise<IFunctionTemplate[]> {
const templates: ITemplates = await this.getTemplates(context, projectPath, language, version, projectTemplateKey);
switch (templateFilter) {
case TemplateFilter.All:
return templates.functionTemplates;
case TemplateFilter.Core:
return templates.functionTemplates.filter((t: IFunctionTemplate) => t.categories.find((c: TemplateCategory) => c === TemplateCategory.Core) !== undefined);
case TemplateFilter.Verified:
default:
const verifiedTemplateIds = getScriptVerifiedTemplateIds(version).concat(getDotnetVerifiedTemplateIds(version)).concat(getJavaVerifiedTemplateIds());
return templates.functionTemplates.filter((t: IFunctionTemplate) => verifiedTemplateIds.find(vt => typeof vt === 'string' ? vt === t.id : vt.test(t.id)));
}
}
public async clearTemplateCache(context: IActionContext, projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion): Promise<void> {
const providers: TemplateProviderBase[] = CentralTemplateProvider.getProviders(projectPath, language, version, undefined);
for (const provider of providers) {
await provider.clearCachedTemplateMetadata();
await provider.clearCachedTemplates(context);
provider.projKeyMayHaveChanged();
}
const cachedProviders = this.tryGetCachedProviders(projectPath, language, version);
if (cachedProviders) {
delete cachedProviders.templatesTask;
}
}
public async getBindingTemplates(context: IActionContext, projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion): Promise<IBindingTemplate[]> {
const templates: ITemplates = await this.getTemplates(context, projectPath, language, version, undefined);
return templates.bindingTemplates;
}
public async tryGetSampleData(context: IActionContext, version: FuncVersion, triggerBindingType: string): Promise<string | undefined> {
try {
const templates: IScriptFunctionTemplate[] = <IScriptFunctionTemplate[]>await this.getFunctionTemplates(context, undefined, ProjectLanguage.JavaScript, version, TemplateFilter.All, undefined);
const template: IScriptFunctionTemplate | undefined = templates.find(t => t.functionJson.triggerBinding?.type?.toLowerCase() === triggerBindingType.toLowerCase());
return template?.templateFiles['sample.dat'];
} catch {
return undefined;
}
}
public async getProjectTemplateKey(context: IActionContext, projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion, projectTemplateKey: string | undefined): Promise<string> {
const cachedProviders = await this.getCachedProviders(context, projectPath, language, version, projectTemplateKey);
// .NET is the only language that supports project template keys and they only have one provider
// We probably need to do something better here once multi-provider languages support project template keys
const provider = nonNullValue(cachedProviders.providers[0], 'firstProvider');
return await provider.getProjKey(context);
}
private getCachedProvidersKey(language: ProjectLanguage, version: FuncVersion): string {
return language + version;
}
private tryGetCachedProviders(projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion): CachedProviders | undefined {
const key: string = this.getCachedProvidersKey(language, version);
if (this._providersMap.has(key)) {
return this._providersMap.get(key);
} else if (projectPath) {
return this._providersMap.get(key + projectPath);
} else {
return undefined;
}
}
private setCachedProviders(projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion, cachedProviders: CachedProviders): void {
let key: string = this.getCachedProvidersKey(language, version);
if (cachedProviders.providers.some(p => p.supportsProjKey())) {
key += projectPath;
}
this._providersMap.set(key, cachedProviders);
}
private async getCachedProviders(context: IActionContext, projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion, projectTemplateKey: string | undefined): Promise<CachedProviders> {
let cachedProviders = this.tryGetCachedProviders(projectPath, language, version);
if (!cachedProviders) {
cachedProviders = { providers: CentralTemplateProvider.getProviders(projectPath, language, version, projectTemplateKey) };
this.setCachedProviders(projectPath, language, version, cachedProviders);
} else {
await Promise.all(cachedProviders.providers.map(async p => {
if (await p.updateProjKeyIfChanged(context, projectTemplateKey)) {
delete cachedProviders?.templatesTask;
}
}));
}
return cachedProviders;
}
/**
* Ensures we only have one task going at a time for refreshing templates
*/
private async getTemplates(context: IActionContext, projectPath: string | undefined, language: ProjectLanguage, version: FuncVersion, projectTemplateKey: string | undefined): Promise<ITemplates> {
context.telemetry.properties.projectRuntime = version;
context.telemetry.properties.projectLanguage = language;
const cachedProviders = await this.getCachedProviders(context, projectPath, language, version, projectTemplateKey);
let templatesTask: Promise<ITemplates> | undefined = cachedProviders.templatesTask;
if (templatesTask) {
return await templatesTask;
} else {
templatesTask = this.refreshTemplates(context, cachedProviders.providers);
cachedProviders.templatesTask = templatesTask;
try {
return await templatesTask;
} catch (error) {
// If an error occurs, we want to start from scratch next time we try to get templates so remove this task from the map
delete cachedProviders.templatesTask;
throw error;
}
}
}
private async refreshTemplates(context: IActionContext, providers: TemplateProviderBase[]): Promise<ITemplates> {
return (await Promise.all(providers.map(async provider => {
return await this.refreshTemplatesForProvider(context, provider);
}))).reduce((t1: ITemplates, t2: ITemplates) => {
return {
functionTemplates: t1.functionTemplates.concat(t2.functionTemplates),
bindingTemplates: t1.bindingTemplates.concat(t2.bindingTemplates)
};
});
}
private async refreshTemplatesForProvider(context: IActionContext, provider: TemplateProviderBase): Promise<ITemplates> {
let result: ITemplates | undefined;
let latestErrorMessage: string | undefined;
try {
const latestTemplateVersion: string = await provider.getLatestTemplateVersion(context);
context.telemetry.properties.latestTemplateVersion = latestTemplateVersion;
const cachedTemplateVersion: string | undefined = await provider.getCachedTemplateVersion();
context.telemetry.properties.cachedTemplateVersion = cachedTemplateVersion;
// 1. Use the cached templates if they match latestTemplateVersion
if (cachedTemplateVersion === latestTemplateVersion) {
result = await this.tryGetCachedTemplates(context, provider);
}
// 2. Refresh templates if the cache doesn't match latestTemplateVersion
if (!result) {
const timeout = requestUtils.getRequestTimeoutMS();
result = await Promise.race([
this.getLatestTemplates(context, provider, latestTemplateVersion),
delay(timeout).then(() => {
throw new Error(localize('templatesTimeout', 'Retrieving templates timed out. Modify setting "{0}.{1}" if you want to extend the timeout.', ext.prefix, requestUtils.timeoutKey));
})
]);
}
} catch (error) {
const errorMessage: string = parseError(error).message;
// This error should be the most actionable to the user, so save it and throw later if cache/backup doesn't work
latestErrorMessage = localize('latestTemplatesError', 'Failed to get latest templates: {0}', errorMessage);
ext.outputChannel.appendLog(latestErrorMessage);
context.telemetry.properties.latestTemplatesError = errorMessage;
}
// 3. Use the cached templates, even if they don't match latestTemplateVersion
if (!result) {
result = await this.tryGetCachedTemplates(context, provider);
}
// 4. Use backup templates shipped with the extension
if (!result) {
result = await this.tryGetBackupTemplates(context, provider);
}
if (result) {
return {
functionTemplates: result.functionTemplates.filter(f => this.includeTemplate(provider, f)),
bindingTemplates: result.bindingTemplates.filter(b => this.includeTemplate(provider, b))
};
} else if (latestErrorMessage) {
throw new Error(latestErrorMessage);
} else {
// This should only happen for dev/test scenarios where we explicitly set templateSource
throw new Error(localize('templateSourceError', 'Internal error: Failed to get templates for source "{0}".', this.templateSource));
}
}
private includeTemplate(provider: TemplateProviderBase, template: IBindingTemplate | IFunctionTemplate): boolean {
return provider.includeTemplate(template) && (!('language' in template) || template.language.toLowerCase() === provider.language.toLowerCase());
}
private async getLatestTemplates(context: IActionContext, provider: TemplateProviderBase, latestTemplateVersion: string): Promise<ITemplates | undefined> {
if (!this.templateSource || this.templateSource === TemplateSource.Latest || this.templateSource === TemplateSource.Staging) {
context.telemetry.properties.templateSource = 'latest';
const result: ITemplates = await provider.getLatestTemplates(context, latestTemplateVersion);
await provider.cacheTemplateMetadata(latestTemplateVersion);
await provider.cacheTemplates(context);
return result;
}
return undefined;
}
private async tryGetCachedTemplates(context: IActionContext, provider: TemplateProviderBase): Promise<ITemplates | undefined> {
if (!this.templateSource) {
try {
context.telemetry.properties.templateSource = 'cache';
if (await provider.doesCachedProjKeyMatch(context)) {
return await provider.getCachedTemplates(context);
} else {
return undefined;
}
} catch (error) {
const errorMessage: string = parseError(error).message;
ext.outputChannel.appendLog(localize('cachedTemplatesError', 'Failed to get cached templates: {0}', errorMessage));
context.telemetry.properties.cachedTemplatesError = errorMessage;
}
}
return undefined;
}
private async tryGetBackupTemplates(context: IActionContext, provider: TemplateProviderBase): Promise<ITemplates | undefined> {
if (!this.templateSource || this.templateSource === TemplateSource.Backup) {
try {
context.telemetry.properties.templateSource = 'backup';
const backupTemplateVersion: string = await provider.getBackupTemplateVersion();
context.telemetry.properties.backupTemplateVersion = backupTemplateVersion;
const result: ITemplates = await provider.getBackupTemplates(context);
await provider.cacheTemplateMetadata(backupTemplateVersion);
await provider.cacheTemplates(context);
return result;
} catch (error) {
const errorMessage: string = parseError(error).message;
ext.outputChannel.appendLog(localize('backupTemplatesError', 'Failed to get backup templates: {0}', errorMessage));
context.telemetry.properties.backupTemplatesError = errorMessage;
}
}
return undefined;
}
private onConfigChanged(e: ConfigurationChangeEvent): void {
if (e.affectsConfiguration(`${ext.prefix}.${projectTemplateKeySetting}`)) {
for (const cached of this._providersMap.values()) {
for (const provider of cached.providers) {
provider.projKeyMayHaveChanged();
}
}
}
}
} | the_stack |
import { useRouter } from 'next/router';
import { Dialog, Transition } from '@headlessui/react';
import { Fragment, useState } from 'react';
import truncate from 'lodash.truncate';
import { useClerkSWR } from '@/lib/fetcher';
import { notionSites } from '@prisma/client';
import SidebarLayout from '@/layouts/SidebarLayout';
import axios from 'axios';
import useUserWithSession from '@/lib/useUrlWithSession';
import toast from 'react-hot-toast';
import { Switch } from '@headlessui/react';
import Link from 'next/link';
import Image from 'next/image';
const Page = () => {
const router = useRouter();
const { data } = useClerkSWR<notionSites>(
`/api/getSiteData/notion/?siteId=${router.query.notionId}`
);
const urlWithSession = useUserWithSession(
'/api/updateSiteData/notion/showcase'
);
const deleteUrlWithSession = useUserWithSession('/api/deleteSite/notion');
const [enabled, setEnabled] = useState(data?.inShowcase);
const [isLoading, setIsLoading] = useState(false);
const [isOpen, setIsOpen] = useState(false);
function closeModal() {
setIsOpen(false);
}
function openModal() {
setIsOpen(true);
}
return (
<div>
<div>
<SidebarLayout activeTab='settings'>
<h1 className='text-4xl font-extrabold'>Settings</h1>
<p className='mt-4 text-gray-800 font-base'>
{data?.siteName || 'Just a second...'}
</p>
<div className='mt-8'>
<h2 className='text-2xl font-bold'>Showcase Settings</h2>
<div className='flex items-center my-5'>
<span className='inline-block mr-2'>
I prefer not to display{' '}
<strong title={data?.siteName}>
{truncate(data?.siteName, {
length: 15,
})}
</strong>{' '}
in showcase
</span>
<Switch
checked={enabled}
onChange={setEnabled}
style={{ zoom: 0.5 }}
className={`${enabled ? 'bg-gray-900' : 'bg-gray-700'}
relative inline-flex flex-shrink-0 h-[38px] w-[74px] border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75`}>
<span className='sr-only'>Use setting</span>
<span
aria-hidden='true'
className={`${enabled ? 'translate-x-9' : 'translate-x-0'}
pointer-events-none inline-block h-[34px] w-[34px] rounded-full bg-white shadow-lg transform ring-0 transition ease-in-out duration-200`}
/>
</Switch>
<span className='inline-block ml-2'>
Display{' '}
<strong title={data?.siteName}>
{truncate(data?.siteName, {
length: 15,
})}
</strong>{' '}
in{' '}
<Link href='/showcase'>
<a className='text-blue-500 hover:underline'>Showcase</a>
</Link>
</span>
</div>
<button
onClick={() => {
setIsLoading(true);
axios
.post(urlWithSession, {
inShowcase: enabled,
siteId: data.id,
})
.then((res) => {
console.log(res);
toast.success(
enabled
? `Yay 🎉, ${data?.siteName} will be displayed in showcase soon.`
: `${data?.siteName} will be removed showcase soon.`,
{
duration: 5000,
}
);
setIsLoading(false);
});
}}
className={`h-10 px-3 mb-10 bg-gray-800 rounded shadow-md text-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-800 hover:bg-gray-700 ${
isLoading && 'opacity-50 cursor-wait'
}`}>
Update Showcase Settings
</button>
</div>
<hr className='w-[70vw] my-3 text-gray-200' />
<div className='mt-8'>
<h2 className='text-2xl font-bold'>Password protection</h2>
{data?.isPasswordProtected ? (
<div>
<div className='flex items-center my-5'>
<span className='inline-block'>
<strong>{data?.siteName}</strong> has already been password
protected
</span>
</div>
<button className='h-10 px-3 mb-10 bg-gray-800 rounded shadow-md text-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-800 hover:bg-gray-700'>
<a
href='https://staticshield.vercel.app/dashboard'
target='_blank'
rel='noopener noreferrer'>
View details
</a>
</button>
</div>
) : (
<div>
<div className='flex items-center my-5'>
<span className='inline-block'>
Password protect <strong>{data?.siteName}</strong>
</span>
</div>
<button
onClick={() => {
window.open(
`https://staticshield.vercel.app/new/?name=${data?.siteName}&desc=${data?.siteDesc}&url=${data?.subdomain}.pagely.site&id=${data?.id}`,
'_blank'
);
}}
className={`mb-10 h-10 inline-flex items-center px-3 bg-gray-800 rounded shadow-md text-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-800 hover:bg-gray-700`}>
Password protect{' '}
<strong className='mx-1'>{data?.siteName}</strong> with{' '}
<span className='inline-flex !items-center justify-center p-1 mx-1 bg-white rounded'>
<Image
src='/staticshield.png'
alt=''
width='20'
height='20'
// className='block mt-2'
/>
</span>
StaticShield
</button>
</div>
)}
</div>
<hr className='w-[70vw] my-3 text-gray-200' />
<div className='mt-8'>
<h2 className='text-2xl font-bold text-red-500'>Danger Zone</h2>
<div className='mt-5'>
<button
onClick={openModal}
className='h-10 px-3 mb-10 bg-red-600 rounded shadow-md text-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-800 hover:bg-red-400'>
{/* <button className='px-2 py-1 text-red-600 border border-red-500 rounded shadow bg-red-50 hover:bg-red-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-red-200'> */}
Delete <strong>{data?.siteName}</strong>
</button>
</div>
</div>
</SidebarLayout>
<Transition appear show={isOpen} as={Fragment}>
<Dialog
as='div'
className='fixed inset-0 z-10 overflow-y-auto'
onClose={closeModal}>
<div className='min-h-screen px-4 text-center'>
<Transition.Child
as={Fragment}
enter='ease-out duration-300'
enterFrom='opacity-0'
enterTo='opacity-100'
leave='ease-in duration-200'
leaveFrom='opacity-100'
leaveTo='opacity-0'>
<Dialog.Overlay className='fixed inset-0 backdrop-filter backdrop-blur-sm bg-white/40' />
</Transition.Child>
{/* This element is to trick the browser into centering the modal contents. */}
<span
className='inline-block h-screen align-middle'
aria-hidden='true'>
​
</span>
<Transition.Child
as={Fragment}
enter='ease-out duration-300'
enterFrom='opacity-0 scale-95'
enterTo='opacity-100 scale-100'
leave='ease-in duration-200'
leaveFrom='opacity-100 scale-100'
leaveTo='opacity-0 scale-95'>
<div className='inline-block w-full max-w-lg p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white border rounded-md shadow-xl border-gray-500/40'>
<Dialog.Title
as='h3'
className='text-lg font-medium leading-6 text-red-700'>
Are you sure that you want to delete{' '}
<strong>{data?.siteName}</strong>?
</Dialog.Title>
<div className='mt-2 mb-10'>
<p className='text-sm text-gray-500'>
Proceed with caution. This action cannot be reversed.
</p>
</div>
<div className='mt-4'>
<button
type='button'
className='inline-flex justify-center px-4 py-1 mr-2 text-sm font-medium text-blue-900 bg-blue-100 border border-blue-500 rounded-md hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-blue-500'
onClick={closeModal}>
Cancel
</button>
<button
type='button'
className='inline-flex justify-center px-4 py-1 text-sm font-medium text-red-900 bg-red-100 border border-red-500 rounded-md hover:bg-red-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-red-500'
onClick={() => {
axios
.post(deleteUrlWithSession, {
siteId: data?.id,
})
.then((res) => {
if (res.data.success) {
toast.success('Site deleted successfully', {
duration: 2000,
});
setTimeout(() => {
router.push('/dashboard');
}, 2000);
} else {
toast.error('Site deletion failed');
}
});
}}>
Delete
</button>
</div>
</div>
</Transition.Child>
</div>
</Dialog>
</Transition>
</div>
</div>
);
};
export default Page; | the_stack |
"use strict";
import * as nexpect from "nexpect";
import * as rimraf from "rimraf";
import * as mkdirp from "mkdirp";
import * as fs from "fs";
import * as path from "path";
describe("command line interface", () => {
var dtsmPath = path.resolve(__dirname, "../bin/dtsm");
var testWorkingDir = path.resolve(process.cwd(), "test-cli");
var fixtureRootDir = path.resolve(process.cwd(), "test/fixture");
before(done => {
// turn off send usage
// make fetch log
nexpect
.spawn("node", [dtsmPath, "--insight", "false", "fetch"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
done();
});
});
beforeEach(() => {
rimraf.sync(testWorkingDir);
mkdirp.sync(testWorkingDir);
});
describe("init sub-command", () => {
it("make new dtsm.json", done => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
assert(!fs.existsSync(targetFile));
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "init"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
assert(fs.existsSync(targetFile));
done();
});
});
it("make new dtsm.json with --remote option", done => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
assert(!fs.existsSync(targetFile));
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "--remote", "https://github.com/vvakame/gapidts.git", "init"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
assert(fs.existsSync(targetFile));
var data = JSON.parse(fs.readFileSync(targetFile, "utf8"));
assert(data.repos.length === 1);
assert(data.repos[0].url === "https://github.com/vvakame/gapidts.git");
done();
});
});
});
describe("search sub-command", () => {
it("can find all .d.ts files without config file", done => {
nexpect
.spawn("node", [dtsmPath, "search"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
// https://github.com/DefinitelyTyped/DefinitelyTyped has greater than 500 .d.ts files
assert(500 < stdout.length);
done();
});
});
it("can find all .d.ts files with config file", done => {
var configFile = path.resolve(fixtureRootDir, "dtsm-gapidts-repo.json");
nexpect
.spawn("node", [dtsmPath, "--config", configFile, "search"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
// https://github.com/vvakame/gapidts has less than 300 .d.ts files
assert(stdout.length < 300);
done();
});
});
it("can find all .d.ts files with --remote option", done => {
nexpect
.spawn("node", [dtsmPath, "--remote", "https://github.com/vvakame/gapidts.git", "search"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
// https://github.com/vvakame/gapidts has less than 300 .d.ts files
assert(stdout.length < 300);
done();
});
});
it("can find .d.ts files by phrase", done => {
nexpect
.spawn("node", [dtsmPath, "search", "atom"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
// found 2 files
assert(stdout.length < 10);
done();
});
});
it("can find .d.ts files with --raw option", done => {
nexpect
.spawn("node", [dtsmPath, "search", "--raw"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
assert(stdout.length !== 0);
stdout.forEach(line => {
assert(line.indexOf("\t") === -1);
});
done();
});
});
});
describe("fetch sub-command", () => {
it("can fetch remote info", done => {
nexpect
.spawn("node", [dtsmPath, "fetch"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
done();
});
});
it("can fetch remote info with --remote option", done => {
nexpect
.spawn("node", [dtsmPath, "--remote", "https://github.com/vvakame/gapidts.git", "fetch"])
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
done();
});
});
});
describe("install sub-command", () => {
it("can install .d.ts file", done => {
assert(!fs.existsSync(path.resolve(testWorkingDir, "typings/atom/atom.d.ts")));
nexpect
.spawn("node", [dtsmPath, "install", "atom"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
assert(stdout.some(line => line.indexOf("atom/atom.d.ts") !== -1));
assert(stdout.some(line => line.indexOf("space-pen/space-pen.d.ts") !== -1));
assert(fs.existsSync(path.resolve(testWorkingDir, "typings/atom/atom.d.ts")));
assert(fs.existsSync(path.resolve(testWorkingDir, "typings/space-pen/space-pen.d.ts")));
done();
});
});
it("can install .d.ts file with --dry-run option", done => {
assert(!fs.existsSync(path.resolve(testWorkingDir, "/typings/atom/atom.d.ts")));
nexpect
.spawn("node", [dtsmPath, "install", "atom", "--dry-run"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
assert(stdout.some(line => line.indexOf("atom/atom.d.ts") !== -1));
assert(stdout.some(line => line.indexOf("space-pen/space-pen.d.ts") !== -1));
assert(!fs.existsSync(path.resolve(testWorkingDir, "typings/atom/atom.d.ts")));
assert(!fs.existsSync(path.resolve(testWorkingDir, "typings/space-pen/space-pen.d.ts")));
done();
});
});
it("can install .d.ts file with --save option", done => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
assert(!fs.existsSync(targetFile));
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "init"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
assert(fs.existsSync(targetFile));
var data: any;
data = JSON.parse(fs.readFileSync(targetFile, "utf8"));
assert(Object.keys(data.dependencies).length === 0);
nexpect
.spawn("node", [dtsmPath, "install", "--save", "atom"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
data = JSON.parse(fs.readFileSync(targetFile, "utf8"));
assert(Object.keys(data.dependencies).length === 1);
done();
});
});
});
it("can install .d.ts file with --remote and --save option", done => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
assert(!fs.existsSync(targetFile));
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "init"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
assert(fs.existsSync(targetFile));
var data: any;
data = JSON.parse(fs.readFileSync(targetFile, "utf8"));
assert(Object.keys(data.dependencies).length === 0);
nexpect
.spawn("node", [dtsmPath, "--remote", "https://github.com/vvakame/gapidts.git", "install", "--save", "bigquery-v2-browser"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
data = JSON.parse(fs.readFileSync(targetFile, "utf8"));
assert(Object.keys(data.dependencies).length === 1);
var dep = data.dependencies["test/valid/bigquery-v2-browser.d.ts"];
assert(dep.repo === "https://github.com/vvakame/gapidts.git");
done();
});
});
});
});
describe("uninstall sub-command", () => {
it("can uninstall definition files", () => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
var bundleFile = path.resolve(testWorkingDir, "typings/bundle.d.ts");
assert(!fs.existsSync(targetFile));
return Promise.resolve(null)
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "init"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
resolve();
});
});
})
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "install", "es6-promise", "--save"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
assert(fs.existsSync(path.resolve(testWorkingDir, "typings/es6-promise/es6-promise.d.ts")));
assert(fs.existsSync(bundleFile));
assert(fs.readFileSync(bundleFile).indexOf('/// <reference path="es6-promise/es6-promise.d.ts" />') !== -1);
resolve();
});
});
})
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "uninstall", "es6-promise", "--save"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
assert(!fs.existsSync(path.resolve(testWorkingDir + "typings/es6-promise/es6-promise.d.ts")));
assert(fs.existsSync(bundleFile));
assert(fs.readFileSync(bundleFile).indexOf('/// <reference path="es6-promise/es6-promise.d.ts" />') === -1);
resolve();
});
});
});
});
});
describe("update sub-command", () => {
it("can update definition files", () => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
assert(!fs.existsSync(targetFile));
return Promise.resolve(null)
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "init"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
resolve();
});
});
})
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "install", "es6-promise"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
resolve();
});
});
})
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "update", "--save"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
resolve();
});
});
});
});
});
describe("link sub-command", () => {
it("can link npm or bower definition files", () => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
assert(!fs.existsSync(targetFile));
return Promise.resolve(null)
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "init"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
resolve();
});
});
})
.then(() => {
return new Promise((resolve, reject) => {
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "link", "--save"])
.run((err, stdout, exit) => {
assert(!err);
if (err) {
reject(err);
return;
}
assert(exit === 0);
assert(fs.existsSync(targetFile));
resolve();
});
});
});
});
});
describe("refs sub-command", () => {
it("can show repository refs", done => {
var targetFile = path.resolve(testWorkingDir, "dtsm.json");
nexpect
.spawn("node", [dtsmPath, "--config", targetFile, "refs"], {
cwd: testWorkingDir
})
.run((err, stdout, exit) => {
assert(!err);
assert(exit === 0);
done();
});
});
});
}); | the_stack |
import {
Assert, AITestClass, PollingAssert, EventValidator, TraceValidator, ExceptionValidator,
MetricValidator, PageViewPerformanceValidator, PageViewValidator, RemoteDepdencyValidator
} from "@microsoft/ai-test-framework";
import { SinonStub, SinonSpy } from 'sinon';
import {
Exception, SeverityLevel, Event, Trace, PageViewPerformance, IConfig, IExceptionInternal,
AnalyticsPluginIdentifier, Util, IAppInsights, Metric, PageView, RemoteDependencyData
} from "@microsoft/applicationinsights-common";
import { ITelemetryItem, AppInsightsCore, IPlugin, IConfiguration, IAppInsightsCore, setEnableEnvMocks, getLocation, dumpObj } from "@microsoft/applicationinsights-core-js";
import { Sender } from "@microsoft/applicationinsights-channel-js"
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import { ApplicationInsights } from "../../../src/JavaScriptSDK/ApplicationInsights";
declare class ExceptionHelper {
capture: (appInsights:IAppInsights) => void;
captureStrict: (appInsights:IAppInsights) => void;
throw: (value:any) => void;
throwCors: () => void;
throwStrict: (value:any) => void;
throwRuntimeException: (timeoutFunc: VoidFunction) => void;
throwStrictRuntimeException: (timeoutFunc: VoidFunction) => void;
};
export class ApplicationInsightsTests extends AITestClass {
private _onerror:any = null;
private trackSpy:SinonSpy;
private throwInternalSpy:SinonSpy;
private exceptionHelper: any = new ExceptionHelper();
public testInitialize() {
this._onerror = window.onerror;
setEnableEnvMocks(false);
super.testInitialize();
Util.setCookie(undefined, 'ai_session', "");
Util.setCookie(undefined, 'ai_user', "");
if (Util.canUseLocalStorage()) {
window.localStorage.clear();
}
}
public testCleanup() {
super.testCleanup();
Util.setCookie(undefined, 'ai_session', "");
Util.setCookie(undefined, 'ai_user', "");
if (Util.canUseLocalStorage()) {
window.localStorage.clear();
}
window.onerror = this._onerror;
}
public causeException(cb:Function) {
AITestClass.orgSetTimeout(() => {
cb();
}, 0);
}
public registerTests() {
this.testCase({
name: 'enableAutoRouteTracking: event listener is added to the popstate event',
test: () => {
// Setup
const appInsights = new ApplicationInsights();
const core = new AppInsightsCore();
const channel = new ChannelPlugin();
const eventListenerStub = this.sandbox.stub(window, 'addEventListener');
// Act
core.initialize({
instrumentationKey: '',
enableAutoRouteTracking: true
} as IConfig & IConfiguration, [appInsights, channel]);
// Assert
Assert.ok(eventListenerStub.calledTwice);
Assert.equal(eventListenerStub.args[0][0], "popstate");
Assert.equal(eventListenerStub.args[1][0], "locationchange");
}
});
this.testCase({
name: 'enableAutoRouteTracking: route changes trigger a new pageview',
useFakeTimers: true,
test: () => {
// Current URL will be the test page
setEnableEnvMocks(true);
this.setLocationHref("firstUri");
// Setup
const appInsights = new ApplicationInsights();
appInsights.autoRoutePVDelay = 500;
const core = new AppInsightsCore();
const channel = new ChannelPlugin();
const properties = new PropertiesPlugin();
properties.context = { telemetryTrace: { traceID: 'not set', name: 'name not set' } } as any;
const trackPageViewStub = this.sandbox.stub(appInsights, 'trackPageView');
// Act
core.initialize({
instrumentationKey: '',
enableAutoRouteTracking: true
} as IConfig & IConfiguration, [appInsights, channel, properties]);
this.setLocationHref("secondUri");
window.dispatchEvent(Util.createDomEvent('locationchange'));
this.clock.tick(500);
this.setLocationHref("thirdUri");
window.dispatchEvent(Util.createDomEvent('locationchange'));
this.clock.tick(500);
// Assert
Assert.equal(2, trackPageViewStub.callCount);
Assert.ok(properties.context.telemetryTrace.traceID);
Assert.ok(properties.context.telemetryTrace.name);
Assert.notEqual(properties.context.telemetryTrace.traceID, 'not set', 'current operation id is updated after route change');
Assert.notEqual(properties.context.telemetryTrace.name, 'name not set', 'current operation name is updated after route change');
// Assert.equal(appInsights['_prevUri'], 'secondUri', "the previous uri is stored on variable _prevUri");
// Assert.equal(appInsights['_currUri'], window.location.href, "the current uri is stored on variable _currUri");
Assert.equal("firstUri", trackPageViewStub.args[0][0].refUri, "previous uri is assigned to refUri as firstUri, and send as an argument of trackPageview method");
Assert.equal("secondUri", trackPageViewStub.args[1][0].refUri, "previous uri is assigned to refUri as secondUri and send as an argument of trackPageview method");
}
});
this.testCase({
name: 'enableAutoRouteTracking: route changes trigger a new pageview with correct refUri when route changes happening before the timer autoRoutePVDelay stops',
useFakeTimers: true,
test: () => {
// Setup
setEnableEnvMocks(true);
this.setLocationHref("firstUri");
const appInsights = new ApplicationInsights();
appInsights.autoRoutePVDelay = 500;
const core = new AppInsightsCore();
const channel = new ChannelPlugin();
const properties = new PropertiesPlugin();
properties.context = { telemetryTrace: { traceID: 'not set', name: 'name not set' } } as any;
appInsights['_prevUri'] = "firstUri";
const trackPageViewStub = this.sandbox.stub(appInsights, 'trackPageView');
// Act
core.initialize({
instrumentationKey: '',
enableAutoRouteTracking: true
} as IConfig & IConfiguration, [appInsights, channel, properties]);
window.dispatchEvent(Util.createDomEvent('locationchange'));
this.clock.tick(200);
// set up second dispatch
window.dispatchEvent(Util.createDomEvent('locationchange'));
this.clock.tick(500);
// Assert
Assert.equal(2, trackPageViewStub.callCount);
Assert.ok(properties.context.telemetryTrace.traceID);
Assert.ok(properties.context.telemetryTrace.name);
Assert.notEqual(properties.context.telemetryTrace.traceID, 'not set', 'current operation id is updated after route change');
Assert.notEqual(properties.context.telemetryTrace.name, 'name not set', 'current operation name is updated after route change');
// first trackPageView event
Assert.equal(trackPageViewStub.args[0][0].refUri, 'firstUri', "first trackPageview event: refUri grabs the value of existing _prevUri");
// Assert.equal(appInsights['_currUri'], getLocation(true).href, "first trackPageview event: the current uri is stored on variable _currUri");
// second trackPageView event
Assert.equal(trackPageViewStub.args[1][0].refUri, getLocation(true).href, "second trackPageview event: refUri grabs the value of updated _prevUri, which is the first pageView event's _currUri");
}
});
this.testCase({
name: 'enableAutoRouteTracking: (IE9) app does not crash if history.pushState does not exist',
test: () => {
// Setup
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
history.pushState = null;
history.replaceState = null;
const appInsights = new ApplicationInsights();
const core = new AppInsightsCore();
const channel = new ChannelPlugin();
const properties = new PropertiesPlugin();
properties.context = { telemetryTrace: { traceID: 'not set', parentID: undefined} } as any;
this.sandbox.stub(appInsights, 'trackPageView');
// Act
core.initialize({
instrumentationKey: '',
enableAutoRouteTracking: true
} as IConfig & IConfiguration, [appInsights, channel]);
window.dispatchEvent(Util.createDomEvent('locationchange'));
// Assert
Assert.ok(true, 'App does not crash when history object is incomplete');
// Cleanup
history.pushState = originalPushState;
history.replaceState = originalReplaceState;
}
});
this.testCase({
name: 'AppInsightsTests: PageVisitTimeManager is constructed when analytics plugin is initialized',
test: () => {
// Setup
const channel = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights: ApplicationInsights = new ApplicationInsights();
// Act
const config = {
instrumentationKey: 'ikey'
};
core.initialize(
config,
[appInsights, channel]
);
const pvtm = appInsights['_pageVisitTimeManager'];
// Assert
Assert.ok(pvtm)
Assert.ok(pvtm['_logger']);
Assert.ok(pvtm['pageVisitTimeTrackingHandler']);
}
});
this.testCase({
name: 'AppInsightsTests: PageVisitTimeManager is available when config.autoTrackPageVisitTime is true and trackPageView is called',
test: () => {
// Setup
const channel = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights: ApplicationInsights = new ApplicationInsights();
const config = {
instrumentationKey: 'ikey',
autoTrackPageVisitTime: true
};
core.initialize(
config,
[appInsights, channel]
);
const pvtm = appInsights['_pageVisitTimeManager'];
const pvtmSpy = this.sandbox.spy(pvtm, 'trackPreviousPageVisit');
Assert.ok(pvtm)
Assert.ok(pvtmSpy.notCalled);
// Act
appInsights.trackPageView();
// Assert
Assert.ok(pvtmSpy.calledOnce);
}
});
this.testCase({
name: 'AppInsightsTests: config can be set from root',
test: () => {
// Setup
const appInsights = new ApplicationInsights();
const core = new AppInsightsCore();
const channel = new ChannelPlugin();
const properties = new PropertiesPlugin();
// Act
const config = {
instrumentationKey: 'instrumentation_key',
samplingPercentage: 12,
accountId: 'aaa',
extensionConfig: {
[appInsights.identifier]: {
accountId: 'def'
}
}
};
// Initialize
core.initialize(config, [appInsights, channel, properties]);
// Assert
Assert.equal(12, appInsights.config.samplingPercentage);
Assert.notEqual('aaa', appInsights.config.accountId);
Assert.equal('def', appInsights.config.accountId);
Assert.equal('instrumentation_key', (appInsights['config'] as IConfiguration).instrumentationKey);
Assert.equal(30 * 60 * 1000, appInsights.config.sessionRenewalMs);
Assert.equal(24 * 60 * 60 * 1000, appInsights.config.sessionExpirationMs);
let extConfig = (core.config as IConfiguration).extensionConfig[AnalyticsPluginIdentifier] as IConfig;
Assert.equal('instrumentation_key', core.config.instrumentationKey);
Assert.equal(12, extConfig.samplingPercentage);
Assert.notEqual('aaa', extConfig.accountId);
Assert.equal('def', extConfig.accountId);
Assert.equal('instrumentation_key', (extConfig as any).instrumentationKey);
Assert.equal(30 * 60 * 1000, extConfig.sessionRenewalMs);
Assert.equal(24 * 60 * 60 * 1000, extConfig.sessionExpirationMs);
}
});
this.testCase({
name: "AppInsightsTests: public members are correct",
test: () => {
// setup
const appInsights = new ApplicationInsights();
// the assert test will only see config as part of an object member if it has been initialized. Not sure how it worked before
appInsights.config = {};
const leTest = (name) => {
// assert
Assert.ok(name in appInsights, name + " exists");
}
// act
const members = [
"config",
"trackException",
"_onerror",
"trackEvent",
"trackTrace",
"trackMetric",
"trackPageView",
"trackPageViewPerformance",
"startTrackPage",
"stopTrackPage"
];
while (members.length) {
leTest(members.pop());
}
}
});
this.addGenericTests();
this.addStartStopTrackPageTests();
this.addTrackExceptionTests();
this.addOnErrorTests();
this.addTrackMetricTests();
this.addTelemetryInitializerTests();
}
private addGenericTests(): void {
this.testCase({
name: 'AppInsightsGenericTests: envelope type, data type, and ikey are correct',
test: () => {
// setup
const iKey: string = "BDC8736D-D8E8-4B69-B19B-B0CE6B66A456";
const iKeyNoDash: string = "BDC8736DD8E84B69B19BB0CE6B66A456";
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: iKey},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({instrumentationKey: core.config.instrumentationKey}, core, []);
const trackStub = this.sandbox.stub(appInsights.core, "track");
let envelope: ITelemetryItem;
const test = (action, expectedEnvelopeType, expectedDataType, test?: () => void) => {
action();
envelope = this.getFirstResult(action, trackStub);
Assert.equal("", envelope.iKey, "envelope iKey");
Assert.equal(expectedEnvelopeType, envelope.name, "envelope name");
Assert.equal(expectedDataType, envelope.baseType, "data type name");
if (typeof test === 'function') {test();}
trackStub.reset();
};
// Test
test(() => appInsights.trackException({exception: new Error(), severityLevel: SeverityLevel.Critical}), Exception.envelopeType, Exception.dataType)
test(() => appInsights.trackException({error: new Error(), severityLevel: SeverityLevel.Critical}), Exception.envelopeType, Exception.dataType)
test(() => appInsights.trackTrace({message: "some string"}), Trace.envelopeType, Trace.dataType);
test(() => appInsights.trackPageViewPerformance({name: undefined, uri: undefined, measurements: {somefield: 123}}, {vpHeight: 123}), PageViewPerformance.envelopeType, PageViewPerformance.dataType, () => {
Assert.deepEqual(undefined, envelope.baseData.properties, 'Properties does not exist in Part B');
});
}
});
this.testCase({
name: 'AppInsightsGenericTests: public APIs call track',
useFakeTimers: true,
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const senderStub = this.sandbox.stub(appInsights.core, "track");
// Act
appInsights.trackException({exception: new Error(), severityLevel: SeverityLevel.Critical});
appInsights.trackException({error: new Error(), severityLevel: SeverityLevel.Critical});
this.clock.tick(1);
// Test
Assert.ok(senderStub.calledTwice, "Telemetry is sent when master switch is on");
}
});
}
private addTrackExceptionTests(): void {
this.testCase({
name: "TrackExceptionTests: trackException accepts single exception",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const trackStub = this.sandbox.stub(appInsights.core, "track");
// Test
appInsights.trackException({error: new Error(), severityLevel: SeverityLevel.Critical});
Assert.ok(trackStub.calledOnce, "single exception is tracked");
// Verify ver is a string, as required by CS4.0
const baseData = (trackStub.args[0][0] as ITelemetryItem).baseData as IExceptionInternal;
Assert.equal("string", typeof baseData.ver, "Exception.ver should be a string for CS4.0");
Assert.equal("4.0", baseData.ver);
}
});
this.testCase({
name: "TrackExceptionTests: trackException allows logging errors with different severity level",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const trackStub = this.sandbox.stub(appInsights.core, "track");
// Test
appInsights.trackException({error: new Error(), severityLevel: SeverityLevel.Critical});
Assert.ok(trackStub.calledOnce, "single exception is tracked");
Assert.equal(SeverityLevel.Critical, trackStub.firstCall.args[0].baseData.severityLevel);
trackStub.reset();
appInsights.trackException({error: new Error(), severityLevel: SeverityLevel.Error});
Assert.ok(trackStub.calledOnce, "single exception is tracked");
Assert.equal(SeverityLevel.Error, trackStub.firstCall.args[0].baseData.severityLevel);
}
});
}
private addOnErrorTests(): void {
this.testCase({
name: "OnErrorTests: _onerror creates a dump of unexpected error thrown by trackException for logging",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const unexpectedError = new Error();
const expectedString = dumpObj(unexpectedError);
const throwSpy = this.sandbox.spy(core.logger, "throwInternal");
this.sandbox.stub(appInsights, "trackException").throws(unexpectedError);
// Act
appInsights._onerror({message: "msg", url: "some://url", lineNumber: 123, columnNumber: 456, error: unexpectedError});
// Assert
Assert.equal(1, throwSpy.callCount);
// Check Message
Assert.ok(throwSpy.args[0][2].indexOf("_onError threw exception while logging error,") !== -1, "Message should indicate that _onError failed");
// Check Exception contains the exception details
Assert.ok(throwSpy.args[0][3].exception.indexOf(expectedString) !== -1, "Expected error to contain - " + expectedString);
}
});
this.testCase({
name: "OnErrorTests: _onerror stringifies error object",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ instrumentationKey: "ikey"}, core, []);
const unexpectedError = new Error("some message");
const throwSpy = this.sandbox.spy(core.logger, "throwInternal");
const stub = this.sandbox.stub(appInsights, "trackException").throws(unexpectedError);
// Act
appInsights._onerror({message: "any message", url: "any://url", lineNumber: 123, columnNumber: 456, error: unexpectedError});
// Test
const dumpExMsg = throwSpy.args[0][3].exception;
Assert.ok(dumpExMsg.indexOf("stack: ") != -1);
Assert.ok(dumpExMsg.indexOf(`message: '${unexpectedError.message}'`) !== -1);
Assert.ok(dumpExMsg.indexOf("name: 'Error'") !== -1);
}
});
this.testCase({
name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ instrumentationKey: "key" }, core, []);
const throwInternal = this.sandbox.spy(appInsights.core.logger, "throwInternal");
this.sandbox.stub(appInsights, "trackException").throws(new CustomTestError("Simulated Error"));
const expectedErrorName: string = "CustomTestError";
appInsights._onerror({message: "some message", url: "some://url", lineNumber: 1234, columnNumber: 5678, error: new Error()});
Assert.ok(throwInternal.calledOnce, "throwInternal called once");
const logMessage: string = throwInternal.getCall(0).args[2];
Assert.notEqual(-1, logMessage.indexOf(expectedErrorName), "expected: " + logMessage);
}
});
this.testCase({
name: "OnErrorTests: _onerror adds document URL in case of CORS error",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const trackSpy = this.sandbox.spy(appInsights.core, "track");
// Act
appInsights._onerror({message: "Script error.", url: "", lineNumber: 0, columnNumber: 0, error: null});
// Assert
Assert.equal(document.URL, trackSpy.args[0][0].baseData.url);
}
});
this.testCase({
name: "OnErrorTests: _onerror adds document URL in case of no CORS error",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const trackExceptionSpy = this.sandbox.spy(appInsights, "trackException");
// Act
// Last arg is not an error/null which will be treated as not CORS issue
appInsights._onerror({message: "Script error.", url: "", lineNumber: 0, columnNumber: 0, error: new Object() as any});
// Assert
// properties are passed as a 3rd parameter
Assert.equal(document.URL, trackExceptionSpy.args[0][1].url);
}
});
this.testCase({
name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics",
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ instrumentationKey: "key" }, core, []);
const throwInternal = this.sandbox.spy(appInsights.core.logger, "throwInternal");
// Internal code does call this anymore!
const expectedErrorName: string = "test error";
let theError = new Error();
theError.name = expectedErrorName;
this.sandbox.stub(appInsights, "trackException").throws(theError);
appInsights._onerror({message: "some message", url: "some://url", lineNumber: 1234, columnNumber: 5678, error: "the error message"});
Assert.ok(throwInternal.calledOnce, "throwInternal called once");
const logMessage: string = throwInternal.getCall(0).args[2];
Assert.notEqual(-1, logMessage.indexOf(expectedErrorName), "logMessage: " + logMessage);
}
});
this.testCaseAsync({
name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics",
stepDelay: 1,
useFakeTimers: true,
steps: [() => {
// setup
const sender: Sender = new Sender();
const core = new AppInsightsCore();
core.initialize(
{
instrumentationKey: "key",
extensionConfig: {
[sender.identifier]: {
enableSessionStorageBuffer: false,
maxBatchInterval: 1
}
}
},
[sender]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ instrumentationKey: "key" }, core, []);
appInsights.addTelemetryInitializer((item: ITelemetryItem) => {
Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format");
});
this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal");
sender._sender = (payload:string[], isAsync:boolean) => {
sender._onSuccess(payload, payload.length);
};
this.sandbox.spy()
this.trackSpy = this.sandbox.spy(sender, "_onSuccess");
this.exceptionHelper.capture(appInsights);
this.causeException(() => {
this.exceptionHelper.throwRuntimeException(AITestClass.orgSetTimeout);
});
Assert.ok(!this.trackSpy.calledOnce, "track not called yet");
Assert.ok(!this.throwInternalSpy.called, "No internal errors");
}].concat(this.waitForException(1))
.concat(() => {
let isLocal = window.location.protocol === "file:";
let exp = this.trackSpy.args[0];
const payloadStr: string[] = this.getPayloadMessages(this.trackSpy);
if (payloadStr.length > 0) {
const payload = JSON.parse(payloadStr[0]);
const data = payload.data;
Assert.ok(data, "Has Data");
if (data) {
Assert.ok(data.baseData, "Has BaseData");
let baseData = data.baseData;
if (baseData) {
const ex = baseData.exceptions[0];
if (isLocal) {
Assert.ok(ex.message.indexOf("Script error:") !== -1, "Make sure the error message is present [" + ex.message + "]");
Assert.equal("String", ex.typeName, "Got the correct typename [" + ex.typeName + "]");
} else {
Assert.ok(ex.message.indexOf("ug is not a function") !== -1, "Make sure the error message is present [" + ex.message + "]");
Assert.equal("TypeError", ex.typeName, "Got the correct typename [" + ex.typeName + "]");
Assert.ok(baseData.properties["columnNumber"], "has column number");
Assert.ok(baseData.properties["lineNumber"], "has Line number");
}
Assert.ok(ex.stack.length > 0, "Has stack");
Assert.ok(ex.parsedStack, "Stack was parsed");
Assert.ok(ex.hasFullStack, "Stack has been decoded");
Assert.ok(baseData.properties["url"], "has Url");
Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source");
}
}
}
})
});
this.testCaseAsync({
name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics with a text exception",
stepDelay: 1,
useFakeTimers: true,
steps: [() => {
// setup
const sender: Sender = new Sender();
const core = new AppInsightsCore();
core.initialize(
{
instrumentationKey: "key",
extensionConfig: {
[sender.identifier]: {
enableSessionStorageBuffer: false,
maxBatchInterval: 1
}
}
},
[sender]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ instrumentationKey: "key" }, core, []);
appInsights.addTelemetryInitializer((item: ITelemetryItem) => {
Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format");
});
this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal");
sender._sender = (payload:string[], isAsync:boolean) => {
sender._onSuccess(payload, payload.length);
};
this.sandbox.spy()
this.trackSpy = this.sandbox.spy(sender, "_onSuccess");
this.exceptionHelper.capture(appInsights);
this.causeException(() => {
this.exceptionHelper.throw("Test Text Error!");
});
Assert.ok(!this.trackSpy.calledOnce, "track not called yet");
Assert.ok(!this.throwInternalSpy.called, "No internal errors");
}].concat(this.waitForException(1))
.concat(() => {
let exp = this.trackSpy.args[0];
const payloadStr: string[] = this.getPayloadMessages(this.trackSpy);
if (payloadStr.length > 0) {
const payload = JSON.parse(payloadStr[0]);
const data = payload.data;
Assert.ok(data, "Has Data");
if (data) {
Assert.ok(data.baseData, "Has BaseData");
let baseData = data.baseData;
if (baseData) {
const ex = baseData.exceptions[0];
Assert.ok(ex.message.indexOf("Test Text Error!") !== -1, "Make sure the error message is present [" + ex.message + "]");
Assert.ok(baseData.properties["columnNumber"], "has column number");
Assert.ok(baseData.properties["lineNumber"], "has Line number");
Assert.equal("String", ex.typeName, "Got the correct typename");
Assert.ok(ex.stack.length > 0, "Has stack");
Assert.ok(ex.parsedStack, "Stack was parsed");
Assert.ok(ex.hasFullStack, "Stack has been decoded");
Assert.ok(baseData.properties["url"], "has Url");
Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source");
}
}
}
})
});
this.testCaseAsync({
name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics with a custom direct exception",
stepDelay: 1,
useFakeTimers: true,
steps: [() => {
// setup
const sender: Sender = new Sender();
const core = new AppInsightsCore();
core.initialize(
{
instrumentationKey: "key",
extensionConfig: {
[sender.identifier]: {
enableSessionStorageBuffer: false,
maxBatchInterval: 1
}
}
},
[sender]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ instrumentationKey: "key" }, core, []);
appInsights.addTelemetryInitializer((item: ITelemetryItem) => {
Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format");
});
this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal");
sender._sender = (payload:string[], isAsync:boolean) => {
sender._onSuccess(payload, payload.length);
};
this.sandbox.spy()
this.trackSpy = this.sandbox.spy(sender, "_onSuccess");
this.exceptionHelper.capture(appInsights);
this.causeException(() => {
this.exceptionHelper.throw(new CustomTestError("Test Text Error!"));
});
Assert.ok(!this.trackSpy.calledOnce, "track not called yet");
Assert.ok(!this.throwInternalSpy.called, "No internal errors");
}].concat(this.waitForException(1))
.concat(() => {
let isLocal = window.location.protocol === "file:";
let exp = this.trackSpy.args[0];
const payloadStr: string[] = this.getPayloadMessages(this.trackSpy);
if (payloadStr.length > 0) {
const payload = JSON.parse(payloadStr[0]);
const data = payload.data;
Assert.ok(data, "Has Data");
if (data) {
Assert.ok(data.baseData, "Has BaseData");
let baseData = data.baseData;
if (baseData) {
const ex = baseData.exceptions[0];
if (isLocal) {
Assert.ok(ex.message.indexOf("Script error:") !== -1, "Make sure the error message is present [" + ex.message + "]");
Assert.equal("String", ex.typeName, "Got the correct typename");
} else {
Assert.ok(ex.message.indexOf("Test Text Error!") !== -1, "Make sure the error message is present [" + ex.message + "]");
Assert.ok(ex.message.indexOf("CustomTestError") !== -1, "Make sure the error type is present [" + ex.message + "]");
Assert.equal("CustomTestError", ex.typeName, "Got the correct typename");
Assert.ok(baseData.properties["columnNumber"], "has column number");
Assert.ok(baseData.properties["lineNumber"], "has Line number");
}
Assert.ok(ex.stack.length > 0, "Has stack");
Assert.ok(ex.parsedStack, "Stack was parsed");
Assert.ok(ex.hasFullStack, "Stack has been decoded");
Assert.ok(baseData.properties["url"], "has Url");
Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source");
}
}
}
})
});
this.testCaseAsync({
name: "OnErrorTests: _onerror logs name of unexpected error thrown by trackException for diagnostics with a strict custom direct exception",
stepDelay: 1,
useFakeTimers: true,
steps: [() => {
// setup
const sender: Sender = new Sender();
const core = new AppInsightsCore();
core.initialize(
{
instrumentationKey: "key",
extensionConfig: {
[sender.identifier]: {
enableSessionStorageBuffer: false,
maxBatchInterval: 1
}
}
},
[sender]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ instrumentationKey: "key" }, core, []);
appInsights.addTelemetryInitializer((item: ITelemetryItem) => {
Assert.equal("4.0", item.ver, "Telemetry items inside telemetry initializers should be in CS4.0 format");
});
this.throwInternalSpy = this.sandbox.spy(appInsights.core.logger, "throwInternal");
sender._sender = (payload:string[], isAsync:boolean) => {
sender._onSuccess(payload, payload.length);
};
this.sandbox.spy()
this.trackSpy = this.sandbox.spy(sender, "_onSuccess");
this.exceptionHelper.capture(appInsights);
this.causeException(() => {
this.exceptionHelper.throwStrict(new CustomTestError("Test Text Error!"));
});
Assert.ok(!this.trackSpy.calledOnce, "track not called yet");
Assert.ok(!this.throwInternalSpy.called, "No internal errors");
}].concat(this.waitForException(1))
.concat(() => {
let isLocal = window.location.protocol === "file:";
let exp = this.trackSpy.args[0];
const payloadStr: string[] = this.getPayloadMessages(this.trackSpy);
if (payloadStr.length > 0) {
const payload = JSON.parse(payloadStr[0]);
const data = payload.data;
Assert.ok(data, "Has Data");
if (data) {
Assert.ok(data.baseData, "Has BaseData");
let baseData = data.baseData;
if (baseData) {
const ex = baseData.exceptions[0];
if (isLocal) {
Assert.ok(ex.message.indexOf("Script error:") !== -1, "Make sure the error message is present [" + ex.message + "]");
Assert.equal("String", ex.typeName, "Got the correct typename");
} else {
Assert.ok(ex.message.indexOf("Test Text Error!") !== -1, "Make sure the error message is present [" + ex.message + "]");
Assert.ok(ex.message.indexOf("CustomTestError") !== -1, "Make sure the error type is present [" + ex.message + "]");
Assert.equal("CustomTestError", ex.typeName, "Got the correct typename");
Assert.ok(baseData.properties["columnNumber"], "has column number");
Assert.ok(baseData.properties["lineNumber"], "has Line number");
}
Assert.ok(ex.stack.length > 0, "Has stack");
Assert.ok(ex.parsedStack, "Stack was parsed");
Assert.ok(ex.hasFullStack, "Stack has been decoded");
Assert.ok(baseData.properties["url"], "has Url");
Assert.ok(baseData.properties["errorSrc"].indexOf("window.onerror@") !== -1, "has source");
}
}
}
})
});
}
private throwStrictRuntimeException() {
"use strict";
function doThrow() {
var ug: any = "Hello";
// This should throw
ug();
}
doThrow();
}
private addStartStopTrackPageTests() {
const testValues = {
name: "name",
url: "url",
duration: 200,
properties: {
"property1": "5",
"property2": "10",
"refUri": "test.com"
},
measurements: {
"measurement": 300
}
};
this.testCase({
name: "Timing Tests: Start/StopPageView pass correct duration",
useFakeTimers: true,
test: () => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const spy = this.sandbox.spy(appInsights, "sendPageViewInternal");
this.clock.tick(1);
// act
appInsights.startTrackPage(testValues.name);
this.clock.tick(testValues.duration);
appInsights.stopTrackPage(testValues.name, testValues.url, testValues.properties, testValues.measurements);
// verify
Assert.ok(spy.calledOnce, "stop track page view sent data");
const actual = spy.args[0][0];
Assert.equal(testValues.name, actual.name);
Assert.equal(testValues.url, actual.uri);
const actualProperties = actual.properties;
const actualMeasurements = actual.measurements;
Assert.equal(testValues.duration, actualProperties.duration, "duration is calculated and sent correctly");
Assert.equal(testValues.properties.property1, actualProperties.property1);
Assert.equal(testValues.properties.property2, actualProperties.property2);
Assert.equal(testValues.properties.refUri, actualProperties.refUri);
Assert.equal(testValues.measurements.measurement, actualMeasurements.measurement);
}
});
this.testCase({
name: "Timing Tests: Start/StopPageView tracks single page view with no parameters",
useFakeTimers: true,
test: () => {
// setup
const core = new AppInsightsCore();
this.sandbox.stub(core, "getTransmissionControls");
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const trackStub = this.sandbox.stub(appInsights.core, "track");
this.clock.tick(10); // Needed to ensure the duration calculation works
// act
appInsights.startTrackPage();
this.clock.tick(testValues.duration);
appInsights.stopTrackPage();
Assert.ok(trackStub.calledOnce, "single page view tracking stopped");
// verify
const telemetry: ITelemetryItem = trackStub.args[0][0];
Assert.equal(window.document.title, telemetry.baseData.name);
Assert.equal(testValues.duration, telemetry.baseData.properties.duration);
}
});
this.testCase({
name: "Timing Tests: Multiple Start/StopPageView track single pages view ",
useFakeTimers: true,
test: () => {
// setup
const core = new AppInsightsCore();
this.sandbox.stub(core, "getTransmissionControls");
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const trackStub = this.sandbox.stub(appInsights.core, "track");
this.clock.tick(10); // Needed to ensure the duration calculation works
// act
appInsights.startTrackPage(testValues.name);
this.clock.tick(testValues.duration);
appInsights.startTrackPage();
this.clock.tick(testValues.duration);
appInsights.stopTrackPage();
Assert.ok(trackStub.calledOnce, "single page view tracking stopped no parameters");
this.clock.tick(testValues.duration);
appInsights.stopTrackPage(testValues.name, testValues.url, testValues.properties);
Assert.ok(trackStub.calledTwice, "single page view tracking stopped all parameters");
// verify
// Empty parameters
let telemetry: ITelemetryItem = trackStub.args[0][0];
Assert.equal(window.document.title, telemetry.baseData.name);
Assert.equal(window.document.location.href, telemetry.baseData.uri);
// // All parameters
telemetry = trackStub.args[1][0];
Assert.equal(testValues.name, telemetry.baseData.name);
Assert.equal(testValues.url, telemetry.baseData.uri);
Assert.deepEqual(testValues.properties, telemetry.baseData.properties);
}
});
this.testCase({
name: "Timing Tests: Multiple startTrackPage",
test:
() => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const logStub = this.sandbox.stub(core.logger, "throwInternal");
core.logger.consoleLoggingLevel = () => 999;
// act
appInsights.startTrackPage();
appInsights.startTrackPage();
// verify
Assert.ok(logStub.calledOnce, "calling start twice triggers warning to user");
}
});
this.testCase({
name: "Timing Tests: stopTrackPage called without a corresponding start",
test:
() => {
// setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const logStub = this.sandbox.stub(core.logger, "throwInternal");
core.logger.consoleLoggingLevel = () => 999;
// act
appInsights.stopTrackPage();
// verify
Assert.ok(logStub.calledOnce, "calling stop without a corresponding start triggers warning to user");
}
});
}
private addTrackMetricTests() {
this.testCase({
name: 'TrackMetricTests: trackMetric batches metrics sent in a hot loop',
useFakeTimers: true,
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
core.initialize(
{instrumentationKey: "key"},
[plugin]
);
const appInsights = new ApplicationInsights();
appInsights.initialize({ "instrumentationKey": "ikey" }, core, []);
const trackStub = this.sandbox.stub(appInsights.core, "track");
// Act
appInsights.trackMetric({name: "test metric", average: 0});
this.clock.tick(1);
// Verify
Assert.ok(trackStub.calledOnce, "core.track was called once after sending one metric");
trackStub.reset();
// Act
for (let i = 0; i < 100; i++) {
appInsights.trackMetric({name: "test metric", average: 0});
}
this.clock.tick(1);
// Test
Assert.equal(100, trackStub.callCount, "core.track was called 100 times for sending 100 metrics");
}
});
}
private addTelemetryInitializerTests(): void {
this.testCase({
name: "TelemetryContext: onBeforeSendTelemetry is called within track() and gets the envelope as an argument",
useFakeTimers: true,
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
const telemetryInitializer = {
initializer: (envelope) => { }
}
const spy = this.sandbox.spy(telemetryInitializer, "initializer");
// act
appInsights.addTelemetryInitializer(telemetryInitializer.initializer);
appInsights.trackEvent({name: 'test event'});
this.clock.tick(1);
// verify
Assert.ok(spy.calledOnce, 'telemetryInitializer was called');
Assert.deepEqual(trackStub.args[0][0], spy.args[0][0], 'expected envelope is used');
}
});
this.testCase({
name: "TelemetryContext: onBeforeSendTelemetry changes the envelope props and sender gets them",
useFakeTimers: true,
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
const nameOverride = "my unique name";
const telemetryInitializer = {
initializer: (envelope) => {
envelope.name = nameOverride;
return true;}
}
// act
appInsights.addTelemetryInitializer(telemetryInitializer.initializer);
appInsights.trackTrace({message: 'test message'});
this.clock.tick(1);
// verify
Assert.ok(trackStub.calledOnce, "channel sender was called");
const envelope: ITelemetryItem = trackStub.args[0][0];
Assert.equal(envelope.name, nameOverride, 'expected envelope is used');
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer can modify the contents of an envelope",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
const messageOverride = "my unique name";
const propOverride = "val1";
const telemetryInitializer = {
// This illustrates how to use telemetry initializer (onBeforeSendTelemetry)
// to access/ modify the contents of an envelope.
initializer: (envelope) => {
if (envelope.baseType ===
Trace.dataType) {
const telemetryItem = envelope.baseData;
telemetryItem.message = messageOverride;
telemetryItem.properties = telemetryItem.properties || {};
telemetryItem.properties["prop1"] = propOverride;
return true;
}
}
}
appInsights.addTelemetryInitializer(telemetryInitializer.initializer);
// act
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.calledOnce, "sender should be called");
const envelope: ITelemetryItem = trackStub.args[0][0];
Assert.equal(messageOverride, envelope.baseData.message);
Assert.equal(propOverride, envelope.baseData.properties["prop1"]);
}
});
this.testCase({
name: "TelemetryContext: all added telemetry initializers get invoked",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const initializer1 = { init: () => { } };
const initializer2 = { init: () => { } };
const spy1 = this.sandbox.spy(initializer1, "init");
const spy2 = this.sandbox.spy(initializer2, "init");
// act
appInsights.addTelemetryInitializer(initializer1.init);
appInsights.addTelemetryInitializer(initializer2.init);
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(spy1.calledOnce);
Assert.ok(spy2.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: all added telemetry initializers get invoked for trackException",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const initializer1 = { init: (item: ITelemetryItem) => {
if (item.data !== undefined) {
item.data.init1 = true;
}
} };
const initializer2 = { init: (item: ITelemetryItem) => {
if (item.data !== undefined) {
item.data.init2 = true;
}
} };
const spy1 = this.sandbox.spy(initializer1, "init");
const spy2 = this.sandbox.spy(initializer2, "init");
// act
appInsights.addTelemetryInitializer(initializer1.init);
appInsights.addTelemetryInitializer(initializer2.init);
// Act
appInsights._onerror({message: "msg", url: "some://url", lineNumber: 123, columnNumber: 456, error: new Error()});
// verify
Assert.ok(spy1.calledOnce);
Assert.ok(spy2.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: all added telemetry initializers get invoked for _onError calls",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const initializer1 = { init: () => { } };
const initializer2 = { init: () => { } };
const spy1 = this.sandbox.spy(initializer1, "init");
const spy2 = this.sandbox.spy(initializer2, "init");
// act
appInsights.addTelemetryInitializer(initializer1.init);
appInsights.addTelemetryInitializer(initializer2.init);
appInsights.trackException({exception: new Error(), severityLevel: SeverityLevel.Critical});
// verify
Assert.ok(spy1.calledOnce);
Assert.ok(spy2.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning false means don't send an item",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
// act
appInsights.addTelemetryInitializer(() => false);
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.notCalled);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning void means do send an item (back compact with older telemetry initializers)",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
// act
appInsights.addTelemetryInitializer(() => { return; });
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.calledOnce); // TODO: use sender
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning true means do send an item",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
// act
appInsights.addTelemetryInitializer(() => true);
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - if one of initializers returns false than item is not sent",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
// act
appInsights.addTelemetryInitializer(() => true);
appInsights.addTelemetryInitializer(() => false);
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.notCalled);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - if one of initializers returns false (any order) than item is not sent",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
// act
appInsights.addTelemetryInitializer(() => false);
appInsights.addTelemetryInitializer(() => true);
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.notCalled);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning not boolean/undefined/null means do send an item (back compat with older telemetry initializers)",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
// act
appInsights.addTelemetryInitializer((() => "asdf") as any);
appInsights.addTelemetryInitializer(() => null);
appInsights.addTelemetryInitializer(() => undefined);
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.calledOnce); // TODO: use sender
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - if one initializer fails then error logged and is still sent",
test: () => {
// Setup
const plugin = new ChannelPlugin();
const core = new AppInsightsCore();
const appInsights = new ApplicationInsights();
core.initialize(
{instrumentationKey: "key"},
[plugin, appInsights]
);
appInsights.initialize({ "instrumentationKey": "ikey" }, core, [plugin, appInsights]);
plugin.initialize({instrumentationKey: 'ikey'}, core, [plugin, appInsights]);
const trackStub = this.sandbox.spy(appInsights.core.getTransmissionControls()[0][0], 'processTelemetry');
const logStub = this.sandbox.spy(appInsights.core.logger, "throwInternal")
// act
appInsights.addTelemetryInitializer(() => { throw new Error("Test error IGNORE"); });
appInsights.addTelemetryInitializer(() => { });
appInsights.trackTrace({message: 'test message'});
// verify
Assert.ok(trackStub.calledOnce);
Assert.ok(logStub.calledOnce);
}
});
}
private getFirstResult(action: string, trackStub: SinonStub, skipSessionState?: boolean): ITelemetryItem {
const index: number = skipSessionState ? 1 : 0;
Assert.ok(trackStub.args && trackStub.args[index] && trackStub.args[index][0], "track was called for: " + action);
return trackStub.args[index][0] as ITelemetryItem;
}
private checkNoInternalErrors() {
if (this.throwInternalSpy) {
Assert.ok(this.throwInternalSpy.notCalled, "Check no internal errors");
if (this.throwInternalSpy.called) {
Assert.ok(false, JSON.stringify(this.throwInternalSpy.args[0]));
}
}
}
private waitForException: any = (expectedCount:number, action: string = "", includeInit:boolean = false) => [
() => {
const message = "polling: " + new Date().toISOString() + " " + action;
Assert.ok(true, message);
console.log(message);
this.checkNoInternalErrors();
this.clock.tick(500);
},
(PollingAssert.createPollingAssert(() => {
this.checkNoInternalErrors();
let argCount = 0;
if (this.trackSpy.called) {
this.trackSpy.args.forEach(call => {
argCount += call.length;
});
}
Assert.ok(true, "* [" + argCount + " of " + expectedCount + "] checking spy " + new Date().toISOString());
try {
if (argCount >= expectedCount) {
const payload = JSON.parse(this.trackSpy.args[0][0]);
const baseType = payload.data.baseType;
// call the appropriate Validate depending on the baseType
switch (baseType) {
case Event.dataType:
return EventValidator.EventValidator.Validate(payload, baseType);
case Trace.dataType:
return TraceValidator.TraceValidator.Validate(payload, baseType);
case Exception.dataType:
return ExceptionValidator.ExceptionValidator.Validate(payload, baseType);
case Metric.dataType:
return MetricValidator.MetricValidator.Validate(payload, baseType);
case PageView.dataType:
return PageViewValidator.PageViewValidator.Validate(payload, baseType);
case PageViewPerformance.dataType:
return PageViewPerformanceValidator.PageViewPerformanceValidator.Validate(payload, baseType);
case RemoteDependencyData.dataType:
return RemoteDepdencyValidator.RemoteDepdencyValidator.Validate(payload, baseType);
default:
return EventValidator.EventValidator.Validate(payload, baseType);
}
}
} finally {
this.clock.tick(500);
}
return false;
}, "sender succeeded", 10, 1000))
];
}
class ChannelPlugin implements IPlugin {
public isFlushInvoked = false;
public isTearDownInvoked = false;
public isResumeInvoked = false;
public isPauseInvoked = false;
public identifier = "Sender";
public priority: number = 1001;
constructor() {
this.processTelemetry = this._processTelemetry.bind(this);
}
public pause(): void {
this.isPauseInvoked = true;
}
public resume(): void {
this.isResumeInvoked = true;
}
public teardown(): void {
this.isTearDownInvoked = true;
}
flush(async?: boolean, callBack?: () => void): void {
this.isFlushInvoked = true;
if (callBack) {
callBack();
}
}
public processTelemetry(env: ITelemetryItem) {}
setNextPlugin(next: any) {
// no next setup
}
public initialize = (config: IConfiguration, core: IAppInsightsCore, plugin: IPlugin[]) => {
}
private _processTelemetry(env: ITelemetryItem) {
}
}
class CustomTestError extends Error {
constructor(message = "") {
super(message);
this.name = "CustomTestError";
this.message = message + " -- test error.";
}
} | the_stack |
import { Store } from 'ember-orbit';
import {
Planet,
Moon,
Star,
Ocean,
BinaryStar,
PlanetarySystem
} from 'dummy/tests/support/dummy-models';
import { createStore } from 'dummy/tests/support/store';
import { buildTransform } from '@orbit/data';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { InitializedRecord, RecordTransform } from '@orbit/records';
module('Integration - Store', function (hooks) {
setupTest(hooks);
let store: Store;
hooks.beforeEach(function () {
store = createStore(this.owner, {
planet: Planet,
moon: Moon,
star: Star,
ocean: Ocean,
binaryStar: BinaryStar,
planetarySystem: PlanetarySystem
});
});
test('exposes properties from source', function (assert) {
assert.strictEqual(store.keyMap, store.source.keyMap);
assert.strictEqual(store.schema, store.source.schema);
assert.strictEqual(store.queryBuilder, store.queryBuilder);
assert.strictEqual(store.transformBuilder, store.transformBuilder);
assert.strictEqual(store.transformLog, store.source.transformLog);
assert.strictEqual(store.requestQueue, store.source.requestQueue);
assert.strictEqual(store.syncQueue, store.source.syncQueue);
assert.strictEqual(store.validatorFor, store.source.validatorFor);
});
test('`defaultQueryOptions` and `defaultTransformOptions` can be modified', function (assert) {
const defaultQueryOptions = {
maxRequests: 3
};
const defaultTransformOptions = {
maxRequests: 1
};
store.defaultQueryOptions = defaultQueryOptions;
store.defaultTransformOptions = defaultTransformOptions;
assert.deepEqual(store.defaultQueryOptions, defaultQueryOptions);
assert.deepEqual(store.cache.defaultQueryOptions, defaultQueryOptions);
assert.deepEqual(store.defaultTransformOptions, defaultTransformOptions);
assert.deepEqual(
store.cache.defaultTransformOptions,
defaultTransformOptions
);
});
test('#addRecord', async function (assert) {
const planet = await store.addRecord<Planet>({
type: 'planet',
name: 'Earth'
});
assert.ok(planet instanceof Planet);
assert.ok(planet.id, 'assigned id');
assert.strictEqual(planet.name, 'Earth');
});
test('#addRecord - with blocking sync updates that return hints', async function (assert) {
store.source.on('beforeUpdate', async (transform, hints) => {
await store.sync(transform);
hints.data = transform.operations.record;
});
const planet = await store.addRecord<Planet>({
type: 'planet',
name: 'Earth'
});
assert.ok(planet instanceof Planet);
assert.ok(planet.id, 'assigned id');
assert.strictEqual(planet.name, 'Earth');
});
test('#findRecord', async function (assert) {
const earth = await store.addRecord({ type: 'planet', name: 'Earth' });
const planet = await store.findRecord('planet', earth.id);
assert.strictEqual(planet, earth);
});
test('#findRecord - missing record', async function (assert) {
const planet = await store.findRecord('planet', 'jupiter');
assert.strictEqual(planet, undefined);
});
test('#findRecord - missing record, `raiseNotFoundExceptions: true`', async function (assert) {
try {
await store.findRecord('planet', 'jupiter', {
raiseNotFoundExceptions: true
});
} catch (e) {
assert.strictEqual(
(e as Error).message,
'Record not found: planet:jupiter'
);
}
});
test('#findRecord - can find a previously added record by key', async function (assert) {
const earth = await store.addRecord({
type: 'planet',
name: 'Earth',
remoteId: 'p01'
});
const record = await store.findRecord({
type: 'planet',
key: 'remoteId',
value: 'p01'
});
assert.strictEqual(record, earth);
});
test('#removeRecord - when passed a record, it should serialize its identity in a `removeRecord` op', async function (assert) {
assert.expect(2);
const record = await store.addRecord({ type: 'planet', name: 'Earth' });
store.on('update', (data) => {
assert.deepEqual(
data.operations,
{
op: 'removeRecord',
record: { type: 'planet', id: record.id }
},
'only the identity has been serialized in the operation'
);
});
await store.removeRecord(record);
assert.strictEqual(await store.findRecord('planet', record.id), undefined);
});
test('#removeRecord - when passed an identity', async function (assert) {
assert.expect(2);
const record = await store.addRecord({ type: 'planet', name: 'Earth' });
store.on('update', (data) => {
assert.deepEqual(
data.operations,
{
op: 'removeRecord',
record: { type: 'planet', id: record.id }
},
'only the identity has been serialized in the operation'
);
});
await store.removeRecord({ type: 'planet', id: record.id });
assert.strictEqual(await store.findRecord('planet', record.id), undefined);
});
test('#getTransform - returns a particular transform given an id', async function (assert) {
const recordA = {
id: 'jupiter',
type: 'planet',
attributes: { name: 'Jupiter' }
};
const addRecordATransform = buildTransform(
store.transformBuilder.addRecord(recordA)
);
await store.sync(addRecordATransform);
assert.strictEqual(
store.getTransform(addRecordATransform.id),
addRecordATransform
);
});
test('#getInverseOperations - returns the inverse operations for a particular transform', async function (assert) {
const recordA = {
id: 'jupiter',
type: 'planet',
attributes: { name: 'Jupiter' }
};
const addRecordATransform = buildTransform(
store.transformBuilder.addRecord(recordA)
);
await store.sync(addRecordATransform);
assert.deepEqual(store.getInverseOperations(addRecordATransform.id), [
{ op: 'removeRecord', record: { id: 'jupiter', type: 'planet' } }
]);
});
test('#getTransformsSince - returns all transforms since a specified transformId', async function (assert) {
const recordA = {
id: 'jupiter',
type: 'planet',
attributes: { name: 'Jupiter' }
};
const recordB = {
id: 'saturn',
type: 'planet',
attributes: { name: 'Saturn' }
};
const recordC = {
id: 'pluto',
type: 'planet',
attributes: { name: 'Pluto' }
};
const tb = store.transformBuilder;
const addRecordATransform = buildTransform(tb.addRecord(recordA));
const addRecordBTransform = buildTransform(tb.addRecord(recordB));
const addRecordCTransform = buildTransform(tb.addRecord(recordC));
await store.sync(addRecordATransform);
await store.sync(addRecordBTransform);
await store.sync(addRecordCTransform);
assert.deepEqual(
store.getTransformsSince(addRecordATransform.id),
[addRecordBTransform, addRecordCTransform],
'returns transforms since the specified transform'
);
});
test('#getAllTransforms - returns all tracked transforms', async function (assert) {
const recordA = {
id: 'jupiter',
type: 'planet',
attributes: { name: 'Jupiter' }
};
const recordB = {
id: 'saturn',
type: 'planet',
attributes: { name: 'Saturn' }
};
const recordC = {
id: 'pluto',
type: 'planet',
attributes: { name: 'Pluto' }
};
const tb = store.transformBuilder;
const addRecordATransform = buildTransform(tb.addRecord(recordA));
const addRecordBTransform = buildTransform(tb.addRecord(recordB));
const addRecordCTransform = buildTransform(tb.addRecord(recordC));
await store.sync(addRecordATransform);
await store.sync(addRecordBTransform);
await store.sync(addRecordCTransform);
assert.deepEqual(
store.getAllTransforms(),
[addRecordATransform, addRecordBTransform, addRecordCTransform],
'tracks transforms in correct order'
);
});
test('replacing a record invalidates attributes and relationships', async function (assert) {
const planet = await store.addRecord<Planet>({
type: 'planet',
id: 'p1',
name: 'Earth'
});
const star = await store.addRecord<Star>({
type: 'star',
id: 's1',
name: 'The Sun'
});
assert.strictEqual(planet.name, 'Earth', 'initial attribute get is fine');
assert.strictEqual(planet.sun, undefined, 'initial hasOne get is fine');
assert.strictEqual(star.name, 'The Sun', 'star has been created properly');
await store.update((t) =>
t.updateRecord({
type: 'planet',
id: planet.id,
attributes: { name: 'Jupiter' },
relationships: { sun: { data: { type: 'star', id: star.id } } }
})
);
assert.strictEqual(planet.name, 'Jupiter', 'attribute has been reset');
assert.strictEqual(planet.sun, star, 'hasOne has been reset');
});
test('#query - findRecord', async function (assert) {
const earth = await store.addRecord({ type: 'planet', name: 'Earth' });
const record = await store.query((q) => q.findRecord(earth));
assert.strictEqual(record, earth);
});
test('#query - findRecords', async function (assert) {
const earth = await store.addRecord<Planet>({
type: 'planet',
name: 'Earth'
});
const jupiter = await store.addRecord<Planet>({
type: 'planet',
name: 'Jupiter'
});
const records = await store.query<Planet[]>((q) => q.findRecords('planet'));
assert.strictEqual(records.length, 2);
assert.ok(records.includes(earth));
assert.ok(records.includes(jupiter));
});
test('#query - findRelatedRecord', async function (assert) {
const sun = await store.addRecord({ type: 'star', name: 'The Sun' });
const jupiter = await store.addRecord({
type: 'planet',
name: 'Jupiter',
sun
});
const record = await store.query((q) =>
q.findRelatedRecord(jupiter.$identity, 'sun')
);
assert.strictEqual(record, sun);
});
test('#query - findRelatedRecords', async function (assert) {
const io = await store.addRecord<Moon>({ type: 'moon', name: 'Io' });
const callisto = await store.addRecord<Moon>({
type: 'moon',
name: 'Callisto'
});
const jupiter = await store.addRecord<Planet>({
type: 'planet',
name: 'Jupiter',
moons: [io, callisto]
});
const records = await store.query<Moon[]>((q) =>
q.findRelatedRecords(jupiter.$identity, 'moons')
);
assert.deepEqual(records, [io, callisto]);
assert.strictEqual(records[0], io);
assert.strictEqual(records[1], callisto);
});
test('#query - filter', async function (assert) {
const earth = await store.addRecord<Planet>({
type: 'planet',
name: 'Earth'
});
await store.addRecord<Planet>({ type: 'planet', name: 'Jupiter' });
const records = await store.query<Planet[]>((q) =>
q.findRecords('planet').filter({ attribute: 'name', value: 'Earth' })
);
assert.deepEqual(records, [earth]);
assert.strictEqual(records[0], earth);
});
test('#query - records - multiple expressions', async function (assert) {
const [earth, jupiter, io, callisto] = await store.update<
[Planet, Planet, Moon, Moon]
>((t) => [
t.addRecord({
type: 'planet',
name: 'Earth'
}),
t.addRecord({
type: 'planet',
name: 'Jupiter'
}),
t.addRecord({ type: 'moon', name: 'Io' }),
t.addRecord({ type: 'moon', name: 'Callisto' })
]);
const [planets, moons] = await store.query<[Planet[], Moon[]]>((q) => [
q.findRecords('planet'),
q.findRecords('moon')
]);
assert.strictEqual(planets.length, 2, 'two records found');
assert.ok(planets.includes(earth), 'earth is included');
assert.ok(planets.includes(jupiter), 'jupiter is included');
assert.strictEqual(moons.length, 2, 'two records found');
assert.ok(moons.includes(io), 'io is included');
assert.ok(moons.includes(callisto), 'callisto is included');
});
test('#query - records - fullResponse', async function (assert) {
const earth = await store.addRecord<Planet>({
type: 'planet',
name: 'Earth'
});
const jupiter = await store.addRecord<Planet>({
type: 'planet',
name: 'Jupiter'
});
const { data: planets, transforms } = await store.query<Planet[]>(
(q) => q.findRecords('planet'),
{ fullResponse: true }
);
assert.strictEqual(planets!.length, 2, 'two records found');
assert.ok(planets!.includes(earth), 'earth is included');
assert.ok(planets!.includes(jupiter), 'jupiter is included');
assert.strictEqual(transforms, undefined, 'no transforms');
});
test('#update - single operation', async function (assert) {
const earth = await store.update<Planet>((o) =>
o.addRecord({ type: 'planet', attributes: { name: 'Earth' } })
);
assert.strictEqual(earth.name, 'Earth');
});
test('#update - single operation - fullResponse', async function (assert) {
const { data, transforms } = await store.update<Planet>(
(o) => o.addRecord({ type: 'planet', attributes: { name: 'Earth' } }),
{
fullResponse: true
}
);
assert.strictEqual(data!.name, 'Earth');
assert.strictEqual(transforms?.length, 1, 'one transform');
});
test('#update - multiple operations', async function (assert) {
const [earth, jupiter] = await store.update<[Planet, Planet]>((o) => [
o.addRecord({ type: 'planet', attributes: { name: 'Earth' } }),
o.addRecord({ type: 'planet', attributes: { name: 'Jupiter' } })
]);
assert.strictEqual(earth.name, 'Earth');
assert.strictEqual(jupiter.name, 'Jupiter');
});
test('#update - when transform is applied pessimistically via sync without hints', async function (assert) {
// Sync transform to store before store applies update
const beforeUpdate = (t: RecordTransform) => {
return store.sync(t);
};
store.on('beforeUpdate', beforeUpdate);
const response = await store.update((o) => [
o.addRecord({
id: 'earth',
type: 'planet',
attributes: { name: 'Earth' }
})
]);
// Response will be `undefined` because transform was applied `beforeUpdate` via `sync`
assert.strictEqual(response, undefined, 'undefined returned from update');
assert.ok(
store.cache.includesRecord('planet', 'earth'),
'store includes record'
);
store.off('beforeUpdate', beforeUpdate);
});
test('#update - when transform is applied pessimistically via sync without hints (fullResponse)', async function (assert) {
// Sync transform to store before store applies update
const beforeUpdate = (t: RecordTransform) => {
return store.sync(t);
};
store.on('beforeUpdate', beforeUpdate);
const response = await store.update(
(o) => [
o.addRecord({
id: 'earth',
type: 'planet',
attributes: { name: 'Earth' }
})
],
{ fullResponse: true }
);
// Response will be undefined because transform was applied `beforeUpdate` via `sync`
assert.strictEqual(
response.data,
undefined,
'undefined returned from update'
);
assert.ok(
store.cache.includesRecord('planet', 'earth'),
'store includes record'
);
store.off('beforeUpdate', beforeUpdate);
});
test('#fork - creates a clone of a base store', async function (assert) {
const forkedStore = store.fork();
const jupiter = await forkedStore.addRecord({
type: 'planet',
name: 'Jupiter',
classification: 'gas giant'
});
assert.strictEqual(forkedStore.base, store);
assert.notOk(
store.cache.includesRecord('planet', jupiter.id),
'store does not contain record'
);
assert.ok(
forkedStore.cache.includesRecord('planet', jupiter.id),
'fork includes record'
);
});
test('#merge - merges a forked store back into a base store', async function (assert) {
const storeTransforms: RecordTransform[] = [];
const forkedStore = store.fork();
const jupiter = await forkedStore.update<Planet>((t) =>
t.addRecord({
type: 'planet',
name: 'Jupiter',
classification: 'gas giant'
})
);
const storeTransformed = (t: RecordTransform) => {
storeTransforms.push(t);
};
store.on('transform', storeTransformed);
const [jupiterInStore] = await store.merge<[Planet]>(forkedStore);
assert.deepEqual(
jupiterInStore.$identity,
jupiter.$identity,
'result matches expectations'
);
assert.ok(
store.cache.includesRecord('planet', jupiter.id),
'store includes record'
);
assert.ok(
forkedStore.cache.includesRecord('planet', jupiter.id),
'fork includes record'
);
assert.strictEqual(storeTransforms.length, 1);
assert.deepEqual(storeTransforms[0]?.operations, [
{
op: 'addRecord',
record: jupiterInStore.$getData() as InitializedRecord
}
]);
store.off('transform', storeTransformed);
});
test('#merge - when transform is applied pessimistically via sync without hints', async function (assert) {
const forkedStore = store.fork();
const jupiter = await forkedStore.update<Planet>((t) =>
t.addRecord({
type: 'planet',
name: 'Jupiter',
classification: 'gas giant'
})
);
// Sync transform to store before store applies update
const beforeUpdate = (t: RecordTransform) => {
return store.sync(t);
};
store.on('beforeUpdate', beforeUpdate);
const response = await store.merge(forkedStore);
// Response will be `undefined` because transform was applied `beforeUpdate` via `sync`
assert.strictEqual(response, undefined, 'undefined returned from merge');
assert.ok(
store.cache.includesRecord('planet', jupiter.id),
'store includes record'
);
assert.ok(
forkedStore.cache.includesRecord('planet', jupiter.id),
'fork includes record'
);
store.off('beforeUpdate', beforeUpdate);
});
test('#merge - when transform is applied pessimistically via sync without hints (fullResponse)', async function (assert) {
const forkedStore = store.fork();
const jupiter = await forkedStore.update<Planet>((t) =>
t.addRecord({
type: 'planet',
name: 'Jupiter',
classification: 'gas giant'
})
);
// Sync transform to store before store applies update
const beforeUpdate = (t: RecordTransform) => {
return store.sync(t);
};
store.on('beforeUpdate', beforeUpdate);
const response = await store.merge(forkedStore, { fullResponse: true });
// Response will be `undefined` because transform was applied `beforeUpdate` via `sync`
assert.strictEqual(
response.data,
undefined,
'undefined data returned from merge'
);
assert.ok(
store.cache.includesRecord('planet', jupiter.id),
'store includes record'
);
assert.ok(
forkedStore.cache.includesRecord('planet', jupiter.id),
'fork includes record'
);
store.off('beforeUpdate', beforeUpdate);
});
test('#merge - can respond with a fullResponse', async function (assert) {
const forkedStore = store.fork();
const jupiter = await forkedStore.addRecord({
type: 'planet',
name: 'Jupiter',
classification: 'gas giant'
});
const fullResponse = await store.merge<[Planet]>(forkedStore, {
fullResponse: true
});
assert.deepEqual(
fullResponse.data![0].$identity,
jupiter.$identity,
'full response has correct data'
);
assert.ok(
store.cache.includesRecord('planet', jupiter.id),
'store includes record'
);
assert.ok(
forkedStore.cache.includesRecord('planet', jupiter.id),
'fork includes record'
);
});
test('#rebase - maintains only unique transforms in fork', async function (assert) {
const recordA = {
id: 'jupiter',
type: 'planet',
attributes: { name: 'Jupiter' }
};
const recordB = {
id: 'saturn',
type: 'planet',
attributes: { name: 'Saturn' }
};
const recordC = {
id: 'pluto',
type: 'planet',
attributes: { name: 'Pluto' }
};
const recordD = {
id: 'neptune',
type: 'planet',
attributes: { name: 'Neptune' }
};
const recordE = {
id: 'uranus',
type: 'planet',
attributes: { name: 'Uranus' }
};
const tb = store.transformBuilder;
const addRecordA = buildTransform(tb.addRecord(recordA));
const addRecordB = buildTransform(tb.addRecord(recordB));
const addRecordC = buildTransform(tb.addRecord(recordC));
const addRecordD = buildTransform(tb.addRecord(recordD));
const addRecordE = buildTransform(tb.addRecord(recordE));
let fork;
await store.update(addRecordA);
await store.update(addRecordB);
fork = store.fork();
await fork.update(addRecordD);
await store.update(addRecordC);
await fork.update(addRecordE);
fork.rebase();
assert.deepEqual(fork.getAllTransforms(), [addRecordD, addRecordE]);
assert.deepEqual(fork.cache.findRecords('planet').length, 5);
assert.ok(fork.cache.includesRecord(recordA.type, recordA.id));
assert.ok(fork.cache.includesRecord(recordB.type, recordB.id));
assert.ok(fork.cache.includesRecord(recordC.type, recordC.id));
assert.ok(fork.cache.includesRecord(recordD.type, recordD.id));
assert.ok(fork.cache.includesRecord(recordE.type, recordE.id));
});
test('#reset - clears the state of a store without a base', async function (assert) {
const recordA = {
id: 'jupiter',
type: 'planet',
attributes: { name: 'Jupiter' }
};
const recordB = {
id: 'saturn',
type: 'planet',
attributes: { name: 'Saturn' }
};
const tb = store.transformBuilder;
const addRecordA = buildTransform(tb.addRecord(recordA));
const addRecordB = buildTransform(tb.addRecord(recordB));
await store.update(addRecordA);
await store.update(addRecordB);
await store.reset();
assert.deepEqual(store.getAllTransforms(), []);
assert.deepEqual(store.cache.findRecords('planet').length, 0);
});
test('#reset - resets a fork to its base state', async function (assert) {
const recordA = {
id: 'jupiter',
type: 'planet',
attributes: { name: 'Jupiter' }
};
const recordB = {
id: 'saturn',
type: 'planet',
attributes: { name: 'Saturn' }
};
const recordC = {
id: 'pluto',
type: 'planet',
attributes: { name: 'Pluto' }
};
const recordD = {
id: 'neptune',
type: 'planet',
attributes: { name: 'Neptune' }
};
const recordE = {
id: 'uranus',
type: 'planet',
attributes: { name: 'Uranus' }
};
const tb = store.transformBuilder;
const addRecordA = buildTransform(tb.addRecord(recordA));
const addRecordB = buildTransform(tb.addRecord(recordB));
const addRecordC = buildTransform(tb.addRecord(recordC));
const addRecordD = buildTransform(tb.addRecord(recordD));
const addRecordE = buildTransform(tb.addRecord(recordE));
let fork;
await store.update(addRecordA);
await store.update(addRecordB);
fork = store.fork();
await fork.update(addRecordD);
await store.update(addRecordC);
await fork.update(addRecordE);
await fork.reset();
assert.deepEqual(fork.getAllTransforms(), []);
assert.deepEqual(fork.cache.findRecords('planet').length, 3);
assert.ok(fork.cache.includesRecord(recordA.type, recordA.id));
assert.ok(fork.cache.includesRecord(recordB.type, recordB.id));
assert.ok(fork.cache.includesRecord(recordC.type, recordC.id));
});
// deprecated
test('#findRecordByKey (deprecated) - can find a previously added record by key', async function (assert) {
const earth = await store.addRecord({
type: 'planet',
name: 'Earth',
remoteId: 'p01'
});
const record = await store.findRecordByKey('planet', 'remoteId', 'p01');
assert.strictEqual(record, earth);
});
// deprecated
test('#findRecordByKey (deprecated) - will generate a local id for a record that has not been added yet', async function (assert) {
const schema = store.source.schema;
const prevFn = schema.generateId;
schema.generateId = () => 'abc';
let result = await store.findRecordByKey('planet', 'remoteId', 'p01');
assert.strictEqual(result, undefined);
assert.strictEqual(
store.source.keyMap!.keyToId('planet', 'remoteId', 'p01'),
'abc'
);
schema.generateId = prevFn;
});
// deprecated
test('#peekRecord (deprecated) - existing record', async function (assert) {
const jupiter = await store.addRecord({ type: 'planet', name: 'Jupiter' });
assert.strictEqual(
store.peekRecord('planet', jupiter.id),
jupiter,
'retrieved record'
);
});
// deprecated
test('#peekRecord (deprecated) - missing record', async function (assert) {
assert.strictEqual(store.peekRecord('planet', 'fake'), undefined);
});
// deprecated
test('#peekRecordByKey (deprecated) - existing record', async function (assert) {
const jupiter = await store.addRecord({
type: 'planet',
name: 'Jupiter',
remoteId: 'p01'
});
assert.strictEqual(
store.peekRecordByKey('planet', 'remoteId', 'p01'),
jupiter,
'retrieved record'
);
});
// deprecated
test('#peekRecordByKey (deprecated) - missing record', async function (assert) {
assert.strictEqual(
store.keyMap!.keyToId('planet', 'remoteId', 'p01'),
undefined,
'key is not in map'
);
assert.strictEqual(
store.peekRecordByKey('planet', 'remoteId', 'p01'),
undefined
);
assert.notStrictEqual(
store.keyMap!.keyToId('planet', 'remoteId', 'p01'),
undefined,
'id has been generated for key'
);
});
// deprecated
test('#peekRecords (deprecated)', async function (assert) {
const earth = await store.addRecord({ type: 'planet', name: 'Earth' });
const jupiter = await store.addRecord({ type: 'planet', name: 'Jupiter' });
await store.addRecord({ type: 'moon', name: 'Io' });
const planets = store.peekRecords('planet');
assert.strictEqual(planets.length, 2);
assert.ok(planets.includes(earth));
assert.ok(planets.includes(jupiter));
});
// deprecated
test('#find (deprecated) - by type', async function (assert) {
let earth = await store.addRecord<Planet>({
type: 'planet',
name: 'Earth'
});
let jupiter = await store.addRecord<Planet>({
type: 'planet',
name: 'Jupiter'
});
let records = (await store.find('planet')) as Planet[];
assert.strictEqual(records.length, 2);
assert.ok(records.includes(earth));
assert.ok(records.includes(jupiter));
});
// deprecated
test('#find (deprecated) - by type and id', async function (assert) {
const earth = await store.addRecord({ type: 'planet', name: 'Earth' });
await store.addRecord({ type: 'planet', name: 'Jupiter' });
const record = await store.find('planet', earth.id);
assert.strictEqual(record, earth);
});
// deprecated
test('#find (deprecated) - missing record', async function (assert) {
const record = await store.find('planet', 'jupiter');
assert.strictEqual(
record,
undefined,
'undefined returned when record cannot be found'
);
});
// deprecated
test('#find (deprecated) - missing record (raises exception)', async function (assert) {
try {
await store.find('planet', 'jupiter', { raiseNotFoundExceptions: true });
} catch (e) {
assert.strictEqual(
(e as Error).message,
'Record not found: planet:jupiter',
'query - error caught'
);
}
});
}); | the_stack |
import { Directionality } from '@angular/cdk/bidi';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import {
ConnectedOverlayPositionChange,
ConnectionPositionPair,
FlexibleConnectedPositionStrategy,
Overlay,
OverlayRef,
ScrollDispatcher
} from '@angular/cdk/overlay';
import { OverlayConfig } from '@angular/cdk/overlay/overlay-config';
import { ComponentPortal } from '@angular/cdk/portal';
import {
Directive,
ElementRef,
EventEmitter,
NgZone,
TemplateRef,
Type,
ViewContainerRef
} from '@angular/core';
import { ESCAPE } from '@ptsecurity/cdk/keycodes';
import { Observable, Subject } from 'rxjs';
import { delay as rxDelay, distinctUntilChanged, takeUntil } from 'rxjs/operators';
import {
EXTENDED_OVERLAY_POSITIONS,
POSITION_MAP,
POSITION_PRIORITY_STRATEGY,
POSITION_TO_CSS_MAP
} from '../overlay/overlay-position-map';
import { PopUpPlacements, PopUpTriggers } from './constants';
const VIEWPORT_MARGIN: number = 8;
@Directive()
// tslint:disable-next-line:naming-convention
export abstract class McPopUpTrigger<T> {
isOpen: boolean = false;
enterDelay: number = 0;
leaveDelay: number = 0;
abstract disabled: boolean;
abstract trigger: string;
abstract customClass: string;
abstract content: string | TemplateRef<any>;
abstract placementChange: EventEmitter<string>;
abstract visibleChange: EventEmitter<boolean>;
protected abstract originSelector: string;
protected abstract overlayConfig: OverlayConfig;
protected placement = PopUpPlacements.Top;
protected placementPriority: string | string[] | null = null;
protected visible = false;
// tslint:disable-next-line:naming-convention orthodox-getter-and-setter
protected _content: string | TemplateRef<any>;
// tslint:disable-next-line:naming-convention orthodox-getter-and-setter
protected _disabled: boolean = false;
// tslint:disable-next-line:naming-convention orthodox-getter-and-setter
protected _customClass: string;
protected overlayRef: OverlayRef | null;
protected portal: ComponentPortal<T>;
protected instance: any | null;
protected listeners = new Map<string, EventListenerOrEventListenerObject>();
protected readonly availablePositions: { [key: string]: ConnectionPositionPair };
protected readonly destroyed = new Subject<void>();
protected constructor(
protected overlay: Overlay,
protected elementRef: ElementRef,
protected ngZone: NgZone,
protected scrollDispatcher: ScrollDispatcher,
protected hostView: ViewContainerRef,
protected scrollStrategy,
protected direction?: Directionality
) {
this.availablePositions = POSITION_MAP;
}
abstract updateClassMap(newPlacement?: string): void;
abstract updateData(): void;
abstract closingActions(): Observable<any>;
abstract getOverlayHandleComponentType(): Type<T>;
ngOnInit(): void {
this.initListeners();
}
ngOnDestroy(): void {
if (this.overlayRef) {
this.overlayRef.dispose();
}
this.listeners.forEach(this.removeEventListener);
this.listeners.clear();
this.destroyed.next();
this.destroyed.complete();
}
updatePlacement(value: PopUpPlacements) {
if (POSITION_TO_CSS_MAP[value]) {
this.placement = value;
this.updateClassMap();
} else {
this.placement = PopUpPlacements.Top;
console.warn(`Unknown position: ${value}. Will used default position: ${this.placement}`);
}
if (this.visible) {
this.updatePosition();
}
}
updatePlacementPriority(value) {
if (value && value.length > 0) {
this.placementPriority = value;
} else {
this.placementPriority = null;
}
}
updateVisible(externalValue: boolean) {
const value = coerceBooleanProperty(externalValue);
if (this.visible !== value) {
this.visible = value;
if (value) {
this.show();
} else {
this.hide();
}
}
}
handleKeydown(event: KeyboardEvent) {
if (this.isOpen && event.keyCode === ESCAPE) { // tslint:disable-line
this.hide();
}
}
handleTouchend() {
this.hide();
}
show(delay: number = this.enterDelay): void {
if (this.disabled || this.instance) { return; }
this.overlayRef = this.createOverlay();
this.detach();
this.portal = this.portal || new ComponentPortal(this.getOverlayHandleComponentType(), this.hostView);
this.instance = this.overlayRef.attach(this.portal).instance;
this.instance.afterHidden()
.pipe(takeUntil(this.destroyed))
.subscribe(this.detach);
this.updateClassMap();
this.updateData();
this.instance.visibleChange
.pipe(takeUntil(this.destroyed), distinctUntilChanged())
.subscribe((value) => {
this.visible = value;
this.visibleChange.emit(value);
this.isOpen = value;
});
this.updatePosition();
this.instance.show(delay);
}
hide(delay: number = this.leaveDelay): void {
if (this.instance) {
this.instance.hide(delay);
}
}
detach = (): void => {
if (this.overlayRef && this.overlayRef.hasAttached()) {
this.overlayRef.detach();
}
this.instance = null;
}
/** Create the overlay config and position strategy */
createOverlay(): OverlayRef {
if (this.overlayRef) { return this.overlayRef; }
// Create connected position strategy that listens for scroll events to reposition.
const strategy = this.overlay.position()
.flexibleConnectedTo(this.elementRef)
.withTransformOriginOn(this.originSelector)
.withFlexibleDimensions(false)
.withViewportMargin(VIEWPORT_MARGIN)
.withPositions([...EXTENDED_OVERLAY_POSITIONS])
.withScrollableContainers(this.scrollDispatcher.getAncestorScrollContainers(this.elementRef));
strategy.positionChanges
.pipe(takeUntil(this.destroyed))
.subscribe(this.onPositionChange);
this.overlayRef = this.overlay.create({
...this.overlayConfig,
direction: this.direction,
positionStrategy: strategy,
scrollStrategy: this.scrollStrategy()
});
this.closingActions()
.pipe(takeUntil(this.destroyed))
.pipe(rxDelay(0))
.subscribe(() => this.hide());
this.overlayRef.outsidePointerEvents()
.subscribe(() => this.instance!.handleBodyInteraction());
this.overlayRef.detachments()
.pipe(takeUntil(this.destroyed))
.subscribe(this.detach);
return this.overlayRef;
}
onPositionChange = ($event: ConnectedOverlayPositionChange): void => {
if (!this.instance) { return; }
let newPlacement = this.placement;
const { originX, originY, overlayX, overlayY } = $event.connectionPair;
Object.keys(this.availablePositions).some((key) => {
if (
originX === this.availablePositions[key].originX && originY === this.availablePositions[key].originY &&
overlayX === this.availablePositions[key].overlayX && overlayY === this.availablePositions[key].overlayY
) {
newPlacement = key as PopUpPlacements;
return true;
}
return false;
});
this.placementChange.emit(newPlacement);
this.updateClassMap(newPlacement);
if ($event.scrollableViewProperties.isOverlayClipped && this.instance.isVisible()) {
// After position changes occur and the overlay is clipped by
// a parent scrollable then close the tooltip.
this.ngZone.run(() => this.hide());
}
}
initListeners() {
this.clearListeners();
if (this.trigger.includes(PopUpTriggers.Click)) {
this.listeners
.set('click', () => this.show())
.forEach(this.addEventListener);
}
if (this.trigger.includes(PopUpTriggers.Hover)) {
this.listeners
.set('mouseenter', () => this.show())
.set('mouseleave', () => this.hide())
.forEach(this.addEventListener);
}
if (this.trigger.includes(PopUpTriggers.Focus)) {
this.listeners
.set('focus', () => this.show())
.set('blur', () => this.hide())
.forEach(this.addEventListener);
}
}
/** Updates the position of the current popover. */
updatePosition(reapplyPosition: boolean = false) {
this.overlayRef = this.createOverlay();
const position = (this.overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy)
.withPositions(this.getPrioritizedPositions())
.withPush(true);
if (reapplyPosition) {
setTimeout(() => position.reapplyLastPosition());
}
}
protected getPriorityPlacementStrategy(value: string | string[]): ConnectionPositionPair[] {
const result: ConnectionPositionPair[] = [];
const possiblePositions = Object.keys(this.availablePositions);
if (Array.isArray(value)) {
value.forEach((position: string) => {
if (possiblePositions.includes(position)) {
result.push(this.availablePositions[position]);
}
});
} else if (possiblePositions.includes(value)) {
result.push(this.availablePositions[value]);
}
return result;
}
protected getPrioritizedPositions() {
if (this.placementPriority) {
return this.getPriorityPlacementStrategy(this.placementPriority);
}
return POSITION_PRIORITY_STRATEGY[this.placement];
}
protected clearListeners() {
this.listeners.forEach(this.removeEventListener);
this.listeners.clear();
}
private addEventListener = (listener: EventListener | EventListenerObject, event: string) => {
this.elementRef.nativeElement.addEventListener(event, listener);
}
private removeEventListener = (listener: EventListener | EventListenerObject, event: string) => {
this.elementRef.nativeElement.removeEventListener(event, listener);
}
} | the_stack |
import * as fs from "fs";
import * as path from "path";
import * as toolrunner from "@actions/exec/lib/toolrunner";
import * as yaml from "js-yaml";
import * as analysisPaths from "./analysis-paths";
import { CODEQL_VERSION_COUNTS_LINES, getCodeQL } from "./codeql";
import * as configUtils from "./config-utils";
import { countLoc } from "./count-loc";
import { isScannedLanguage, Language } from "./languages";
import { Logger } from "./logging";
import * as sharedEnv from "./shared-environment";
import * as util from "./util";
export class CodeQLAnalysisError extends Error {
queriesStatusReport: QueriesStatusReport;
constructor(queriesStatusReport: QueriesStatusReport, message: string) {
super(message);
this.name = "CodeQLAnalysisError";
this.queriesStatusReport = queriesStatusReport;
}
}
export interface QueriesStatusReport {
// Time taken in ms to run builtin queries for cpp (or undefined if this language was not analyzed)
analyze_builtin_queries_cpp_duration_ms?: number;
// Time taken in ms to run builtin queries for csharp (or undefined if this language was not analyzed)
analyze_builtin_queries_csharp_duration_ms?: number;
// Time taken in ms to run builtin queries for go (or undefined if this language was not analyzed)
analyze_builtin_queries_go_duration_ms?: number;
// Time taken in ms to run builtin queries for java (or undefined if this language was not analyzed)
analyze_builtin_queries_java_duration_ms?: number;
// Time taken in ms to run builtin queries for javascript (or undefined if this language was not analyzed)
analyze_builtin_queries_javascript_duration_ms?: number;
// Time taken in ms to run builtin queries for python (or undefined if this language was not analyzed)
analyze_builtin_queries_python_duration_ms?: number;
// Time taken in ms to run builtin queries for ruby (or undefined if this language was not analyzed)
analyze_builtin_queries_ruby_duration_ms?: number;
// Time taken in ms to run custom queries for cpp (or undefined if this language was not analyzed)
analyze_custom_queries_cpp_duration_ms?: number;
// Time taken in ms to run custom queries for csharp (or undefined if this language was not analyzed)
analyze_custom_queries_csharp_duration_ms?: number;
// Time taken in ms to run custom queries for go (or undefined if this language was not analyzed)
analyze_custom_queries_go_duration_ms?: number;
// Time taken in ms to run custom queries for java (or undefined if this language was not analyzed)
analyze_custom_queries_java_duration_ms?: number;
// Time taken in ms to run custom queries for javascript (or undefined if this language was not analyzed)
analyze_custom_queries_javascript_duration_ms?: number;
// Time taken in ms to run custom queries for python (or undefined if this language was not analyzed)
analyze_custom_queries_python_duration_ms?: number;
// Time taken in ms to run custom queries for ruby (or undefined if this language was not analyzed)
analyze_custom_queries_ruby_duration_ms?: number;
// Time taken in ms to interpret results for cpp (or undefined if this language was not analyzed)
interpret_results_cpp_duration_ms?: number;
// Time taken in ms to interpret results for csharp (or undefined if this language was not analyzed)
interpret_results_csharp_duration_ms?: number;
// Time taken in ms to interpret results for go (or undefined if this language was not analyzed)
interpret_results_go_duration_ms?: number;
// Time taken in ms to interpret results for java (or undefined if this language was not analyzed)
interpret_results_java_duration_ms?: number;
// Time taken in ms to interpret results for javascript (or undefined if this language was not analyzed)
interpret_results_javascript_duration_ms?: number;
// Time taken in ms to interpret results for python (or undefined if this language was not analyzed)
interpret_results_python_duration_ms?: number;
// Time taken in ms to interpret results for ruby (or undefined if this language was not analyzed)
interpret_results_ruby_duration_ms?: number;
// Name of language that errored during analysis (or undefined if no language failed)
analyze_failure_language?: string;
}
async function setupPythonExtractor(logger: Logger) {
const codeqlPython = process.env["CODEQL_PYTHON"];
if (codeqlPython === undefined || codeqlPython.length === 0) {
// If CODEQL_PYTHON is not set, no dependencies were installed, so we don't need to do anything
return;
}
let output = "";
const options = {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
},
},
};
await new toolrunner.ToolRunner(
codeqlPython,
[
"-c",
"import os; import pip; print(os.path.dirname(os.path.dirname(pip.__file__)))",
],
options
).exec();
logger.info(`Setting LGTM_INDEX_IMPORT_PATH=${output}`);
process.env["LGTM_INDEX_IMPORT_PATH"] = output;
output = "";
await new toolrunner.ToolRunner(
codeqlPython,
["-c", "import sys; print(sys.version_info[0])"],
options
).exec();
logger.info(`Setting LGTM_PYTHON_SETUP_VERSION=${output}`);
process.env["LGTM_PYTHON_SETUP_VERSION"] = output;
}
async function createdDBForScannedLanguages(
config: configUtils.Config,
logger: Logger
) {
// Insert the LGTM_INDEX_X env vars at this point so they are set when
// we extract any scanned languages.
analysisPaths.includeAndExcludeAnalysisPaths(config);
const codeql = await getCodeQL(config.codeQLCmd);
for (const language of config.languages) {
if (
isScannedLanguage(language) &&
!dbIsFinalized(config, language, logger)
) {
logger.startGroup(`Extracting ${language}`);
if (language === Language.python) {
await setupPythonExtractor(logger);
}
await codeql.extractScannedLanguage(
util.getCodeQLDatabasePath(config, language),
language
);
logger.endGroup();
}
}
}
function dbIsFinalized(
config: configUtils.Config,
language: Language,
logger: Logger
) {
const dbPath = util.getCodeQLDatabasePath(config, language);
try {
const dbInfo = yaml.load(
fs.readFileSync(path.resolve(dbPath, "codeql-database.yml"), "utf8")
);
return !("inProgress" in dbInfo);
} catch (e) {
logger.warning(
`Could not check whether database for ${language} was finalized. Assuming it is not.`
);
return false;
}
}
async function finalizeDatabaseCreation(
config: configUtils.Config,
threadsFlag: string,
memoryFlag: string,
logger: Logger
) {
await createdDBForScannedLanguages(config, logger);
const codeql = await getCodeQL(config.codeQLCmd);
for (const language of config.languages) {
if (dbIsFinalized(config, language, logger)) {
logger.info(
`There is already a finalized database for ${language} at the location where the CodeQL Action places databases, so we did not create one.`
);
} else {
logger.startGroup(`Finalizing ${language}`);
await codeql.finalizeDatabase(
util.getCodeQLDatabasePath(config, language),
threadsFlag,
memoryFlag
);
logger.endGroup();
}
}
}
// Runs queries and creates sarif files in the given folder
export async function runQueries(
sarifFolder: string,
memoryFlag: string,
addSnippetsFlag: string,
threadsFlag: string,
automationDetailsId: string | undefined,
config: configUtils.Config,
logger: Logger
): Promise<QueriesStatusReport> {
const statusReport: QueriesStatusReport = {};
let locPromise: Promise<Partial<Record<Language, number>>> = Promise.resolve(
{}
);
const cliCanCountBaseline = await cliCanCountLoC();
const debugMode =
process.env["INTERNAL_CODEQL_ACTION_DEBUG_LOC"] ||
process.env["ACTIONS_RUNNER_DEBUG"] ||
process.env["ACTIONS_STEP_DEBUG"];
if (!cliCanCountBaseline || debugMode) {
// count the number of lines in the background
locPromise = countLoc(
path.resolve(),
// config.paths specifies external directories. the current
// directory is included in the analysis by default. Replicate
// that here.
config.paths,
config.pathsIgnore,
config.languages,
logger
);
}
for (const language of config.languages) {
const queries = config.queries[language];
const packsWithVersion = config.packs[language] || [];
const hasBuiltinQueries = queries?.builtin.length > 0;
const hasCustomQueries = queries?.custom.length > 0;
const hasPackWithCustomQueries = packsWithVersion.length > 0;
if (!hasBuiltinQueries && !hasCustomQueries && !hasPackWithCustomQueries) {
throw new Error(
`Unable to analyse ${language} as no queries were selected for this language`
);
}
try {
if (hasPackWithCustomQueries) {
logger.info("*************");
logger.info(
"Performing analysis with custom QL Packs. QL Packs are an experimental feature."
);
logger.info("And should not be used in production yet.");
logger.info("*************");
logger.startGroup(`Downloading custom packs for ${language}`);
const codeql = await getCodeQL(config.codeQLCmd);
const results = await codeql.packDownload(packsWithVersion);
logger.info(
`Downloaded packs: ${results.packs
.map((r) => `${r.name}@${r.version || "latest"}`)
.join(", ")}`
);
logger.endGroup();
}
logger.startGroup(`Running queries for ${language}`);
const querySuitePaths: string[] = [];
if (queries["builtin"].length > 0) {
const startTimeBuiltIn = new Date().getTime();
querySuitePaths.push(
await runQueryGroup(
language,
"builtin",
createQuerySuiteContents(queries["builtin"]),
undefined
)
);
statusReport[`analyze_builtin_queries_${language}_duration_ms`] =
new Date().getTime() - startTimeBuiltIn;
}
const startTimeCustom = new Date().getTime();
let ranCustom = false;
for (let i = 0; i < queries["custom"].length; ++i) {
if (queries["custom"][i].queries.length > 0) {
querySuitePaths.push(
await runQueryGroup(
language,
`custom-${i}`,
createQuerySuiteContents(queries["custom"][i].queries),
queries["custom"][i].searchPath
)
);
ranCustom = true;
}
}
if (packsWithVersion.length > 0) {
querySuitePaths.push(
await runQueryGroup(
language,
"packs",
createPackSuiteContents(packsWithVersion),
undefined
)
);
ranCustom = true;
}
if (ranCustom) {
statusReport[`analyze_custom_queries_${language}_duration_ms`] =
new Date().getTime() - startTimeCustom;
}
logger.endGroup();
logger.startGroup(`Interpreting results for ${language}`);
const startTimeInterpretResults = new Date().getTime();
const sarifFile = path.join(sarifFolder, `${language}.sarif`);
const analysisSummary = await runInterpretResults(
language,
querySuitePaths,
sarifFile
);
if (!cliCanCountBaseline)
await injectLinesOfCode(sarifFile, language, locPromise);
statusReport[`interpret_results_${language}_duration_ms`] =
new Date().getTime() - startTimeInterpretResults;
logger.endGroup();
logger.info(analysisSummary);
if (!cliCanCountBaseline || debugMode)
printLinesOfCodeSummary(logger, language, await locPromise);
if (cliCanCountBaseline) logger.info(await runPrintLinesOfCode(language));
} catch (e) {
logger.info(String(e));
if (e instanceof Error) {
logger.info(e.stack!);
}
statusReport.analyze_failure_language = language;
throw new CodeQLAnalysisError(
statusReport,
`Error running analysis for ${language}: ${e}`
);
}
}
return statusReport;
async function runInterpretResults(
language: Language,
queries: string[],
sarifFile: string
): Promise<string> {
const databasePath = util.getCodeQLDatabasePath(config, language);
const codeql = await getCodeQL(config.codeQLCmd);
return await codeql.databaseInterpretResults(
databasePath,
queries,
sarifFile,
addSnippetsFlag,
threadsFlag,
automationDetailsId
);
}
async function cliCanCountLoC() {
return await util.codeQlVersionAbove(
await getCodeQL(config.codeQLCmd),
CODEQL_VERSION_COUNTS_LINES
);
}
async function runPrintLinesOfCode(language: Language): Promise<string> {
const databasePath = util.getCodeQLDatabasePath(config, language);
const codeql = await getCodeQL(config.codeQLCmd);
return await codeql.databasePrintBaseline(databasePath);
}
async function runQueryGroup(
language: Language,
type: string,
querySuiteContents: string,
searchPath: string | undefined
): Promise<string> {
const databasePath = util.getCodeQLDatabasePath(config, language);
// Pass the queries to codeql using a file instead of using the command
// line to avoid command line length restrictions, particularly on windows.
const querySuitePath = `${databasePath}-queries-${type}.qls`;
fs.writeFileSync(querySuitePath, querySuiteContents);
logger.debug(
`Query suite file for ${language}-${type}...\n${querySuiteContents}`
);
const codeql = await getCodeQL(config.codeQLCmd);
await codeql.databaseRunQueries(
databasePath,
searchPath,
querySuitePath,
memoryFlag,
threadsFlag
);
logger.debug(`BQRS results produced for ${language} (queries: ${type})"`);
return querySuitePath;
}
}
function createQuerySuiteContents(queries: string[]) {
return queries.map((q: string) => `- query: ${q}`).join("\n");
}
function createPackSuiteContents(
packsWithVersion: configUtils.PackWithVersion[]
) {
return packsWithVersion.map(packWithVersionToQuerySuiteEntry).join("\n");
}
function packWithVersionToQuerySuiteEntry(
pack: configUtils.PackWithVersion
): string {
let text = `- qlpack: ${pack.packName}`;
if (pack.version) {
text += `\n version: ${pack.version}`;
}
return text;
}
export async function runFinalize(
outputDir: string,
threadsFlag: string,
memoryFlag: string,
config: configUtils.Config,
logger: Logger
) {
// Delete the tracer config env var to avoid tracing ourselves
delete process.env[sharedEnv.ODASA_TRACER_CONFIGURATION];
fs.mkdirSync(outputDir, { recursive: true });
await finalizeDatabaseCreation(config, threadsFlag, memoryFlag, logger);
}
export async function runCleanup(
config: configUtils.Config,
cleanupLevel: string,
logger: Logger
): Promise<void> {
logger.startGroup("Cleaning up databases");
for (const language of config.languages) {
const codeql = await getCodeQL(config.codeQLCmd);
const databasePath = util.getCodeQLDatabasePath(config, language);
await codeql.databaseCleanup(databasePath, cleanupLevel);
}
logger.endGroup();
}
async function injectLinesOfCode(
sarifFile: string,
language: Language,
locPromise: Promise<Partial<Record<Language, number>>>
) {
const lineCounts = await locPromise;
if (language in lineCounts) {
const sarif = JSON.parse(fs.readFileSync(sarifFile, "utf8"));
if (Array.isArray(sarif.runs)) {
for (const run of sarif.runs) {
run.properties = run.properties || {};
run.properties.metricResults = run.properties.metricResults || [];
for (const metric of run.properties.metricResults) {
// Baseline is inserted when matching rule has tag lines-of-code
if (metric.rule && metric.rule.toolComponent) {
const matchingRule =
run.tool.extensions[metric.rule.toolComponent.index].rules[
metric.rule.index
];
if (matchingRule.properties.tags?.includes("lines-of-code")) {
metric.baseline = lineCounts[language];
}
}
}
}
}
fs.writeFileSync(sarifFile, JSON.stringify(sarif));
}
}
function printLinesOfCodeSummary(
logger: Logger,
language: Language,
lineCounts: Partial<Record<Language, number>>
) {
if (language in lineCounts) {
logger.info(
`Counted a baseline of ${lineCounts[language]} lines of code for ${language}.`
);
}
} | the_stack |
import * as date from './mocks/date';
import * as vscode from './mocks/vscode';
jest.mock('vscode', () => vscode, { virtual: true });
jest.mock('fs');
jest.mock('https');
jest.mock('../src/dataSource');
jest.mock('../src/extensionState');
jest.mock('../src/logger');
import * as fs from 'fs';
import { ClientRequest, IncomingMessage } from 'http';
import * as https from 'https';
import { URL } from 'url';
import { ConfigurationChangeEvent } from 'vscode';
import { AvatarEvent, AvatarManager } from '../src/avatarManager';
import { DataSource } from '../src/dataSource';
import { ExtensionState } from '../src/extensionState';
import { Logger } from '../src/logger';
import { GitExecutable } from '../src/utils';
import { EventEmitter } from '../src/utils/event';
import { waitForExpect } from './helpers/expectations';
let onDidChangeConfiguration: EventEmitter<ConfigurationChangeEvent>;
let onDidChangeGitExecutable: EventEmitter<GitExecutable>;
let logger: Logger;
let dataSource: DataSource;
let extensionState: ExtensionState;
let spyOnSaveAvatar: jest.SpyInstance, spyOnRemoveAvatarFromCache: jest.SpyInstance, spyOnHttpsGet: jest.SpyInstance, spyOnWriteFile: jest.SpyInstance, spyOnReadFile: jest.SpyInstance, spyOnLog: jest.SpyInstance, spyOnGetRemoteUrl: jest.SpyInstance;
beforeAll(() => {
onDidChangeConfiguration = new EventEmitter<ConfigurationChangeEvent>();
onDidChangeGitExecutable = new EventEmitter<GitExecutable>();
logger = new Logger();
dataSource = new DataSource(null, onDidChangeConfiguration.subscribe, onDidChangeGitExecutable.subscribe, logger);
extensionState = new ExtensionState(vscode.mocks.extensionContext, onDidChangeGitExecutable.subscribe);
spyOnSaveAvatar = jest.spyOn(extensionState, 'saveAvatar');
spyOnRemoveAvatarFromCache = jest.spyOn(extensionState, 'removeAvatarFromCache');
spyOnHttpsGet = jest.spyOn(https, 'get');
spyOnWriteFile = jest.spyOn(fs, 'writeFile');
spyOnReadFile = jest.spyOn(fs, 'readFile');
spyOnLog = jest.spyOn(logger, 'log');
spyOnGetRemoteUrl = jest.spyOn(dataSource, 'getRemoteUrl');
});
afterAll(() => {
extensionState.dispose();
dataSource.dispose();
logger.dispose();
onDidChangeConfiguration.dispose();
onDidChangeGitExecutable.dispose();
});
describe('AvatarManager', () => {
let avatarManager: AvatarManager;
beforeEach(() => {
jest.spyOn(extensionState, 'getAvatarStoragePath').mockReturnValueOnce('/path/to/avatars');
jest.spyOn(extensionState, 'getAvatarCache').mockReturnValueOnce({
'user1@mhutchie.com': {
image: '530a7b02594e057f39179d3bd8b849f0.png',
timestamp: date.now * 1000,
identicon: false
},
'user2@mhutchie.com': {
image: '57853c107d1aeaa7da6f3096385cb848.png',
timestamp: date.now * 1000 - 1209600001,
identicon: false
},
'user3@mhutchie.com': {
image: 'e36b61e2afd912d3665f1aa92932aa87.png',
timestamp: date.now * 1000 - 345600001,
identicon: true
}
});
avatarManager = new AvatarManager(dataSource, extensionState, logger);
jest.clearAllTimers();
jest.useRealTimers();
});
afterEach(() => {
avatarManager.dispose();
});
it('Should construct an AvatarManager, and be disposed', () => {
// Assert
expect(avatarManager['disposables']).toHaveLength(2);
// Run
avatarManager.dispose();
// Assert
expect(avatarManager['disposables']).toHaveLength(0);
});
describe('fetchAvatarImage', () => {
it('Should trigger the avatar to be emitted when a known avatar is fetched', async () => {
// Setup
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user1@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user1@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
});
describe('GitHub', () => {
it('Should fetch a new avatar from GitHub (HTTPS Remote)', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(200, '{"author":{"avatar_url":"https://avatar-url"}}');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'api.github.com',
path: '/repos/mhutchie/test-repo/commits/1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'avatar-url',
path: '/&size=162',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch a new avatar from GitHub (SSH Remote)', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('git@github.com:mhutchie/test-repo.git');
mockHttpsResponse(200, '{"author":{"avatar_url":"https://avatar-url"}}');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', [
'1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
'2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c',
'3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d',
'4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e',
'5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f',
'6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a',
'1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
'2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c'
]);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'api.github.com',
path: '/repos/mhutchie/test-repo/commits/2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'avatar-url',
path: '/&size=162',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fallback to Gravatar when there is no avatar_url are in the GitHub response', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(200, '{"author":{}}');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'api.github.com',
path: '/repos/mhutchie/test-repo/commits/1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fallback to Gravatar when an unexpected status code is received from the GitHub API', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(401, '');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'api.github.com',
path: '/repos/mhutchie/test-repo/commits/1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should halt fetching the avatar when the GitHub avatar url request is unsuccessful', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(200, '{"author":{"avatar_url":"https://avatar-url"}}');
mockHttpsResponse(404, '');
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('Failed to download avatar from GitHub for user4@*****');
});
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'api.github.com',
path: '/repos/mhutchie/test-repo/commits/1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'avatar-url',
path: '/&size=162',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
});
it('Should requeue the request when the GitHub API cannot find the commit', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(422, '', { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': (date.now + 1).toString() });
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b', '2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c']);
// Assert
await waitForExpect(() => {
expect(avatarManager['queue']['queue'].length).toBe(1);
expect(avatarManager['queue']['queue'][0].attempts).toBe(1);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: [
'1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
'2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c'
],
checkAfter: 0,
attempts: 1
}
]);
});
it('Should set the GitHub API timeout and requeue the request when the rate limit is reached', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(403, '', { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': (date.now + 1).toString() });
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('GitHub API Rate Limit Reached - Paused fetching from GitHub until the Rate Limit is reset');
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: (date.now + 1) * 1000,
attempts: 0
}
]);
expect(avatarManager['githubTimeout']).toBe(1587559259000);
});
it('Should set the GitHub API timeout and requeue the request when the API returns a 5xx error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(500, '');
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['githubTimeout']).toBe(date.now * 1000 + 600000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 600000,
attempts: 0
}
]);
});
it('Should set the GitHub API timeout and requeue the request when there is an HTTPS Client Request Error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsClientRequestErrorEvent();
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['githubTimeout']).toBe(date.now * 1000 + 300000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 300000,
attempts: 0
}
]);
});
it('Should set the GitHub API timeout and requeue the request when there is an HTTPS Incoming Message Error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsIncomingMessageErrorEvent();
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['githubTimeout']).toBe(date.now * 1000 + 300000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 300000,
attempts: 0
}
]);
});
it('Should set the GitHub API timeout and requeue the request once when there are multiple HTTPS Error Events', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsMultipleErrorEvents();
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['githubTimeout']).toBe(date.now * 1000 + 300000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 300000,
attempts: 0
}
]);
});
it('Should requeue the request when it\'s before the GitHub API timeout', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
avatarManager['githubTimeout'] = (date.now + 1) * 1000;
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: 1587559259000,
attempts: 0
}
]);
});
});
});
describe('GitLab', () => {
it('Should fetch a new avatar from GitLab (HTTPS Remote)', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsResponse(200, '[{"avatar_url":"https://avatar-url"}]');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'gitlab.com',
path: '/api/v4/users?search=user4@mhutchie.com',
headers: { 'User-Agent': 'vscode-git-graph', 'Private-Token': 'w87U_3gAxWWaPtFgCcus' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'avatar-url',
path: '/',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch a new avatar from GitLab (SSH Remote)', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('git@gitlab.com:mhutchie/test-repo.git');
mockHttpsResponse(200, '[{"avatar_url":"https://avatar-url"}]');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'gitlab.com',
path: '/api/v4/users?search=user4@mhutchie.com',
headers: { 'User-Agent': 'vscode-git-graph', 'Private-Token': 'w87U_3gAxWWaPtFgCcus' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'avatar-url',
path: '/',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fallback to Gravatar when no users are in the GitLab response', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsResponse(200, '[]');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'gitlab.com',
path: '/api/v4/users?search=user4@mhutchie.com',
headers: { 'User-Agent': 'vscode-git-graph', 'Private-Token': 'w87U_3gAxWWaPtFgCcus' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fallback to Gravatar when an unexpected status code is received from the GitLab API', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsResponse(401, '');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'gitlab.com',
path: '/api/v4/users?search=user4@mhutchie.com',
headers: { 'User-Agent': 'vscode-git-graph', 'Private-Token': 'w87U_3gAxWWaPtFgCcus' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should halt fetching the avatar when the GitLab avatar url request is unsuccessful', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsResponse(200, '[{"avatar_url":"https://avatar-url"}]');
mockHttpsResponse(404, '');
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('Failed to download avatar from GitLab for user4@*****');
});
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'gitlab.com',
path: '/api/v4/users?search=user4@mhutchie.com',
headers: { 'User-Agent': 'vscode-git-graph', 'Private-Token': 'w87U_3gAxWWaPtFgCcus' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'avatar-url',
path: '/',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
});
it('Should set the GitLab API timeout and requeue the request when the rate limit is reached', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsResponse(429, '', { 'ratelimit-remaining': '0', 'ratelimit-reset': (date.now + 1).toString() });
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('GitLab API Rate Limit Reached - Paused fetching from GitLab until the Rate Limit is reset');
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: (date.now + 1) * 1000,
attempts: 0
}
]);
expect(avatarManager['gitLabTimeout']).toBe(1587559259000);
});
it('Should set the GitLab API timeout and requeue the request when the API returns a 5xx error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsResponse(500, '');
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['gitLabTimeout']).toBe(date.now * 1000 + 600000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 600000,
attempts: 0
}
]);
});
it('Should set the GitLab API timeout and requeue the request when there is an HTTPS Client Request Error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsClientRequestErrorEvent();
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['gitLabTimeout']).toBe(date.now * 1000 + 300000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 300000,
attempts: 0
}
]);
});
it('Should set the GitLab API timeout and requeue the request when there is an HTTPS Incoming Message Error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsIncomingMessageErrorEvent();
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['gitLabTimeout']).toBe(date.now * 1000 + 300000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 300000,
attempts: 0
}
]);
});
it('Should set the GitLab API timeout and requeue the request once when there are multiple HTTPS Error Events', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
mockHttpsMultipleErrorEvents();
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['gitLabTimeout']).toBe(date.now * 1000 + 300000);
});
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: date.now * 1000 + 300000,
attempts: 0
}
]);
});
it('Should requeue the request when it\'s before the GitLab API timeout', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://gitlab.com/mhutchie/test-repo.git');
avatarManager['gitLabTimeout'] = (date.now + 1) * 1000;
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: 1587559259000,
attempts: 0
}
]);
});
});
});
describe('Gravatar', () => {
it('Should fetch a new avatar from Gravatar', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('Saved Avatar for user4@*****');
expect(spyOnLog).toHaveBeenCalledWith('Sent Avatar for user4@***** to the Git Graph View');
});
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch an identicon if no avatar can be found on Gravatar', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsResponse(404, '');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=identicon',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: true
});
});
it('Should not save an avatar if it cannot be fetched from Gravatar', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsResponse(404, '');
mockHttpsResponse(500, '');
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('No Avatar could be found for user4@*****');
});
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=identicon',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
});
it('Should fetch an avatar from Gravatar when no remote is specified', async () => {
// Setup
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', null, ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).not.toHaveBeenCalled();
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch an avatar from Gravatar when the remote hostname is not GitHub or GitLab', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('http://other-host/mhutchie/test-repo.git');
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch an identicon the avatar fails to be saved', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(new Error());
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=identicon',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: true
});
});
it('Should fetch an identicon if the first avatar request receives an HTTPS Client Request Error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsClientRequestErrorEvent();
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=identicon',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: true
});
});
it('Should fetch an identicon if the first avatar request receives an HTTPS Incoming Message Error', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsIncomingMessageErrorEvent();
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=identicon',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: true
});
});
it('Should fetch an identicon once if the first avatar request receives multiple HTTPS Error Events', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsMultipleErrorEvents();
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=identicon',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledTimes(1);
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: true
});
});
it('Should fetch an identicon the first avatar HTTPS request throws an expected exception', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
spyOnHttpsGet.mockImplementationOnce(() => {
throw new Error();
});
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=identicon',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: true
});
});
});
it('Should fetch an avatar when the existing avatar is over 14 days old', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockReadFile('binary-image-data');
mockHttpsResponse(200, 'new-binary-image-data');
mockWriteFile(null);
mockReadFile('new-binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 2);
// Run
avatarManager.fetchAvatarImage('user2@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([
{
email: 'user2@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
},
{
email: 'user2@mhutchie.com',
image: 'data:image/png;base64,bmV3LWJpbmFyeS1pbWFnZS1kYXRh'
}
]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/57853c107d1aeaa7da6f3096385cb848?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/57853c107d1aeaa7da6f3096385cb848.png', 'new-binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/57853c107d1aeaa7da6f3096385cb848.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user2@mhutchie.com', {
image: '57853c107d1aeaa7da6f3096385cb848.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Shouldn\'t replace the existing avatar if it wasn\'t an identicon and the new avatar is', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockReadFile('binary-image-data');
mockHttpsResponse(404, 'new-binary-image-data');
mockHttpsResponse(200, 'new-binary-image-data');
mockWriteFile(null);
mockReadFile('new-binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 2);
// Run
avatarManager.fetchAvatarImage('user2@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([
{
email: 'user2@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
},
{
email: 'user2@mhutchie.com',
image: 'data:image/png;base64,bmV3LWJpbmFyeS1pbWFnZS1kYXRh'
}
]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/57853c107d1aeaa7da6f3096385cb848?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/57853c107d1aeaa7da6f3096385cb848.png', 'new-binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/57853c107d1aeaa7da6f3096385cb848.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user2@mhutchie.com', {
image: '57853c107d1aeaa7da6f3096385cb848.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch an avatar when the existing identicon is over 4 days old', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockReadFile('binary-image-data');
mockHttpsResponse(200, 'new-binary-image-data');
mockWriteFile(null);
mockReadFile('new-binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 2);
// Run
avatarManager.fetchAvatarImage('user3@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([
{
email: 'user3@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
},
{
email: 'user3@mhutchie.com',
image: 'data:image/png;base64,bmV3LWJpbmFyeS1pbWFnZS1kYXRh'
}
]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/e36b61e2afd912d3665f1aa92932aa87?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/e36b61e2afd912d3665f1aa92932aa87.png', 'new-binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/e36b61e2afd912d3665f1aa92932aa87.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user3@mhutchie.com', {
image: 'e36b61e2afd912d3665f1aa92932aa87.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch multiple avatars', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
jest.useFakeTimers();
mockHttpsResponse(200, 'binary-image-data-one');
mockWriteFile(null);
mockReadFile('binary-image-data-one');
mockHttpsResponse(200, 'binary-image-data-two');
mockWriteFile(null);
mockReadFile('binary-image-data-two');
const avatarEvents = waitForEvents(avatarManager, 2, true);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
avatarManager.fetchAvatarImage('user5@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([
{
email: 'user4@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGEtb25l'
},
{
email: 'user5@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGEtdHdv'
}
]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data-one');
expectFileToHaveBeenRead('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/da4173f868c17bcd6353cdba41070ca9?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/da4173f868c17bcd6353cdba41070ca9.png', 'binary-image-data-two');
expectFileToHaveBeenRead('/path/to/avatars/da4173f868c17bcd6353cdba41070ca9.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user5@mhutchie.com', {
image: 'da4173f868c17bcd6353cdba41070ca9.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch a new avatar when the existing image can\'t be read', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockReadFile(null);
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile('binary-image-data');
const avatarEvents = waitForEvents(avatarManager, 1);
// Run
avatarManager.fetchAvatarImage('user1@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(await avatarEvents).toStrictEqual([{
email: 'user1@mhutchie.com',
image: 'data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE='
}]);
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnRemoveAvatarFromCache).toHaveBeenCalledWith('user1@mhutchie.com');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/530a7b02594e057f39179d3bd8b849f0?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/530a7b02594e057f39179d3bd8b849f0.png', 'binary-image-data');
expectFileToHaveBeenRead('/path/to/avatars/530a7b02594e057f39179d3bd8b849f0.png');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user1@mhutchie.com', {
image: '530a7b02594e057f39179d3bd8b849f0.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch a new avatar, but not send it to the Git Graph View', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
mockReadFile(null);
avatarManager.onAvatar(() => { });
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('Saved Avatar for user4@*****');
expect(spyOnLog).toHaveBeenCalledWith('Failed to Send Avatar for user4@***** to the Git Graph View');
});
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should fetch a new avatar, and log when it fails to send it to the Git Graph View', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce(null);
mockHttpsResponse(200, 'binary-image-data');
mockWriteFile(null);
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('Saved Avatar for user4@*****');
expect(spyOnLog).toHaveBeenCalledWith('Avatar for user4@***** is ready to be used the next time the Git Graph View is opened');
});
expect(spyOnGetRemoteUrl).toHaveBeenCalledWith('test-repo', 'test-remote');
expect(spyOnHttpsGet).toHaveBeenCalledWith({
hostname: 'secure.gravatar.com',
path: '/avatar/0ca9d3f228e867bd4feb6d62cc2edbfe?s=162&d=404',
headers: { 'User-Agent': 'vscode-git-graph' },
agent: false,
timeout: 15000
}, expect.anything());
expectFileToHaveBeenWritten('/path/to/avatars/0ca9d3f228e867bd4feb6d62cc2edbfe.png', 'binary-image-data');
expect(spyOnSaveAvatar).toHaveBeenCalledWith('user4@mhutchie.com', {
image: '0ca9d3f228e867bd4feb6d62cc2edbfe.png',
timestamp: 1587559258000,
identicon: false
});
});
it('Should add new commits to existing records queued for the same user in the same repository', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(403, '', { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': (date.now + 1).toString() });
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', [
'1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
'3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d',
'5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f'
]);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('GitHub API Rate Limit Reached - Paused fetching from GitHub until the Rate Limit is reset');
});
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', [
'1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
'2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c',
'3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d',
'4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e'
]);
// Assert
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: [
'1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b',
'3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d',
'5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f',
'2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c',
'4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e'
],
checkAfter: (date.now + 1) * 1000,
attempts: 0
}
]);
expect(avatarManager['githubTimeout']).toBe(1587559259000);
});
it('Should insert requests into the priority queue in the correct order', async () => {
// Setup
spyOnGetRemoteUrl.mockResolvedValueOnce('https://github.com/mhutchie/test-repo.git');
mockHttpsResponse(403, '', { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': (date.now + 1).toString() });
// Run
avatarManager.fetchAvatarImage('user4@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
await waitForExpect(() => {
expect(spyOnLog).toHaveBeenCalledWith('GitHub API Rate Limit Reached - Paused fetching from GitHub until the Rate Limit is reset');
});
// Run
avatarManager.fetchAvatarImage('user2@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
avatarManager.fetchAvatarImage('user5@mhutchie.com', 'test-repo', 'test-remote', ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b']);
// Assert
expect(avatarManager['queue']['queue']).toStrictEqual([
{
email: 'user5@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: 0,
attempts: 0
},
{
email: 'user4@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: (date.now + 1) * 1000,
attempts: 0
},
{
email: 'user2@mhutchie.com',
repo: 'test-repo',
remote: 'test-remote',
commits: ['1a2b3c4d5e6f1a2b3c4d5e6f1a2b3c4d5e6f1a2b'],
checkAfter: (date.now + 1) * 1000 + 1,
attempts: 0
}
]);
});
});
describe('getAvatarImage', () => {
it('Should return a Data Url of the avatar\'s image data', async () => {
// Setup
mockReadFile('binary-image-data');
// Run
const avatar = await avatarManager.getAvatarImage('user1@mhutchie.com');
// Assert
expect(avatar).toBe('data:image/png;base64,YmluYXJ5LWltYWdlLWRhdGE=');
expectFileToHaveBeenRead('/path/to/avatars/530a7b02594e057f39179d3bd8b849f0.png');
});
it('Should return null when the avatar file could not be read from the file system', async () => {
// Setup
mockReadFile(null);
// Run
const avatar = await avatarManager.getAvatarImage('user1@mhutchie.com');
// Assert
expect(avatar).toBe(null);
expectFileToHaveBeenRead('/path/to/avatars/530a7b02594e057f39179d3bd8b849f0.png');
});
it('Should return null when no avatar exists for the provided email address', async () => {
// Run
const avatar = await avatarManager.getAvatarImage('user4@mhutchie.com');
// Assert
expect(avatar).toBe(null);
expect(spyOnReadFile).not.toHaveBeenCalled();
});
});
describe('clearCache', () => {
let spyOnClearAvatarCache: jest.SpyInstance;
beforeAll(() => {
spyOnClearAvatarCache = jest.spyOn(extensionState, 'clearAvatarCache');
});
it('Should clear the cache of avatars', async () => {
// Setup
spyOnClearAvatarCache.mockResolvedValueOnce(null);
// Run
const result = await avatarManager.clearCache();
// Assert
expect(result).toBeNull();
expect(avatarManager['avatars']).toStrictEqual({});
expect(spyOnClearAvatarCache).toHaveBeenCalledTimes(1);
});
it('Should return the error message returned by ExtensionState.clearAvatarCache', async () => {
// Setup
const errorMessage = 'Visual Studio Code was unable to save the Git Graph Global State Memento.';
spyOnClearAvatarCache.mockResolvedValueOnce(errorMessage);
// Run
const result = await avatarManager.clearCache();
// Assert
expect(result).toBe(errorMessage);
expect(avatarManager['avatars']).toStrictEqual({});
expect(spyOnClearAvatarCache).toHaveBeenCalledTimes(1);
});
});
});
function mockHttpsResponse(statusCode: number, imageData: string, headers: { [header: string]: string } = {}) {
spyOnHttpsGet.mockImplementationOnce((_: string | https.RequestOptions | URL, callback: (res: IncomingMessage) => void): ClientRequest => {
if (callback) {
const callbacks: { [event: string]: (...args: any) => void } = {};
const message: IncomingMessage = <any>{
statusCode: statusCode,
headers: Object.assign({
'content-type': 'image/png'
}, headers),
on: (event: string, listener: () => void) => {
callbacks[event] = listener;
return message;
}
};
callback(message);
callbacks['data'](Buffer.from(imageData));
callbacks['end']();
}
return ({
on: jest.fn()
}) as any as ClientRequest;
});
}
function mockHttpsClientRequestErrorEvent() {
spyOnHttpsGet.mockImplementationOnce((_1: string | https.RequestOptions | URL, _2: (res: IncomingMessage) => void): ClientRequest => {
const request: ClientRequest = <any>{
on: (event: string, callback: () => void) => {
if (event === 'error') {
callback();
}
return request;
}
};
return request;
});
}
function mockHttpsIncomingMessageErrorEvent() {
spyOnHttpsGet.mockImplementationOnce((_: string | https.RequestOptions | URL, callback: (res: IncomingMessage) => void): ClientRequest => {
const callbacks: { [event: string]: (...args: any) => void } = {};
const message: IncomingMessage = <any>{
on: (event: string, listener: () => void) => {
callbacks[event] = listener;
return message;
}
};
callback(message);
callbacks['error']();
return ({
on: jest.fn()
}) as any as ClientRequest;
});
}
function mockHttpsMultipleErrorEvents() {
spyOnHttpsGet.mockImplementationOnce((_: string | https.RequestOptions | URL, callback: (res: IncomingMessage) => void): ClientRequest => {
const callbacks: { [event: string]: (...args: any) => void } = {};
const message: IncomingMessage = <any>{
on: (event: string, listener: () => void) => {
callbacks[event] = listener;
return message;
}
};
callback(message);
callbacks['error']();
const request: ClientRequest = <any>{
on: (event: string, callback: () => void) => {
if (event === 'error') {
callback();
}
return request;
}
};
return request;
});
}
function mockWriteFile(error: NodeJS.ErrnoException | null) {
spyOnWriteFile.mockImplementationOnce((_1: fs.PathLike | number, _2: Buffer, callback: (err: NodeJS.ErrnoException | null) => void) => callback(error));
}
function mockReadFile(data: string | null) {
spyOnReadFile.mockImplementationOnce((_: fs.PathLike | number, callback: (err: NodeJS.ErrnoException | null, _: Buffer) => void) => {
if (data) {
callback(null, Buffer.from(data));
} else {
callback(new Error(), Buffer.alloc(0));
}
});
}
function expectFileToHaveBeenWritten(name: string, data: string) {
expect(spyOnWriteFile.mock.calls.some((args) => args[0] === name && args[1].toString() === data)).toBe(true);
}
function expectFileToHaveBeenRead(name: string) {
expect(spyOnReadFile.mock.calls.some((args) => args[0] === name)).toBe(true);
}
function waitForEvents(avatarManager: AvatarManager, n: number, runPendingTimers = false) {
return new Promise<AvatarEvent[]>((resolve) => {
const events: AvatarEvent[] = [];
avatarManager.onAvatar((event) => {
events.push(event);
if (runPendingTimers) {
jest.runOnlyPendingTimers();
}
if (events.length === n) {
resolve(events);
}
});
});
} | the_stack |
export as namespace Zdog;
/** @see {@link Anchor} */
export interface AnchorOptions {
/**
* Adds item to parent item.
* Shapes can be added as children to other shapes.
* A child shape is positioned relative to its parent.
* @see {@link https://zzz.dog/api#anchor-addto Zdog API}
*/
readonly addTo?: Anchor | undefined;
/**
* Positions the item.
* @see {@link https://zzz.dog/api#anchor-translate Zdog API}
*/
readonly translate?: VectorOptions | undefined;
/**
* Rotates the item.
* Set to rotate the item around the corresponding axis.
* @see {@link https://zzz.dog/api#anchor-rotate Zdog API}
*/
readonly rotate?: VectorOptions | undefined;
/**
* Enlarges or shrinks item geometry. `scale` does not scale `stroke`.
* @see {@link https://zzz.dog/api#anchor-scale Zdog API}
*/
readonly scale?: VectorOptions | number | undefined;
}
/**
* An item that can be added to another item, and have other items added to it.
* Anchor is the super class of all item and shape classes — {@link Shape}, {@link Group}, {@link Illustration}, {@link Rect}, {@link Ellipse}, {@link Box}, etc.
* All items that can be added to a Zdog scene act as `Anchor`s.
* All item classes can use `Anchor` properties and methods.
* The `Anchor` class itself is an invisible item.
* {@link https://zzz.dog/modeling#concepts-anchors Anchors are useful for collecting related shapes and transforming them together.}
* @see {@link https://zzz.dog/api#anchor Zdog API}
*/
export class Anchor {
/** @see {@link AnchorOptions#addTo} */
addTo?: Anchor | undefined;
/** @see {@link AnchorOptions#translate} */
translate: Vector;
/** @see {@link AnchorOptions#rotate} */
rotate: Vector;
/** @see {@link AnchorOptions#scale} */
scale: Vector;
constructor(options?: AnchorOptions);
/**
* Copy an item.
* `copy()` only copies the item, not the item’s graph of descendant items.
* Use {@link copyGraph}() to copy the item and its graph.
* @see {@link https://zzz.dog/api#anchor-copy Zdog API}
*/
copy(options?: AnchorOptions): Anchor;
/**
* Copies item and its descendent items.
* @see {@link https://zzz.dog/api#anchor-copygraph Zdog API}
*/
copyGraph(options?: AnchorOptions): Anchor;
/**
* Adds child item. `addChild()` is useful for moving a child item to a new parent, or creating an item without {@link addTo}.
* @see {@link https://zzz.dog/api#anchor-addchild Zdog API}
*/
addChild(anchor: Anchor): void;
/**
* Removes child item.
* @see {@link https://zzz.dog/api#anchor-removechild Zdog API}
*/
removeChild(anchor: Anchor): void;
/**
* Removes item from parent.
* @see {@link https://zzz.dog/api#anchor-remove Zdog API}
*/
remove(): void;
/**
* Updates the items and all its graph of descendant items so they are ready for rendering.
* Useful for {@link https://zzz.dog/extras#rendering-without-illustration rendering without `Illustration`}.
* @see {@link https://zzz.dog/api#anchor-updategraph Zdog API}
*/
updateGraph(): void;
/**
* Renders the item and all its descendant items to a `<canvas>` element.
* Useful for {@link https://zzz.dog/extras#rendering-without-illustration rendering without `Illustration`}.
* @see {@link https://zzz.dog/api#anchor-rendergraphcanvas Zdog API}
*/
renderGraphCanvas(ctx: CanvasRenderingContext2D): void;
/**
* Renders the item and all its descendant items to an SVG element.
* Useful for {@link https://zzz.dog/extras#rendering-without-illustration rendering without `Illustration`}.
* @see {@link https://zzz.dog/api#anchor-rendergraphsvg Zdog API}
*/
renderGraphSvg(svg: SVGSVGElement): void;
/**
* Wraps-around {@link rotate} `x`, `y`, & `z` values between `0` and {@link TAU}.
* @see {@link https://zzz.dog/api#anchor-normalizerotate Zdog API}
*/
normalizeRotate(): void;
}
export interface PathLineCommand {
/** @see {@link https://zzz.dog/shapes#shape-line Zdog Shape API} */
line: VectorOptions;
}
export interface PathMoveCommand {
/** @see {@link https://zzz.dog/shapes#shape-move Zdog Shape API} */
move: VectorOptions;
}
export interface PathArcCommand {
/** @see {@link https://zzz.dog/shapes#shape-arc Zdog Shape API} */
arc: readonly [VectorOptions, VectorOptions];
}
export interface PathBezierCommand {
/** @see {@link https://zzz.dog/shapes#shape-bezier Zdog Shape API} */
bezier: readonly [VectorOptions, VectorOptions, VectorOptions];
}
/* tslint:disable:max-line-length */
/**
* Set {@link ShapeOptions#path path} to {@link Array} of path commands.
* Path commands set the directions for the path to shape.
* Similar to drawing a path in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#Drawing_paths 2D <canvas>}, {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths SVG paths}, or {@link https://en.wikipedia.org/wiki/Logo_(programming_language) Logo’s turtle graphics}.
* @see {@link https://zzz.dog/shapes#shape-path-commands Zdog Shape API}
*/
export type PathCommand = VectorOptions | PathLineCommand | PathMoveCommand | PathArcCommand | PathBezierCommand;
/* tslint:enable:max-line-length */
/** @see {@link Shape} */
export interface ShapeOptions extends AnchorOptions {
/**
* Sets shape stroke and fill color.
* Set to any color string — hex code, `rgb()`, `hsla()`, etc.
* @default '#333'
* @see {@link https://zzz.dog/api#shape-color Zdog API}
*/
readonly color?: string | undefined;
/**
* Renders the shape line and sets line width.
* Set to `0` or `false` to disable.
* @default 1
* @see {@link https://zzz.dog/api#shape-stroke Zdog API}
*/
readonly stroke?: number | false | undefined;
/**
* Renders the inner shape area.
* @default false
* @see {@link https://zzz.dog/api#shape-fill Zdog API}
*/
readonly fill?: boolean | undefined;
/**
* Closes the path from the last point back to the first.
* @default true
* @see {@link https://zzz.dog/api#shape-closed Zdog API}
* @see {@link https://zzz.dog/shapes#shape-closed Zdog Shapes API}
*/
readonly closed?: boolean | undefined;
/**
* Shows or hides shape. Does not affect child items.
* @default true
* @see {@link https://zzz.dog/api#shape-visible Zdog API}
*/
readonly visible?: boolean | undefined;
/**
* Shows or hides the shape when its backface is visible.
* @default true
* @see {@link https://zzz.dog/api#shape-backface Zdog API}
*/
readonly backface?: boolean | string | undefined;
/**
* A {@link Vector} used to determine where the front of the shape is.
* Useful for changing how {@link backface} works for custom `Shape`s.
* @default {z: 1}
* @see {@link https://zzz.dog/api#shape-front Zdog API}
*/
readonly front?: VectorOptions | undefined;
/**
* Defines the shape.
* @see {@link https://zzz.dog/shapes#shape-path Zdog Shape API}
*/
readonly path?: readonly PathCommand[] | undefined;
}
/**
* A visible shape.
* `Shape` is the super-class for all shape classes — {@link Rect}, {@link Ellipse}, {@link Cone}, etc.
* All shape classes can use `Shape` options and methods.
* @see {@link https://zzz.dog/api#shape Zdog API}
* @see {@link https://zzz.dog/shapes#shape Zdog Shape API}
*/
export class Shape extends Anchor {
/** @see {@link ShapeOptions#color} */
color: string;
/** @see {@link ShapeOptions#stroke} */
stroke: number | false;
/** @see {@link ShapeOptions#fill} */
fill: boolean;
/** @see {@link ShapeOptions#closed} */
closed: boolean;
/** @see {@link ShapeOptions#visible} */
visible: boolean;
/** @see {@link ShapeOptions#backface} */
backface: boolean | string;
/** @see {@link ShapeOptions#front} */
front: Vector;
constructor(options?: ShapeOptions);
/**
* Updates the shape path.
* Trigger `updatePath()` after you change a point on a `Shape`’s path, a {@link Rect}’s width or height, etc.
* @see {@link https://zzz.dog/api#shape-updatepath Zdog API}
*/
updatePath(): void;
copy(options?: ShapeOptions): Shape;
copyGraph(options?: ShapeOptions): Shape;
}
/** @see {@link Group} */
export interface GroupOptions extends AnchorOptions {
/**
* Shows or hides group, including all child items in the group.
* {@link Shape#visible} only shows or hides the item.
* @default true
* @see {@link https://zzz.dog/api#group-visible Zdog API}
*/
readonly visible?: boolean | undefined;
/**
* Updates the rendering order of the group’s child items.
* @default false
* @see {@link https://zzz.dog/api#group-updatesort Zdog API}
*/
readonly updateSort?: boolean | undefined;
}
/**
* An item with a separated rendering order.
* Use a `Group` to control rendering order.
* Shapes will be rendered in the order they are added to the `Group`.
* `Group`s are useful for positioning shapes within other shapes, like windows in walls or pupils in eyes.
* @see {@link https://zzz.dog/api#group Zdog API}
*/
export class Group extends Anchor {
/** @see {@link GroupOptions#visible} */
visible: boolean;
/** @see {@link GroupOptions#updateSort} */
updateSort: boolean;
constructor(options?: GroupOptions);
copy(options?: GroupOptions): Group;
copyGraph(options?: GroupOptions): Group;
}
export interface PointerPosition {
pageX: number;
pageY: number;
}
/**
* Callback function triggered when dragging starts with the initial `mousedown`, `pointerdown`, or `touchstart` event.
* @param pointer the Event or Touch object
* @see {@link https://zzz.dog/api#dragger-ondragstart Zdog API}
*/
export type DragStartListener = (this: Dragger, pointer: PointerPosition) => void;
/**
* Callback function triggered when dragging moves with `mousemove`, `pointermove`, or `touchmove` event.
* @param pointer the Event or Touch object
* @param moveX horizontal distance moved from the dragStart position.
* @param moveY vertical distance moved from the dragStart position.
* @see {@link https://zzz.dog/api#dragger-ondragmove Zdog API}
*/
export type DragMoveListener = (this: Dragger, pointer: PointerPosition, moveX: number, moveY: number) => void;
/**
* Callback function triggered when dragging ends on the `mouseup`, `pointerup`, or `touchend` event.
* @see {@link https://zzz.dog/api#dragger-ondragend Zdog API}
*/
export type DragEndListener = (this: Dragger) => void;
/** @see {@link Dragger} */
export interface DraggerOptions {
/**
* The element to start dragging on the initial `mousedown`, `pointerdown`, or `touchstart` event.
*/
readonly startElement?: string | Element | undefined;
readonly onDragStart?: DragStartListener | undefined;
readonly onDragMove?: DragMoveListener | undefined;
readonly onDragEnd?: DragEndListener | undefined;
}
/**
* Tracks dragging interaction with pointer events.
* {@link Illustration} inherits `Dragger` which enables {@link IllustrationOptions#dragRotate dragRotate} and use of the `onDrag` callback functions.
* @see {@link https://zzz.dog/api#dragger Zdog API}
*/
export class Dragger {
/** @see {@link DraggerOptions#onDragStart} */
onDragStart: DragStartListener;
/** @see {@link DraggerOptions#onDragMove} */
onDragMove: DragMoveListener;
/** @see {@link DraggerOptions#onDragEnd} */
onDragEnd: DragEndListener;
constructor(options?: DraggerOptions);
}
/**
* A function triggered when the element is resized
* @see {@link https://zzz.dog/api#illustration-onresize Zdog API}
*/
export type ResizeListener = (this: Illustration, width: number, height: number) => void;
/**
* Function triggered before rendering.
* @param context the rendering context. For `<canvas>`, the {@link CanvasRenderingContext2D}. For `<svg>`, the {@link SVGSVGElement <svg> element}.
* @see {@link https://zzz.dog/api#illustration-onprerender Zdog API}
*/
export type PrerenderListener = (this: Illustration, context: CanvasRenderingContext2D | SVGSVGElement) => void;
/** @see {@link Illustration} */
export interface IllustrationOptions extends AnchorOptions, DraggerOptions {
/**
* The HTML element to render on, either a <canvas> or an <svg>.
* @see {@link https://zzz.dog/api#illustration-element Zdog API}
*/
readonly element: string | HTMLCanvasElement | SVGSVGElement;
/**
* Enlarges or shrinks the displayed size of the rendering.
* Whereas {@link Anchor#scale scale} will change the size of item geometry, `zoom` changes item geometry and {@link Shape#stroke stroke} size.
* @default 1
* @see {@link https://zzz.dog/api#illustration-zoom Zdog API}
*/
readonly zoom?: number | undefined;
/**
* Centers the scene in the element.
* @default true
* @see {@link https://zzz.dog/api#illustration-centered Zdog API}
*/
readonly centered?: boolean | undefined;
/**
* Enables dragging to rotate on an item.
* @default false
* @see {@link https://zzz.dog/api#illustration-dragrotate Zdog API}
*/
readonly dragRotate?: boolean | Anchor | undefined;
/**
* Enables fluid resizing of element.
* @default false
* @see {@link https://zzz.dog/api#illustration-resize Zdog API}
*/
readonly resize?: boolean | undefined;
readonly onResize?: ResizeListener | undefined;
readonly onPrerender?: PrerenderListener | undefined;
}
/**
* Handles displaying and rotating a scene on an HTML element.
* @see {@link https://zzz.dog/api#illustration Zdog API}
*/
export class Illustration extends Anchor implements Dragger {
onDragStart: DragStartListener;
onDragMove: DragMoveListener;
onDragEnd: DragEndListener;
/** @see {@link IllustrationOptions#element} */
element: HTMLCanvasElement | SVGSVGElement;
/** @see {@link IllustrationOptions#zoom} */
zoom: number;
/** @see {@link IllustrationOptions#centered} */
centered: boolean;
/** @see {@link IllustrationOptions#dragRotate} */
dragRotate: boolean;
/** @see {@link IllustrationOptions#resize} */
resize: boolean;
/** @see {@link IllustrationOptions#onResize} */
onResize: ResizeListener;
/** @see {@link IllustrationOptions#onPrerender} */
onPrerender: PrerenderListener;
constructor(options: IllustrationOptions);
/**
* Renders an item and its graph to the Illustration’s element.
* @see {@link https://zzz.dog/api#illustration-rendergraph Zdog API}
*/
renderGraph(scene?: Anchor): void;
/**
* Combines {@link updateGraph}() and {@link renderGraph}() methods — to save you a line of code.
* Updates and renders an item and its graph to the `Illustration`’s element.
* @see {@link https://zzz.dog/api#illustration-updaterendergraph Zdog API}
*/
updateRenderGraph(scene?: Anchor): void;
/**
* Sets element size.
* @see {@link https://zzz.dog/api#illustration-setsize Zdog API}
*/
setSize(width: number, height: number): void;
}
/**
* A vector `Object` is a plain ol' JavaScript `Object` with `x`, `y`, `z` coordinate properties.
*/
export interface VectorOptions {
readonly x?: number | undefined;
readonly y?: number | undefined;
readonly z?: number | undefined;
}
/**
* The coordinate properties are optional. They default to `0` if `undefined`.
* So you only need to set non-zero values.
* @see {@link https://zzz.dog/api#vector-vector-objects Zdog API}
*/
export class Vector {
/** @see {@link VectorOptions#backface} */
x: number;
/** @see {@link VectorOptions#backface} */
y: number;
/** @see {@link VectorOptions#backface} */
z: number;
constructor(position?: VectorOptions);
/**
* Sets {@link x}, {@link y}, {@link z} coordinates.
* @see {@link https://zzz.dog/api#vector-set Zdog API}
*/
set(position?: VectorOptions): this;
/**
* Returns a new {@link Vector} with copied {@link x}, {@link y} and {@link z} coordinates.
* Most Vector methods are mutable — they change the Vector’s coordinates.
* Use .{@link copy}() to work with a vector while still preserving the original.
* @see {@link https://zzz.dog/api#vector-copy Zdog API}
*/
copy(): Vector;
/**
* Adds {@link x}, {@link y}, {@link z} coordinate values.
* @see {@link https://zzz.dog/api#vector-add Zdog API}
*/
add(position?: VectorOptions): this;
/**
* Subtracts {@link x}, {@link y}, {@link z} coordinate values.
* @see {@link https://zzz.dog/api#vector-subtract Zdog API}
*/
subtract(position?: VectorOptions): this;
/**
* Multiplies {@link x}, {@link y}, {@link z} coordinate values.
* @see {@link https://zzz.dog/api#vector-multiply Zdog API}
*/
multiply(position?: number | VectorOptions): this;
/**
* Rotates a position vector given a `rotation` vector Object.
* @see {@link https://zzz.dog/api#vector-rotate Zdog API}
*/
rotate(rotation?: VectorOptions): this;
/**
* Returns the total length of the vector.
* @see {@link https://zzz.dog/api#vector-magnitude Zdog API}
*/
magnitude(): number;
/**
* Linear interporlate the vector towards `point`, given `alpha` a percent between the vector and `point`.
* @see {@link https://zzz.dog/api#vector-lerp Zdog API}
*/
lerp(position: VectorOptions, alpha: number): this;
}
/**
* A full rotation in radians. {@link Math.PI} * 2.
* TAU is more user-friendly than `PI` as `TAU` maps directly to a full rotation.
* @see {@link https://zzz.dog/api#utilities-tau Zdog API}
*/
export const TAU: number;
/**
* Apply an in-out easing. Useful for animation.
* @param alpha 0 to 1
* @param power=2 the exponential power of the easing curve
* @see {@link https://zzz.dog/api#utilities-easeinout Zdog API}
*/
export function easeInOut(alpha: number, power?: number): number;
/**
* @deprecated
* Sets the properties of Object `b` on to Object `a`.
* @see {@link https://zzz.dog/api#utilities-extend Zdog API}
*/
export function extend<T>(a: T, b?: Readonly<T>): T;
/**
* Linear interpolation between values `a` and `b` given a percent decimal `alpha`.
* @see {@link https://zzz.dog/api#utilities-lerp Zdog API}
*/
export function lerp(a: number, b: number, alpha: number): number;
/**
* Returns {@link https://en.wikipedia.org/wiki/Modular_arithmetic modulo} or "wrap around" value of `a` given `b`.
* @see {@link https://zzz.dog/api#utilities-modulo Zdog API}
*/
export function modulo(a: number, b: number): number;
/** @see {@link Rect} */
export interface RectOptions extends ShapeOptions {
/** @default 1 */
readonly width?: number | undefined;
/** @default 1 */
readonly height?: number | undefined;
}
/**
* A rectangle. Set size with {@link width} and {@link height}.
* @see {@link https://zzz.dog/shapes#rect Zdog Shapes API}
*/
export class Rect extends Shape {
/** @see {@link RectOptions#width} */
width: number;
/** @see {@link RectOptions#height} */
height: number;
constructor(options?: RectOptions);
copy(options?: RectOptions): Rect;
copyGraph(options?: RectOptions): Rect;
}
/** @see {@link RoundedRect} */
export interface RoundedRectOptions extends ShapeOptions {
/** @default 1 */
readonly width?: number | undefined;
/** @default 1 */
readonly height?: number | undefined;
/** @default 0.25 */
readonly cornerRadius?: number | undefined;
}
/**
* A rectangle with rounded corners.
* @see {@link https://zzz.dog/shapes#roundedrect Zdog Shapes API}
*/
export class RoundedRect extends Shape {
/** {@link RectOptions#width} */
width: number;
/** {@link RectOptions#height} */
height: number;
/** {@link RectOptions#cornerRadius} */
cornerRadius: number;
constructor(options?: RoundedRectOptions);
copy(options?: RoundedRectOptions): RoundedRect;
copyGraph(options?: RoundedRectOptions): RoundedRect;
}
/**
* Set quarters to an integer for quarter- and semi-circles.
* The quarter circle starts in the upper-right and continues clockwise.
*/
export type QuartersValue = 1 | 2 | 3 | 4;
/** @see {@link Ellipse} */
export interface EllipseOptions extends ShapeOptions {
/** @default 1 */
readonly diameter?: number | undefined;
readonly width?: number | undefined;
readonly height?: number | undefined;
/** @default 4 */
readonly quarters?: QuartersValue | undefined;
}
/**
* An ellipse.
* @see {@link https://zzz.dog/shapes#ellipse Zdog Shapes API}
*/
export class Ellipse extends Shape {
/** @see {@link EllipseOptions#diameter} */
diameter: number;
/** @see {@link EllipseOptions#width} */
width?: number | undefined;
/** @see {@link EllipseOptions#height} */
height?: number | undefined;
/** @see {@link EllipseOptions#quarters} */
quarters: QuartersValue;
constructor(options?: EllipseOptions);
copy(options?: EllipseOptions): Ellipse;
copyGraph(options?: EllipseOptions): Ellipse;
}
/** @see {@link Polygon} */
export interface PolygonOptions extends ShapeOptions {
/** @default 0.5 */
readonly radius?: number | undefined;
/** @default 3 */
readonly sides?: number | undefined;
}
/**
* A regular polygon.
* @see {@link https://zzz.dog/shapes#polygon Zdog Shapes API}
*/
export class Polygon extends Shape {
/** @see {@link PolygonOptions#radius} */
readonly radius?: number | undefined;
/** @see {@link PolygonOptions#sides} */
readonly sides?: number | undefined;
constructor(options?: PolygonOptions);
copy(options?: PolygonOptions): Polygon;
copyGraph(options?: PolygonOptions): Polygon;
}
/** @see {@link Hemisphere} */
export interface HemisphereOptions extends EllipseOptions {
/** @default true */
readonly fill?: boolean | undefined;
}
/**
* A spherical hemisphere.
* @see {@link https://zzz.dog/shapes#hemisphere Zdog Shapes API}
*/
export class Hemisphere extends Ellipse {
constructor(options?: HemisphereOptions);
copy(options?: HemisphereOptions): Hemisphere;
copyGraph(options?: HemisphereOptions): Hemisphere;
}
/** @see {@link Cone} */
export interface ConeOptions extends EllipseOptions {
/** @default true */
readonly fill?: boolean | undefined;
/** @default 1 */
readonly length?: number | undefined;
}
/**
* A square cylinder with circular bases
* @see {@link https://zzz.dog/shapes#cone Zdog Shapes API}
*/
export class Cone extends Ellipse {
/** @see {@link ConeOptions#length} */
length: number;
constructor(options?: ConeOptions);
copy(options?: ConeOptions): Cone;
copyGraph(options?: ConeOptions): Cone;
}
/** @see {@link Cylinder} */
export interface CylinderOptions extends ShapeOptions {
/** @default 1 */
readonly diameter?: number | undefined;
/** @default 1 */
readonly length?: number | undefined;
/** @default true */
readonly fill?: boolean | undefined;
readonly frontFace?: boolean | string | undefined;
}
/**
* A square cylinder with circular bases.
* @see {@link https://zzz.dog/shapes#cylinder Zdog Shapes API}
*/
export class Cylinder extends Shape {
/** @see {@link CylinderOptions#diameter} */
diameter: number;
/** @see {@link CylinderOptions#length} */
length: number;
/** @see {@link CylinderOptions#frontFace} */
frontFace?: boolean | string | undefined;
constructor(options?: CylinderOptions);
}
/** @see {@link Box} */
export interface BoxOptions extends RectOptions {
/** @default 1 */
readonly depth?: number | undefined;
/** @default true */
readonly fill?: boolean | undefined;
/** @default true */
readonly frontFace?: boolean | string | undefined;
/** @default true */
readonly rearFace?: boolean | string | undefined;
/** @default true */
readonly leftFace?: boolean | string | undefined;
/** @default true */
readonly rightFace?: boolean | string | undefined;
/** @default true */
readonly topFace?: boolean | string | undefined;
/** @default true */
readonly bottomFace?: boolean | string | undefined;
}
/**
* A rectangular prism.
* @see {@link https://zzz.dog/shapes#cone Zdog Shapes API}
*/
export class Box extends Rect {
/** @see {@link BoxOptions#depth} */
depth: number;
/** @see {@link BoxOptions#frontFace} */
frontFace: boolean | string;
/** @see {@link BoxOptions#rearFace} */
rearFace: boolean | string;
/** @see {@link BoxOptions#leftFace} */
leftFace: boolean | string;
/** @see {@link BoxOptions#rightFace} */
rightFace: boolean | string;
/** @see {@link BoxOptions#topFace} */
topFace: boolean | string;
/** @see {@link BoxOptions#bottomFace} */
bottomFace: boolean | string;
constructor(options?: BoxOptions);
} | the_stack |
import { contracts, ContractsData } from 'french-contractions';
/*
accord des adjectifs
Actuellement implémenté via des règles et des listes d'exceptions. Les règles sont nombreuses avec plein d'exceptions.
L'implémentation faite actuellement a une bonne couverture, mais quelques impasses, et certainement quelques bugs.
On pourrait utiliser le LEFFF, qui est souvent bon, ex. :
châtain adj châtain s
châtains adj châtain p
mais il y a des erreurs :
pâlote adj pâlot fs
et des manques :
kaki
et des doublons :
sale: sal' sales
vieux: vieil vieux
fou: fol fou
beau: beau bel bô
*/
const adjInvariables = [
// ces trois adjectifs employés dans la langue courante: chic, super, sympa
'chic',
'super',
'sympa',
// Les adjectifs qualificatifs utilisant des noms de fleurs, de fruits, de pierres précieuses, etc.
// ne s'accordent ni en genre ni en nombre :
'orange',
'émeraude',
'marron',
'ébène',
'crème',
'moutarde',
'saumon',
'ocre',
'pervenche',
// https://fr.wiktionary.org/wiki/Cat%C3%A9gorie:Adjectifs_invariables_en_fran%C3%A7ais
'abricot',
'absinthe',
'acajou',
'aigue-marine',
'amande',
'amarante',
'ambre',
'améthyste',
'anthracite',
'antibruit',
'anticrise',
'antifeu',
'antihausse',
'antirejet',
'ardoise',
'argent',
'argile',
'aubergine',
'auburn',
'audio',
'aurore',
'avocat',
'azur',
'banane',
'beurre',
'bisque',
'bordeaux',
'brique',
'bronze',
'bulle',
'café',
'canari',
'capucine',
'caramel',
'carotte',
'cascher',
'cassis',
'cawcher',
'céladon',
'centum',
'cerise',
'chair',
'chamois',
'champagne',
'châtaigne',
'chocolat',
'cinabre',
'cinq',
'cinquante',
'citron',
'citrouille',
'clean',
'coquelicot',
'corail',
'crème',
'cuivre',
'de longue date',
'debout',
'dégueu',
'deux',
'dix',
'douze',
'ébène',
'émeraude',
'enfant',
'est',
'étain',
'ex-ante',
'feu',
'feuille-morte',
'filasse',
'fraise',
'framboise',
'fuchsia',
'furax',
'garance',
'grand-boutiste',
'gratis',
'grenadine',
'grenat',
'groggy',
'groseille',
'huit',
'in',
'indigo',
'indiqué',
'infolio',
'isabelle',
'jade',
'kascher',
'laser',
'lavande',
'lilas',
'maïs',
'marron',
'mastic',
'mastoc',
'melon',
'miel',
'mille',
'moutarde',
'nacarat',
'nankin',
'nature',
'neuf',
'noisette',
'nord',
'ocre',
'olive',
'onze',
'or',
'orange',
'ouest',
'out',
'outremer',
'paille',
'parme',
'pastel',
'pêche',
'perle',
'pie',
'pistache',
'pivoine',
'platine',
'ponceau',
'prune',
'puce',
'quatorze',
'quatre',
'queue-de-renard',
'queue-de-vache',
'quinze',
'raglan',
'ras-la-moule',
'ras-le-bonbon',
'ras-les-fesses',
'rosat',
'rouille',
'rubis',
'sable',
'safran',
'safre',
'sang',
'saphir',
'sarcelle',
'satem',
'saumon',
'sépia',
'sept',
'sexy',
'shocking',
'six',
'six-cents',
'soixante',
'soufre',
'souris',
'sud',
'super',
'tabac',
'tanacross',
'taupe',
'thé',
'tilleul',
'tomate',
'topaze',
'treize',
'trendy',
'trente',
'turquoise',
'vanille',
'vermillon',
'vidéo',
'zéro',
// les adjectifs de couleur formés par emprunt lexical d'un mot venant d'une langue autre que le français
// sont invariables
'abricot',
'absinthe',
'acajou',
'aigue-marine',
'albâtre',
'amadou',
'amande',
'amarante',
'ambre',
'améthyste',
'andrinople',
'anthracite',
'ardoise',
'argent',
'argile',
'aubergine',
'auburn',
'aurore',
'avocat',
'azur',
'basane',
'banane',
'bistre',
'bitume',
'bourgogne',
'brique',
'bronze',
'bulle',
'cacao',
'cachou',
'café',
'café au lait',
'canari',
'cannelle',
'capucine',
'caramel',
'carmélite',
'carmin',
'carotte',
'céladon',
'cerise',
'chair',
'chamois',
'champagne',
'châtaigne',
'chaudron',
'chocolat',
'citron',
'cognac',
'coquelicot',
'corail',
'corbeau',
'crème',
'crevette',
'cuivre',
'cyclamen',
'ébène',
'émeraude',
'étain',
'feuille morte',
'filasse',
'fraise',
'framboise',
'fuchsia',
'garance',
'grenat',
'groseille',
'havane',
'indigo',
'isabelle',
'ivoire',
'jade',
'jonquille',
'kaki',
'lavande',
'lilas',
'magenta',
'maïs',
'marine',
'marengo',
'marron',
'mastic',
'melon',
'miel',
'moutarde',
'muscade',
'nacarat',
'nacre',
'noisette',
'noyer',
'ocre',
'olive',
'or',
'orange',
'paille',
'parme',
'pastel',
'pastèque',
'pêche',
'perle',
'pervenche',
'pie',
'pistache',
'pivoine',
'ponceau',
'porto',
'prune',
'puce',
'réséda',
'rouille',
'rubis',
'sable',
'safran',
'saphir',
'saumon',
'sépia',
'serin',
'soufre',
'tabac',
'tango',
'taupe',
'thé',
'tilleul',
'tomate',
'topaze',
'turquoise',
'vermillon',
'violette',
// des pâtisseries maison
'maison',
];
function getAdjFeminine(adjective: string): string {
if (adjInvariables.indexOf(adjective) != -1) return adjective;
// Si la forme basique (masc. sg.) de l’adjectif a déjà une terminaison en e, la forme reste la
// même au masculin et au féminin (on n’ajoute pas de nouvelle terminaison).
// facile, sobre
if (adjective.endsWith('e')) {
return adjective;
}
// Les adjectifs qui se terminent en -ique, -oire, -ile s'écrivent pareil au masculin ou au feminin
/*
if (adjective.endsWith('ique') || adjective.endsWith('oire') || adjective.endsWith('ile')) {
return adjective;
}
*/
const exceptions = {
// s'accorde uniquement au pluriel
châtain: 'châtain',
// Les adjectifs masculins qui changent carrément leurs terminaisons au féminin :
bénin: 'bénigne',
blanc: 'blanche',
doux: 'douce',
faux: 'fausse',
frais: 'fraîche',
grec: 'grecque',
hâtif: 'hâtive',
malin: 'maligne',
précieux: 'précieuse',
turc: 'turque',
// Les sept adjectifs suivants ne suivent pas la règle générale puisque le s est doublé :
bas: 'basse',
épais: 'épaisse',
exprès: 'expresse',
gras: 'grasse',
gros: 'grosse',
las: 'lasse',
métis: 'métisse',
// encore des exceptions
tiers: 'tierce',
//'frais': 'fraîche',
dissous: 'dissoute',
absous: 'absoute',
// Pour les adjectifs en -an, il n'y a pas de règle générale :
// A COMPLETER
paysan: 'paysanne',
persan: 'persanne',
// Pour les autres adjectifs terminés en -l, il n'y a pas de règle générale :
// A COMPLETER
nul: 'nulle',
seul: 'seule',
gentil: 'gentille',
// exceptions qui se terminent en -ique, -oire, -ile
civil: 'civile',
noir: 'noire',
public: 'publique',
puéril: 'puérile',
subtil: 'subtile',
vil: 'vile',
viril: 'virile',
volatil: 'volatile',
// Les adjectifs qui se terminent par -et au masculin, se terminent en -tte au féminin.
// Cependant, quelques-uns font exception
désuet: 'désuète',
replet: 'replète',
secret: 'secrète',
concret: 'concrète',
complet: 'complète',
incomplet: 'incomplète',
discret: 'discrète',
indiscret: 'indiscrète',
quiet: 'quiète',
inquiet: 'inquiète',
// Exceptions doublement du n
lapon: 'laponne',
nippon: 'nippone', // - Le doublement du n de nippon est facultatif. <= no comment
// Les adjectifs fou, foufou et mou forment leur féminin en -olle.
fou: 'folle',
mou: 'molle',
// Les formes féminines des adjectifs chou et chouchou sont choute et chouchoute.
chou: 'choute',
chouchou: 'chouchou',
// Féminin en -otte
jeunot: 'jeunotte',
pâlot: 'pâlotte',
vieillot: 'vieillotte',
sot: 'sotte',
// Féminin en -ote
bigot: 'bigote',
dévot: 'dévote',
fiérot: 'fiérote',
idiot: 'idiote',
loupiot: 'loupiote',
manchot: 'manchote',
petiot: 'petiote',
poivrot: 'poivrote',
// Exception : chérot est invariable.
chérot: 'chérot',
enchanteur: 'enchanteresse',
enchanteresse: 'désenchanteresse',
vengeur: 'vengeresse',
// Certains adjectifs en -teur font leur féminin en -trice :
// TODO COMPLETER http://la-conjugaison.nouvelobs.com/regles/grammaire/les-adjectifs-en-teur-206.php
protecteur: 'protectrice',
dévastateur: 'dévastatrice',
libérateur: 'libératrice',
créateur: 'créatrice',
//'faux': 'fausse',
roux: 'rousse',
//'doux': 'douce',
//'grec': 'grecque',
sec: 'sèche',
vieux: 'vieille',
};
if (exceptions[adjective]) {
return exceptions[adjective];
}
// Certains adjectifs finissant en -eur font leur féminin en -eure :
if (
[
'antérieur',
'extérieur',
'inférieur',
'intérieur',
'majeur',
'meilleur',
'mineur',
'postérieur',
'supérieur',
'ultérieur',
].indexOf(adjective) != -1
) {
return adjective.replace(/eur$/, 'eure');
}
const terminaisons = {
// Les adjectifs qualificatifs finissant par -eau forment leur féminin en -elle.
// nouveau nouvelle / beau belle
eau: 'elle',
// Les adjectifs finissant en -ier ou -iet prennent un accent grave sur le e et un e final.
// printanier printanière / inquiet inquiète
ier: 'ière',
iet: 'iète',
// Lorsque l’adjectif se termine en –gu, le e du féminin prend un tréma :
// ambigu ambiguë
gu: 'guë',
// Les adjectifs finissant par -ul, -el, -eil ou -iel doublent leur -l et prennent un e final.
// vermeil / vermeille
// habituel / habituelle, traditionnel
// nul nulle, officiel officielle
ul: 'ulle',
el: 'elle',
eil: 'eille',
iel: 'ielle',
// long longue, oblong oblongue
g: 'gue',
// finissant par -ien, -en ou -on doublent leur n et prennent un e final
// californien californienne / vendéen vendéenne / bon bonne
ien: 'ienne',
en: 'enne',
on: 'onne',
// Les adjectifs qui se terminent en -al au masculin, se terminent en -ale au féminin :
// national / nationale
al: 'ale',
// Pour le féminin des adjectifs en -in, -un, il n'y a pas de doublement du n :
// - fin, fine ; brun, brune ; plein, pleine.
in: 'ine',
un: 'une',
// Les adjectifs qui se terminent par -eux au masculin, se terminent en -se au féminin.
// peureux -> peureuse, luxueux -> luxueuse
eux: 'euse',
// Les adjectifs qui se terminent par -er au masculin, se terminent en -ère au féminin.
// premier première
er: 'ère',
// Les adjectifs qui se terminent par -et au masculin, se terminent en -tte au féminin.
// maigrelet / maigrelette
et: 'ette',
// Les adjectifs se terminant en -teur font leur féminin en -teuse quand le participe présent du verbe dont ils sont dérivés se termine par -tant.
teur: 'teuse',
// La plupart des adjectifs qualificatifs finissant en -eur font leur féminin en -euse.
// rêveur rêveuse / songeur songeuse
eur: 'euse',
// finissant par la lettre x se terminent généralement par -se au féminin.
// jaloux jalouse
x: 'se',
// blanc blanche, franc franche (NB : Le féminin de franc est franque quand il signifie "du peuple franc" et franche quand il signifie "sincère".)
c: 'che',
// sportif sportive, neuf neuve
f: 've',
};
for (const term in terminaisons) {
if (adjective.endsWith(term)) {
return adjective.replace(new RegExp(term + '$'), terminaisons[term]);
}
}
// En général on ajoute un e à la forme écrite du masculin pour former le féminin des adjectifs.
return adjective + 'e';
}
function getAdjPlural(adjective: string): string {
if (adjInvariables.indexOf(adjective) > -1) {
return adjective;
}
const exceptions = {
// Exception : l'adjectif bleu prend un s au pluriel
bleu: 'bleus',
};
if (exceptions[adjective]) {
return exceptions[adjective];
}
// Exceptions : bancal, fatal, final, natal, naval et banal prennent un -s au pluriel
if (['bancal', 'fatal', 'final', 'natal', 'naval', 'banal'].indexOf(adjective) > -1) {
return adjective + 's';
}
// se terminant par s ou x sont invariables en nombre
// heureux, obtus
if (adjective.endsWith('x') || adjective.endsWith('s')) {
return adjective;
}
const terminaisons = {
// royal royaux
al: 'aux',
// beau beaux
eau: 'eaux',
// hébreu hébreux
eu: 'eux',
};
for (const term in terminaisons) {
if (adjective.endsWith(term)) {
return adjective.replace(new RegExp(term + '$'), terminaisons[term]);
}
}
return adjective + 's';
}
const adjChangeants = {
vieux: 'vieil',
beau: 'bel',
nouveau: 'nouvel',
mou: 'mol',
fou: 'fol',
};
export function getChangeant(agreedAdj: string): string {
return adjChangeants[agreedAdj]; // most often null
}
function getBeforeNoun(agreedAdj: string, noun: string, contractsData: ContractsData): string {
if (adjChangeants[agreedAdj]) {
if (contracts(noun, contractsData)) {
// console.log(`${agreedAdj} followed by ${noun}, we change it`);
return adjChangeants[agreedAdj];
}
}
return agreedAdj;
}
export type GendersMF = 'M' | 'F';
export type Numbers = 'S' | 'P';
export function agree(
adjective: string,
gender: GendersMF,
number: Numbers,
noun: string,
isBeforeNoun: boolean,
contractsData: ContractsData,
): string {
if (gender != 'M' && gender != 'F') {
const err = new Error();
err.name = 'TypeError';
err.message = `gender must be M or F`;
throw err;
}
if (number != 'S' && number != 'P') {
const err = new Error();
err.name = 'TypeError';
err.message = `number must be S or P`;
throw err;
}
if (isBeforeNoun && !noun) {
const err = new Error();
err.name = 'TypeError';
err.message = `when isBeforeNoun is set, you must provide the noun`;
throw err;
}
let agreedAdj: string = adjective;
if (gender === 'F') {
agreedAdj = getAdjFeminine(agreedAdj);
}
if (number === 'P') {
agreedAdj = getAdjPlural(agreedAdj);
}
if (isBeforeNoun && number === 'S') {
agreedAdj = getBeforeNoun(agreedAdj, noun, contractsData);
}
return agreedAdj;
} | the_stack |
import {
ChangeRangeInterface,
EngineInterface,
RangeInterface,
} from '../types';
import { $ } from '../node';
import { CARD_ELEMENT_KEY, CARD_KEY, EDITABLE_SELECTOR } from '../constants';
import Range from '../range';
import { isFirefox } from '../utils';
export type ChangeRangeOptions = {
onSelect?: (range: RangeInterface) => void;
};
class ChangeRange implements ChangeRangeInterface {
engine: EngineInterface;
#lastBlurRange?: RangeInterface;
#otpions: ChangeRangeOptions;
constructor(engine: EngineInterface, options: ChangeRangeOptions = {}) {
this.engine = engine;
this.#otpions = options;
}
setLastBlurRange(range?: RangeInterface) {
if (range?.commonAncestorNode.inEditor()) this.#lastBlurRange = range;
else this.#lastBlurRange = undefined;
}
/**
* 获取安全可控的光标对象
* @param range 默认当前光标
*/
toTrusty(range: RangeInterface = this.get()) {
// 如果不在编辑器内,聚焦到编辑器
const { commonAncestorNode } = range;
if (
!commonAncestorNode.isEditable() &&
!commonAncestorNode.inEditor()
) {
range
.select(this.engine.container, true)
.shrinkToElementNode()
.collapse(false);
}
//卡片
let rangeClone = range.cloneRange();
rangeClone.collapse(true);
this.setCardRang(rangeClone);
if (
!range.startNode.equal(rangeClone.startNode) ||
range.startOffset !== rangeClone.startOffset
)
range.setStart(rangeClone.startContainer, rangeClone.startOffset);
rangeClone = range.cloneRange();
rangeClone.collapse(false);
this.setCardRang(rangeClone);
if (
!range.endNode.equal(rangeClone.endNode) ||
range.endOffset !== rangeClone.endOffset
)
range.setEnd(rangeClone.endContainer, rangeClone.endOffset);
if (range.collapsed) {
rangeClone = range.cloneRange();
rangeClone.enlargeFromTextNode();
const startNode = $(rangeClone.startContainer);
const startOffset = rangeClone.startOffset;
if (this.engine.node.isInline(startNode) && startOffset === 0) {
range.setStartBefore(startNode[0]);
}
if (
this.engine.node.isInline(startNode) &&
startOffset === startNode[0].childNodes.length
) {
range.setStartAfter(startNode[0]);
}
range.collapse(true);
}
return range;
}
private setCardRang(range: RangeInterface) {
const { startNode, startOffset } = range;
const { card } = this.engine;
const component = card.find(startNode);
if (component) {
const cardCenter = component.getCenter().get();
if (
cardCenter &&
(!startNode.isElement() ||
startNode[0].parentNode !== component.root[0] ||
startNode.attributes(CARD_ELEMENT_KEY))
) {
const comparePoint = () => {
const doc_rang = Range.create(this.engine);
doc_rang.select(cardCenter, true);
return doc_rang.comparePoint(startNode, startOffset) < 0;
};
if ('inline' === component.type) {
range.select(component.root);
range.collapse(comparePoint());
return;
}
if (comparePoint()) {
card.focusPrevBlock(component, range, true);
} else {
card.focusNextBlock(component, range, true);
}
}
}
}
get() {
const { container } = this.engine;
const { window } = container;
let range = Range.from(this.engine, window!, false);
if (!range) {
range = Range.create(this.engine, window!.document)
.select(container, true)
.shrinkToElementNode()
.collapse(false);
}
return range;
}
select(range: RangeInterface, triggerSelect: boolean = true) {
const { container, inline, node, change } = this.engine;
const { window } = container;
const selection = window?.getSelection();
if (change.isComposing()) return;
//折叠状态
if (range.collapsed) {
const { startNode, startOffset } = range;
//如果节点下只要一个br标签,并且是<p><br /><cursor /></p>,那么选择让光标选择在 <p><cursor /><br /></p>
if (
((startNode.isElement() &&
1 === startOffset &&
1 === startNode.get<Node>()?.childNodes.length) ||
(2 === startOffset &&
2 === startNode.get<Node>()?.childNodes.length &&
startNode.first()?.isCard())) &&
'br' === startNode.last()?.name
) {
range.setStart(startNode, startOffset - 1);
range.collapse(true);
}
// 卡片左右侧光标零宽字符节点
if (startNode.isText()) {
const parent = startNode.parent();
if (
parent?.attributes(CARD_ELEMENT_KEY) === 'right' &&
startOffset === 0
) {
range.setStart(startNode, 1);
range.collapse(true);
} else if (
parent?.attributes(CARD_ELEMENT_KEY) === 'left' &&
startOffset === 1
) {
range.setStart(startNode, 0);
range.collapse(true);
}
}
}
//修复inline光标
let { startNode, endNode, startOffset, endOffset } = range
.cloneRange()
.shrinkToTextNode();
const prev = startNode.prev();
const next = endNode.next();
//光标上一个节点是inline节点,让其选择在inline节点后的零宽字符后面
if (
prev &&
!prev.isCard() &&
!node.isVoid(prev) &&
node.isInline(prev)
) {
const text = startNode.text();
//前面是inline节点,后面是零宽字符
if (/^\u200B/g.test(text) && startOffset === 0) {
range.setStart(endNode, startOffset + 1);
if (range.collapsed) range.collapse(true);
}
}
//光标下一个节点是inline节点,让其选择在inline节点前面的零宽字符前面
if (
next &&
!next.isCard() &&
!node.isVoid(next) &&
node.isInline(next)
) {
const text = endNode.text();
if (/\u200B$/g.test(text) && endOffset === text.length) {
range.setEnd(endNode, endOffset - 1);
if (range.collapsed) range.collapse(false);
}
}
//光标内侧位置
const inlineNode = inline.closest(startNode);
if (
!inlineNode.isCard() &&
node.isInline(inlineNode) &&
!node.isVoid(inlineNode)
) {
//左侧
if (
startNode.isText() &&
!startNode.prev() &&
startNode.parent()?.equal(inlineNode) &&
startOffset === 0
) {
const text = startNode.text();
if (/^\u200B/g.test(text)) {
range.setStart(startNode, startOffset + 1);
if (range.collapsed) range.collapse(true);
}
}
//右侧
if (
endNode.isText() &&
!endNode.next() &&
endNode.parent()?.equal(inlineNode)
) {
const text = endNode.text();
if (endOffset === text.length && /\u200B$/g.test(text)) {
range.setEnd(endNode, endOffset - 1);
if (range.collapsed) range.collapse(false);
}
}
}
startNode = range.startNode;
endNode = range.endNode;
if (startNode.isText() || endNode.isText()) {
const cloneRange = range.cloneRange().enlargeFromTextNode();
startNode = cloneRange.startNode;
endNode = cloneRange.endNode;
}
const startChildNodes = startNode.children();
// 自定义列表节点选中卡片前面就让光标到卡片后面去
if (node.isCustomize(startNode) && startOffset === 0) {
range.setStart(startNode, 1);
}
if (node.isCustomize(endNode) && endOffset === 0) {
range.setEnd(endNode, 1);
}
const otStopped = this.engine.ot.isStopped();
// 空节点添加br
if (startNode.name === 'p' && !otStopped) {
if (startChildNodes.length === 0) startNode.append('<br />');
else if (
!isFirefox &&
startChildNodes.length > 1 &&
startChildNodes[startChildNodes.length - 2].nodeName !== 'BR' &&
startChildNodes[startChildNodes.length - 1].nodeName === 'BR'
) {
const br = startNode.last();
br?.remove();
}
}
if (
!range.collapsed &&
!otStopped &&
endNode.name === 'p' &&
endNode.get<Node>()?.childNodes.length === 0
) {
endNode.append('<br />');
}
const startChildren = startNode.children();
// 列表节点没有子节点
if (
node.isList(startNode) &&
!otStopped &&
(startChildren.length === 0 || startChildren[0].nodeName === 'BR')
) {
const newNode = $('<p><br /></p>');
this.engine.nodeId.create(newNode);
startNode.before(newNode);
startNode.remove();
startNode = newNode;
}
// 空列表添加br
if (startNode.name === 'li' && !otStopped) {
if (node.isCustomize(startNode) && !startNode.first()?.isCard()) {
const cardItem = startNode
.parent()
?.children()
.toArray()
.find((child) => child.first()?.isCard());
const cardKey = cardItem?.first()?.attributes(CARD_KEY);
if (cardKey) {
this.engine.list.addCardToCustomize(startNode, cardKey);
} else {
this.engine.list.unwrapCustomize(startNode);
}
}
if (startChildNodes.length === 0) {
startNode.append('<br />');
} else if (
!node.isCustomize(startNode) &&
startChildNodes.length > 1 &&
startChildNodes[startChildNodes.length - 2].nodeName !== 'BR' &&
startChildNodes[startChildNodes.length - 1].nodeName === 'BR'
) {
startNode.last()?.remove();
} else if (
node.isCustomize(startNode) &&
startChildNodes.length === 1
) {
startNode.append('<br />');
} else if (
node.isCustomize(startNode) &&
startChildNodes.length > 2 &&
startChildNodes[startChildNodes.length - 2].nodeName !== 'BR' &&
startChildNodes[startChildNodes.length - 1].nodeName === 'BR'
) {
startNode.last()?.remove();
}
}
if (!range.collapsed && endNode.name === 'li' && !otStopped) {
const endChildNodes = endNode.children();
if (endChildNodes.length === 0) {
endNode.append('<br />');
} else if (
!node.isCustomize(endNode) &&
endChildNodes.length > 1 &&
endChildNodes[endChildNodes.length - 2].nodeName !== 'BR' &&
endChildNodes[endChildNodes.length - 1].nodeName === 'BR'
) {
startNode.last()?.remove();
} else if (
node.isCustomize(endNode) &&
endChildNodes.length === 1
) {
endNode.append('<br />');
} else if (
node.isCustomize(endNode) &&
endChildNodes.length > 2 &&
endChildNodes[endChildNodes.length - 2].nodeName !== 'BR' &&
endChildNodes[endChildNodes.length - 1].nodeName === 'BR'
) {
startNode.last()?.remove();
}
}
if (
startNode.isEditable() &&
!otStopped &&
startNode.get<Node>()?.childNodes.length === 0 &&
!this.engine.ot.isStopped
) {
startNode.html('<p><br /></p>');
}
//在非折叠,或者当前range对象和selection中的对象不一致的时候重新设置range
if (
selection &&
(range.collapsed ||
(selection.rangeCount > 0 &&
!range.equal(selection.getRangeAt(0)))) &&
range.startNode.get<Node>()?.isConnected
) {
selection.removeAllRanges();
selection.addRange(range.toRange());
}
const { onSelect } = this.#otpions;
if (onSelect && triggerSelect) onSelect(range);
}
/**
* 聚焦编辑器
* @param toStart true:开始位置,false:结束位置,默认为之前操作位置
*/
focus(toStart?: boolean) {
const range = this.#lastBlurRange || this.get();
if (toStart !== undefined) {
range
.select(this.engine.container, true)
.shrinkToElementNode()
.collapse(toStart);
}
this.select(range);
const editableElement =
range.commonAncestorNode.closest(EDITABLE_SELECTOR);
editableElement?.get<HTMLElement>()?.focus();
if (
editableElement.length > 0 &&
!this.engine.container.equal(editableElement)
) {
const mouseEvent = new MouseEvent('mousedown');
this.engine.container.get<HTMLElement>()?.dispatchEvent(mouseEvent);
setTimeout(() => {
const mouseEvent = new MouseEvent('mouseup');
this.engine.container
.get<HTMLElement>()
?.dispatchEvent(mouseEvent);
}, 0);
}
}
blur() {
const range = this.get();
range.commonAncestorNode
.closest(EDITABLE_SELECTOR)
.get<HTMLElement>()
?.blur();
this.engine.container.get<HTMLElement>()?.blur();
this.engine.trigger('blur');
}
}
export default ChangeRange; | the_stack |
import { OrbitGtBlobProps, RealityDataFormat, RealityDataProvider, RealityDataSourceKey } from "@itwin/core-common";
import { expect } from "chai";
import { CesiumIonAssetProvider, getCesiumAssetUrl } from "../core-frontend";
import { RealityDataSource } from "../RealityDataSource";
describe("RealityDataSource", () => {
it("should handle creation from empty url", () => {
const tilesetUrl = "";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.TilesetUrl);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal(tilesetUrl);
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("TilesetUrl:ThreeDTile::undefined");
});
it("should handle creation from CesiumIonAsset url", () => {
const tilesetUrl = "$CesiumIonAsset=";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.CesiumIonAsset);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
// dummy id for CesiumIonAsset, we want to hide the url and key
expect(rdSourceKey.id).to.be.equal(CesiumIonAssetProvider.osmBuildingId);
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("CesiumIonAsset:ThreeDTile:OSMBuildings:undefined");
});
it("should handle creation from any CesiumIonAsset url (not OSM Building)", () => {
const rdSourceKey = RealityDataSource.createCesiumIonAssetKey(75343,"ThisIsADummyCesiumIonKey");
expect(rdSourceKey.provider).to.equal(RealityDataProvider.CesiumIonAsset);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
const tilesetUrl = getCesiumAssetUrl(75343,"ThisIsADummyCesiumIonKey");
expect(rdSourceKey.id).to.be.equal(tilesetUrl);
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal(`CesiumIonAsset:ThreeDTile:${tilesetUrl}:undefined`);
});
it("should handle creation from Context Share url", () => {
const tilesetUrl = "https://connect-realitydataservices.bentley.com/v2.9/Repositories/S3MXECPlugin--5b4ebd22-d94b-456b-8bd8-d59563de9acd/S3MX/RealityData/994fc408-401f-4ee1-91f0-3d7bfba50136";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal("994fc408-401f-4ee1-91f0-3d7bfba50136");
expect(rdSourceKey.iTwinId).to.equal("5b4ebd22-d94b-456b-8bd8-d59563de9acd");
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:ThreeDTile:994fc408-401f-4ee1-91f0-3d7bfba50136:5b4ebd22-d94b-456b-8bd8-d59563de9acd");
});
it("should handle creation from Context Share url with server context", () => {
const tilesetUrl = "https://connect-realitydataservices.bentley.com/v2.9/Repositories/S3MXECPlugin--server/S3MX/RealityData/994fc408-401f-4ee1-91f0-3d7bfba50136";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal("994fc408-401f-4ee1-91f0-3d7bfba50136");
expect(rdSourceKey.iTwinId).to.equal("server");
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:ThreeDTile:994fc408-401f-4ee1-91f0-3d7bfba50136:server");
});
it("should handle creation from Context Share url with empty guid context", () => {
const tilesetUrl = "https://connect-realitydataservices.bentley.com/v2.9/Repositories/S3MXECPlugin--00000000-0000-0000-0000-000000000000/S3MX/RealityData/994fc408-401f-4ee1-91f0-3d7bfba50136";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal("994fc408-401f-4ee1-91f0-3d7bfba50136");
expect(rdSourceKey.iTwinId).to.equal("00000000-0000-0000-0000-000000000000");
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:ThreeDTile:994fc408-401f-4ee1-91f0-3d7bfba50136:00000000-0000-0000-0000-000000000000");
});
it("should handle creation from Context Share url using apim in QA (qa-api.bentley.com)", () => {
const tilesetUrl = "https://qa-api.bentley.com/realitydata/c9fddf2c-e519-468b-b6fa-6d0e39f198a7?projectId=a57f6b1c-747d-4253-b0ce-9900c4dd7c1c";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal("c9fddf2c-e519-468b-b6fa-6d0e39f198a7");
expect(rdSourceKey.iTwinId).to.equal("a57f6b1c-747d-4253-b0ce-9900c4dd7c1c");
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:ThreeDTile:c9fddf2c-e519-468b-b6fa-6d0e39f198a7:a57f6b1c-747d-4253-b0ce-9900c4dd7c1c");
});
it("should handle creation from Context Share url using apim in PROD (api.bentley.com)", () => {
const tilesetUrl = "https://api.bentley.com/realitydata/c9fddf2c-e519-468b-b6fa-6d0e39f198a7?projectId=a57f6b1c-747d-4253-b0ce-9900c4dd7c1c";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal("c9fddf2c-e519-468b-b6fa-6d0e39f198a7");
expect(rdSourceKey.iTwinId).to.equal("a57f6b1c-747d-4253-b0ce-9900c4dd7c1c");
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:ThreeDTile:c9fddf2c-e519-468b-b6fa-6d0e39f198a7:a57f6b1c-747d-4253-b0ce-9900c4dd7c1c");
});
it("should handle creation from url to an .opc file on an azure blob", () => {
const tilesetUrl = "https://realityblobqaeussa01.blob.core.windows.net/fe8d32a5-f6ab-4157-b3ec-a9b53db923e3/Tuxford.opc?sv=2020-08-04&se=2021-08-26T05%3A11%3A31Z&sr=c&sp=rl&sig=J9wGT1f3nyKePPj%2FI%2BJdx086GylEfM0P4ZXBQL%2FaRD4%3D";
const rdSourceKey = RealityDataSource.createKeyFromBlobUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.OPC);
expect(rdSourceKey.id).to.be.equal("fe8d32a5-f6ab-4157-b3ec-a9b53db923e3");
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:OPC:fe8d32a5-f6ab-4157-b3ec-a9b53db923e3:undefined");
});
it("should handle creation from url to any http server", () => {
const tilesetUrl = "https://customserver/myFile.json";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.TilesetUrl);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal(tilesetUrl);
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("TilesetUrl:ThreeDTile:https://customserver/myFile.json:undefined");
});
it("should handle creation from url to any local file", () => {
const tilesetUrl = "c:\\customserver\\myFile.json";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.TilesetUrl);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal(tilesetUrl);
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("TilesetUrl:ThreeDTile:c:\\customserver\\myFile.json:undefined");
});
it("should handle creation from url to an OPC local file", () => {
// we detect format based on extension-> .opc -> OPC format, otherwise 3dTile
const tilesetUrl = "c:\\customserver\\myFile.opc";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.TilesetUrl);
expect(rdSourceKey.format).to.equal(RealityDataFormat.OPC);
expect(rdSourceKey.id).to.be.equal(tilesetUrl);
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("TilesetUrl:OPC:c:\\customserver\\myFile.opc:undefined");
});
it("should handle invalid url and fallback to simply returns it in id as tileset url", () => {
const tilesetUrl = "Anything that is not a valid url";
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.TilesetUrl);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal(tilesetUrl);
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("TilesetUrl:ThreeDTile:Anything that is not a valid url:undefined");
});
it("should handle creation from Context Share url with provider override", () => {
const tilesetUrl = "https://connect-realitydataservices.bentley.com/v2.9/Repositories/S3MXECPlugin--5b4ebd22-d94b-456b-8bd8-d59563de9acd/S3MX/RealityData/994fc408-401f-4ee1-91f0-3d7bfba50136";
const forceProvider = RealityDataProvider.TilesetUrl;
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl, forceProvider);
expect(rdSourceKey.provider).to.equal(forceProvider);
expect(rdSourceKey.format).to.equal(RealityDataFormat.ThreeDTile);
expect(rdSourceKey.id).to.be.equal("994fc408-401f-4ee1-91f0-3d7bfba50136");
expect(rdSourceKey.iTwinId).to.equal("5b4ebd22-d94b-456b-8bd8-d59563de9acd");
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("TilesetUrl:ThreeDTile:994fc408-401f-4ee1-91f0-3d7bfba50136:5b4ebd22-d94b-456b-8bd8-d59563de9acd");
});
it("should handle creation from Context Share url with format override", () => {
const tilesetUrl = "https://connect-realitydataservices.bentley.com/v2.9/Repositories/S3MXECPlugin--5b4ebd22-d94b-456b-8bd8-d59563de9acd/S3MX/RealityData/994fc408-401f-4ee1-91f0-3d7bfba50136";
const forceFormat = RealityDataFormat.OPC;
const rdSourceKey = RealityDataSource.createKeyFromUrl(tilesetUrl, undefined, forceFormat);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(forceFormat);
expect(rdSourceKey.id).to.be.equal("994fc408-401f-4ee1-91f0-3d7bfba50136");
expect(rdSourceKey.iTwinId).to.equal("5b4ebd22-d94b-456b-8bd8-d59563de9acd");
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:OPC:994fc408-401f-4ee1-91f0-3d7bfba50136:5b4ebd22-d94b-456b-8bd8-d59563de9acd");
});
it("should handle creation from a blob url to an .opc file on an azure blob", () => {
const blobUrl = "https://realityblobqaeussa01.blob.core.windows.net/fe8d32a5-f6ab-4157-b3ec-a9b53db923e3/Tuxford.opc?sv=2020-08-04&se=2021-08-26T05%3A11%3A31Z&sr=c&sp=rl&sig=J9wGT1f3nyKePPj%2FI%2BJdx086GylEfM0P4ZXBQL%2FaRD4%3D";
const rdSourceKey = RealityDataSource.createKeyFromBlobUrl(blobUrl);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.OPC);
expect(rdSourceKey.id).to.be.equal("fe8d32a5-f6ab-4157-b3ec-a9b53db923e3");
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:OPC:fe8d32a5-f6ab-4157-b3ec-a9b53db923e3:undefined");
});
it("should handle creation from blob url with provider override", () => {
const blobUrl = "https://realityblobqaeussa01.blob.core.windows.net/fe8d32a5-f6ab-4157-b3ec-a9b53db923e3/Tuxford.opc?sv=2020-08-04&se=2021-08-26T05%3A11%3A31Z&sr=c&sp=rl&sig=J9wGT1f3nyKePPj%2FI%2BJdx086GylEfM0P4ZXBQL%2FaRD4%3D";
const forceProvider = RealityDataProvider.TilesetUrl;
const rdSourceKey = RealityDataSource.createKeyFromBlobUrl(blobUrl, forceProvider);
expect(rdSourceKey.provider).to.equal(forceProvider);
expect(rdSourceKey.format).to.equal(RealityDataFormat.OPC);
expect(rdSourceKey.id).to.be.equal("fe8d32a5-f6ab-4157-b3ec-a9b53db923e3");
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("TilesetUrl:OPC:fe8d32a5-f6ab-4157-b3ec-a9b53db923e3:undefined");
});
it("should handle creation from blob url with format override", () => {
const blobUrl = "https://realityblobqaeussa01.blob.core.windows.net/fe8d32a5-f6ab-4157-b3ec-a9b53db923e3/Tuxford.opc?sv=2020-08-04&se=2021-08-26T05%3A11%3A31Z&sr=c&sp=rl&sig=J9wGT1f3nyKePPj%2FI%2BJdx086GylEfM0P4ZXBQL%2FaRD4%3D";
const forceFormat = RealityDataFormat.ThreeDTile;
const rdSourceKey = RealityDataSource.createKeyFromBlobUrl(blobUrl, undefined, forceFormat);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(forceFormat);
expect(rdSourceKey.id).to.be.equal("fe8d32a5-f6ab-4157-b3ec-a9b53db923e3");
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:ThreeDTile:fe8d32a5-f6ab-4157-b3ec-a9b53db923e3:undefined");
});
it("should handle creation from orbitGtBlobProps", () => {
const orbitGtBlob: OrbitGtBlobProps = {
accountName: "ocpalphaeudata001",
containerName: "a5932aa8-2fde-470d-b5ab-637412ec4e49",
blobFileName: "/datasources/0b2ad731-ec01-4b8b-8f0f-c99a593f1ff3/Seinajoki_Trees_utm.opc",
sasToken: "sig=EaHCCCSX6bWw%2FOHgad%2Fn3VCgUs2gPbDn%2BE2p5osMYIg%3D&se=2022-01-11T12%3A01%3A20Z&sv=2019-02-02&sp=r&sr=b",
};
const rdSourceKey = RealityDataSource.createKeyFromOrbitGtBlobProps(orbitGtBlob);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.OrbitGtBlob);
expect(rdSourceKey.format).to.equal(RealityDataFormat.OPC);
expect(rdSourceKey.id).to.be.equal("ocpalphaeudata001:a5932aa8-2fde-470d-b5ab-637412ec4e49:/datasources/0b2ad731-ec01-4b8b-8f0f-c99a593f1ff3/Seinajoki_Trees_utm.opc:?sig=EaHCCCSX6bWw%2FOHgad%2Fn3VCgUs2gPbDn%2BE2p5osMYIg%3D&se=2022-01-11T12%3A01%3A20Z&sv=2019-02-02&sp=r&sr=b");
expect(rdSourceKey.iTwinId).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("OrbitGtBlob:OPC:ocpalphaeudata001:a5932aa8-2fde-470d-b5ab-637412ec4e49:/datasources/0b2ad731-ec01-4b8b-8f0f-c99a593f1ff3/Seinajoki_Trees_utm.opc:?sig=EaHCCCSX6bWw%2FOHgad%2Fn3VCgUs2gPbDn%2BE2p5osMYIg%3D&se=2022-01-11T12%3A01%3A20Z&sv=2019-02-02&sp=r&sr=b:undefined");
const orbitGtBlobFromKey = RealityDataSource.createOrbitGtBlobPropsFromKey(rdSourceKey);
expect(orbitGtBlobFromKey).to.not.be.undefined;
if (orbitGtBlobFromKey !== undefined) {
expect(orbitGtBlob.accountName).to.equal(orbitGtBlobFromKey.accountName);
expect(orbitGtBlob.containerName).to.equal(orbitGtBlobFromKey.containerName);
expect(orbitGtBlob.blobFileName).to.equal(orbitGtBlobFromKey.blobFileName);
expect(orbitGtBlob.sasToken).to.equal(orbitGtBlobFromKey.sasToken);
}
});
it("should handle creation from orbitGtBlobProps when blobFilename is http or https", () => {
const orbitGtBlob: OrbitGtBlobProps = {
accountName: "",
containerName: "fe8d32a5-f6ab-4157-b3ec-a9b53db923e3",
blobFileName: "https://realityblobqaeussa01.blob.core.windows.net/fe8d32a5-f6ab-4157-b3ec-a9b53db923e3/Tuxford.opc?sv=2020-08-04&se=2021-08-26T05%3A11%3A31Z&sr=c&sp=rl&sig=J9wGT1f3nyKePPj%2FI%2BJdx086GylEfM0P4ZXBQL%2FaRD4%3D",
sasToken: "",
};
const rdSourceKey = RealityDataSource.createKeyFromOrbitGtBlobProps(orbitGtBlob);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.OPC);
expect(rdSourceKey.id).to.be.equal("fe8d32a5-f6ab-4157-b3ec-a9b53db923e3");
expect(rdSourceKey.iTwinId).to.be.undefined;
const orbitGtBlobFromKey = RealityDataSource.createOrbitGtBlobPropsFromKey(rdSourceKey);
expect(orbitGtBlobFromKey).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:OPC:fe8d32a5-f6ab-4157-b3ec-a9b53db923e3:undefined");
});
it("should handle creation from orbitGtBlobProps when rdsUrl is defined", () => {
const orbitGtBlob: OrbitGtBlobProps = {
rdsUrl: "https://connect-realitydataservices.bentley.com/v2.9/Repositories/S3MXECPlugin--5b4ebd22-d94b-456b-8bd8-d59563de9acd/S3MX/RealityData/994fc408-401f-4ee1-91f0-3d7bfba50136",
accountName: "",
containerName: "",
blobFileName: "",
sasToken: "",
};
const rdSourceKey = RealityDataSource.createKeyFromOrbitGtBlobProps(orbitGtBlob);
expect(rdSourceKey.provider).to.equal(RealityDataProvider.ContextShare);
expect(rdSourceKey.format).to.equal(RealityDataFormat.OPC);
expect(rdSourceKey.id).to.be.equal("994fc408-401f-4ee1-91f0-3d7bfba50136");
expect(rdSourceKey.iTwinId).to.be.equal("5b4ebd22-d94b-456b-8bd8-d59563de9acd");
const orbitGtBlobFromKey = RealityDataSource.createOrbitGtBlobPropsFromKey(rdSourceKey);
expect(orbitGtBlobFromKey).to.be.undefined;
const rdSourceKeyStr = RealityDataSourceKey.convertToString(rdSourceKey);
expect(rdSourceKeyStr).to.be.equal("ContextShare:OPC:994fc408-401f-4ee1-91f0-3d7bfba50136:5b4ebd22-d94b-456b-8bd8-d59563de9acd");
});
}); | the_stack |
import { flattenBy, functionalUpdate, memo, RequiredKeys } from '../utils'
import {
Updater,
TableOptionsResolved,
TableState,
TableInstance,
Renderable,
TableGenerics,
InitialTableState,
Row,
Column,
RowModel,
ColumnDef,
} from '../types'
//
import { createColumn } from './column'
import { Headers } from './headers'
//
import { ColumnSizing } from '../features/ColumnSizing'
import { Expanding } from '../features/Expanding'
import { Filters } from '../features/Filters'
import { Grouping } from '../features/Grouping'
import { Ordering } from '../features/Ordering'
import { Pagination } from '../features/Pagination'
import { Pinning } from '../features/Pinning'
import { RowSelection } from '../features/RowSelection'
import { Sorting } from '../features/Sorting'
import { Visibility } from '../features/Visibility'
export type TableFeature = {
getDefaultOptions?: (instance: any) => any
getInitialState?: (initialState?: InitialTableState) => any
createInstance?: (instance: any) => any
getDefaultColumnDef?: () => any
createColumn?: (column: any, instance: any) => any
createHeader?: (column: any, instance: any) => any
createCell?: (cell: any, column: any, row: any, instance: any) => any
createRow?: (row: any, instance: any) => any
}
const features = [
Headers,
Visibility,
Ordering,
Pinning,
Filters,
Sorting,
Grouping,
Expanding,
Pagination,
RowSelection,
ColumnSizing,
] as const
//
export type CoreTableState = {}
export type CoreOptions<TGenerics extends TableGenerics> = {
data: TGenerics['Row'][]
state: Partial<TableState>
onStateChange: (updater: Updater<TableState>) => void
render: TGenerics['Renderer']
debugAll?: boolean
debugTable?: boolean
debugHeaders?: boolean
debugColumns?: boolean
debugRows?: boolean
initialState?: InitialTableState
autoResetAll?: boolean
mergeOptions?: <T>(defaultOptions: T, options: Partial<T>) => T
meta?: TGenerics['TableMeta']
getCoreRowModel: (instance: TableInstance<any>) => () => RowModel<any>
getSubRows?: (
originalRow: TGenerics['Row'],
index: number
) => undefined | TGenerics['Row'][]
getRowId?: (
originalRow: TGenerics['Row'],
index: number,
parent?: Row<TGenerics>
) => string
columns: ColumnDef<TGenerics>[]
defaultColumn?: Partial<ColumnDef<TGenerics>>
renderFallbackValue: any
}
export type CoreInstance<TGenerics extends TableGenerics> = {
initialState: TableState
reset: () => void
options: RequiredKeys<TableOptionsResolved<TGenerics>, 'state'>
setOptions: (newOptions: Updater<TableOptionsResolved<TGenerics>>) => void
getState: () => TableState
setState: (updater: Updater<TableState>) => void
_features: readonly TableFeature[]
_queue: (cb: () => void) => void
_render: <TProps>(
template: Renderable<TGenerics, TProps>,
props: TProps
) => string | null | TGenerics['Rendered']
_getRowId: (
_: TGenerics['Row'],
index: number,
parent?: Row<TGenerics>
) => string
getCoreRowModel: () => RowModel<TGenerics>
_getCoreRowModel?: () => RowModel<TGenerics>
getRowModel: () => RowModel<TGenerics>
getRow: (id: string) => Row<TGenerics>
_getDefaultColumnDef: () => Partial<ColumnDef<TGenerics>>
_getColumnDefs: () => ColumnDef<TGenerics>[]
_getAllFlatColumnsById: () => Record<string, Column<TGenerics>>
getAllColumns: () => Column<TGenerics>[]
getAllFlatColumns: () => Column<TGenerics>[]
getAllLeafColumns: () => Column<TGenerics>[]
getColumn: (columnId: string) => Column<TGenerics>
}
export function createTableInstance<TGenerics extends TableGenerics>(
options: TableOptionsResolved<TGenerics>
): TableInstance<TGenerics> {
if (options.debugAll || options.debugTable) {
console.info('Creating Table Instance...')
}
let instance = { _features: features } as unknown as TableInstance<TGenerics>
const defaultOptions = instance._features.reduce((obj, feature) => {
return Object.assign(obj, feature.getDefaultOptions?.(instance))
}, {}) as TableOptionsResolved<TGenerics>
const mergeOptions = (options: TableOptionsResolved<TGenerics>) => {
if (instance.options.mergeOptions) {
return instance.options.mergeOptions(defaultOptions, options)
}
return {
...defaultOptions,
...options,
}
}
const coreInitialState: CoreTableState = {}
let initialState = {
...coreInitialState,
...(options.initialState ?? {}),
} as TableState
instance._features.forEach(feature => {
initialState = feature.getInitialState?.(initialState) ?? initialState
})
const queued: (() => void)[] = []
let queuedTimeout = false
const coreInstance: CoreInstance<TGenerics> = {
_features: features,
options: {
...defaultOptions,
...options,
},
initialState,
_queue: cb => {
queued.push(cb)
if (!queuedTimeout) {
queuedTimeout = true
// Schedule a microtask to run the queued callbacks after
// the current call stack (render, etc) has finished.
Promise.resolve()
.then(() => {
while (queued.length) {
queued.shift()!()
}
queuedTimeout = false
})
.catch(error =>
setTimeout(() => {
throw error
})
)
}
},
reset: () => {
instance.setState(instance.initialState)
},
setOptions: updater => {
const newOptions = functionalUpdate(updater, instance.options)
instance.options = mergeOptions(newOptions)
},
_render: (template, props) => {
if (typeof instance.options.render === 'function') {
return instance.options.render(template, props)
}
if (typeof template === 'function') {
return (template as Function)(props)
}
return template
},
getState: () => {
return instance.options.state as TableState
},
setState: (updater: Updater<TableState>) => {
instance.options.onStateChange?.(updater)
},
_getRowId: (
row: TGenerics['Row'],
index: number,
parent?: Row<TGenerics>
) =>
instance.options.getRowId?.(row, index, parent) ??
`${parent ? [parent.id, index].join('.') : index}`,
getCoreRowModel: () => {
if (!instance._getCoreRowModel) {
instance._getCoreRowModel = instance.options.getCoreRowModel(instance)
}
return instance._getCoreRowModel()
},
// The final calls start at the bottom of the model,
// expanded rows, which then work their way up
getRowModel: () => {
return instance.getPaginationRowModel()
},
getRow: (id: string) => {
const row = instance.getRowModel().rowsById[id]
if (!row) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(`getRow expected an ID, but got ${id}`)
}
throw new Error()
}
return row
},
_getDefaultColumnDef: memo(
() => [instance.options.defaultColumn],
defaultColumn => {
defaultColumn = (defaultColumn ?? {}) as Partial<ColumnDef<TGenerics>>
return {
header: props => props.header.column.id,
footer: props => props.header.column.id,
cell: props => props.getValue()?.toString?.() ?? null,
...instance._features.reduce((obj, feature) => {
return Object.assign(obj, feature.getDefaultColumnDef?.())
}, {}),
...defaultColumn,
} as Partial<ColumnDef<TGenerics>>
},
{
debug: () => instance.options.debugAll ?? instance.options.debugColumns,
key: process.env.NODE_ENV === 'development' && 'getDefaultColumnDef',
}
),
_getColumnDefs: () => instance.options.columns,
getAllColumns: memo(
() => [instance._getColumnDefs()],
columnDefs => {
const recurseColumns = (
columnDefs: ColumnDef<TGenerics>[],
parent?: Column<TGenerics>,
depth = 0
): Column<TGenerics>[] => {
return columnDefs.map(columnDef => {
const column = createColumn(instance, columnDef, depth, parent)
column.columns = columnDef.columns
? recurseColumns(columnDef.columns, column, depth + 1)
: []
return column
})
}
return recurseColumns(columnDefs)
},
{
key: process.env.NODE_ENV === 'development' && 'getAllColumns',
debug: () => instance.options.debugAll ?? instance.options.debugColumns,
}
),
getAllFlatColumns: memo(
() => [instance.getAllColumns()],
allColumns => {
return allColumns.flatMap(column => {
return column.getFlatColumns()
})
},
{
key: process.env.NODE_ENV === 'development' && 'getAllFlatColumns',
debug: () => instance.options.debugAll ?? instance.options.debugColumns,
}
),
_getAllFlatColumnsById: memo(
() => [instance.getAllFlatColumns()],
flatColumns => {
return flatColumns.reduce((acc, column) => {
acc[column.id] = column
return acc
}, {} as Record<string, Column<TGenerics>>)
},
{
key: process.env.NODE_ENV === 'development' && 'getAllFlatColumnsById',
debug: () => instance.options.debugAll ?? instance.options.debugColumns,
}
),
getAllLeafColumns: memo(
() => [instance.getAllColumns(), instance._getOrderColumnsFn()],
(allColumns, orderColumns) => {
let leafColumns = allColumns.flatMap(column => column.getLeafColumns())
return orderColumns(leafColumns)
},
{
key: process.env.NODE_ENV === 'development' && 'getAllLeafColumns',
debug: () => instance.options.debugAll ?? instance.options.debugColumns,
}
),
getColumn: columnId => {
const column = instance._getAllFlatColumnsById()[columnId]
if (!column) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`[Table] Column with id ${columnId} does not exist.`)
}
throw new Error()
}
return column
},
}
Object.assign(instance, coreInstance)
instance._features.forEach(feature => {
return Object.assign(instance, feature.createInstance?.(instance))
})
return instance
} | the_stack |
import cbor from 'cbor';
import chalk from 'chalk';
import dgram from 'dgram';
import express from 'express';
import net from 'net';
import upnp from 'node-ssdp';
import {Readable} from 'stream';
import xmlBuilder from 'xmlbuilder2';
import yargs from 'yargs';
import {ControlKind, DiscoveryKind} from '../common/discovery';
import {IOPCMessage} from './types';
const bonjour = require('bonjour');
const mdnsParser = require('multicast-dns-service-types');
const opcParser = require('opc/parser');
const opcStrand = require('opc/strand');
const argv =
yargs.usage('Usage: $0 --device_id ID [protocol settings]')
.option('discovery_protocol', {
describe: 'Discovery Protocol',
alias: 'd',
type: 'string',
demandOption: true,
default: DiscoveryKind.UDP,
choices: Object.values(DiscoveryKind),
})
.option('control_protocol', {
describe: 'Control Protocol',
alias: 'c',
type: 'string',
demandOption: true,
default: ControlKind.TCP,
choices: Object.values(ControlKind),
})
.option('mdns_service_name', {
describe: 'MDNS service name',
type: 'string',
default: '_sample._tcp.local',
})
.option('mdns_instance_name', {
describe: 'MDNS instance name.',
type: 'string',
default: 'strand1._sample._tcp.local',
})
.option('upnp_server_port', {
describe: 'Port to serve XML UPnP configuration by HTTP server',
type: 'number',
default: 8080,
})
.option('upnp_service_type', {
describe: 'UPnP service type',
type: 'string',
default: 'urn:sample:service:strand:1',
})
.option('upnp_device_type', {
describe: 'UPnP device type',
type: 'string',
default: 'urn:sample:device:strand:1',
})
.option('udp_discovery_port', {
describe: 'port to listen on for UDP discovery query',
type: 'number',
default: 3311,
})
.option('udp_discovery_packet', {
describe:
'hex encoded packet content to match for UDP discovery query',
type: 'string',
default: 'A5A5A5A5',
})
.option('device_id', {
describe: 'device id to return in the discovery response',
type: 'string',
demandOption: true,
})
.option('device_model', {
describe: 'device model to return in the discovery response',
default: 'fakecandy',
})
.option('hardware_revision', {
describe: 'hardware revision to return in the discovery response',
default: 'evt-1',
})
.option('firmware_revision', {
describe: 'firmware revision to return in the discovery response',
default: 'v1-beta',
})
.option('opc_port', {
describe: 'port to listen on for openpixelcontrol messages',
default: 7890,
})
.option('led_char', {
describe: 'character to show for each strand leds',
default: '◉',
})
.option('led_count', {
describe: 'number of leds per strands',
default: 16,
})
.option('channel', {
describe:
'add a new led strand with the corresponding channel number',
default: [1],
array: true,
})
.argv;
function makeDiscoveryData() {
const discoveryData = {
id: argv.device_id,
model: argv.device_model,
hw_rev: argv.hardware_revision,
fw_rev: argv.firmware_revision,
channels: argv.channel,
};
return discoveryData;
}
function startUdpDiscovery() {
const discoveryPacket = Buffer.from(argv.udp_discovery_packet, 'hex');
const socket = dgram.createSocket('udp4');
// Handle discovery request.
socket.on('message', (msg, rinfo) => {
if (msg.compare(discoveryPacket) !== 0) {
console.warn('UDP received unknown payload:', msg, 'from:', rinfo);
return;
}
console.debug('UDP received discovery payload:', msg, 'from:', rinfo);
// Reply to discovery request with device parameters encoded in CBOR.
// note: any encoding/properties could be used as long as the app-side can
// interpret the payload.
const discoveryData = makeDiscoveryData();
const responsePacket = cbor.encode(discoveryData);
socket.send(responsePacket, rinfo.port, rinfo.address, (error) => {
if (error !== null) {
console.error('UDP failed to send ack:', error);
return;
}
console.debug(
'UDP sent discovery response:', responsePacket, 'to:', rinfo);
});
});
socket.on('listening', () => {
console.log('UDP discovery listening', socket.address());
});
socket.bind(argv.udp_discovery_port);
}
function startMdnsDiscovery() {
// Validate and parse the input string
const serviceParts = mdnsParser.parse(argv.mdns_service_name);
// Publish the DNS-SD service
const mdnsServer = bonjour();
mdnsServer.publish({
name: argv.device_id,
type: serviceParts.name,
protocol: serviceParts.protocol,
port: 5353,
txt: makeDiscoveryData(),
});
// Log query events from internal mDNS server
mdnsServer._server.mdns.on('query', (query: any) => {
if (query.questions[0].name === argv.mdns_service_name) {
console.debug(`Received mDNS query for ${argv.mdns_service_name}`);
}
});
console.log(`mDNS discovery advertising ${argv.mdns_service_name}`);
}
function startUpnpDiscovery() {
const descriptionPath = '/device.xml';
// HTTP server to response to description requests
const server = express();
server.get(descriptionPath, (req, res) => {
console.debug(`UPnP: received device description request.`);
const deviceDescription = upnpCreateXmlDescription();
res.status(200).send(deviceDescription);
});
server.listen(argv.upnp_server_port, () => {
console.log(`UPnP: HTTP server listening on port ${argv.upnp_server_port}`);
});
// Start the UPnP advertisements
const upnpServer = new upnp.Server({
location: {
path: descriptionPath,
port: argv.upnp_server_port,
},
udn: `uuid:${argv.device_id}`,
});
upnpServer.addUSN('upnp:rootdevice');
upnpServer.addUSN(argv.upnp_device_type);
upnpServer.addUSN(argv.upnp_service_type);
upnpServer.start();
console.log(`UPnP discovery advertising ${argv.upnp_service_type}`);
}
// UPnP HTTP server should return XML with device description
// in compliance with schemas-upnp-org. See
// http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf
function upnpCreateXmlDescription() {
const description = {
root: {
'@xmlns': 'urn:schemas-upnp-org:device-1-0',
'specVersion': {
major: '1',
minor: '1',
},
'device': {
deviceType: argv.upnp_device_type,
friendlyName: 'Virtual Light Device',
UDN: `uuid:${argv.device_id}`,
modelName: argv.device_model,
serviceList: {
service: argv.channel.map((channel) => {
return {
serviceType: argv.upnp_service_type,
serviceId: `urn:sample:serviceId:strand-${channel}`,
};
}),
},
},
},
};
return xmlBuilder.create(description)
.end({ prettyPrint: true });
}
export function startDiscovery() {
switch (argv.discovery_protocol) {
case DiscoveryKind.MDNS:
startMdnsDiscovery();
break;
case DiscoveryKind.UDP:
startUdpDiscovery();
break;
case DiscoveryKind.UPNP:
startUpnpDiscovery();
break;
}
}
// Default strands color is white.
const strands = new Map(
argv.channel.map(
(c) => [c, opcStrand(Buffer.alloc(argv.led_count * 3).fill(0xff))]),
);
function startTcpControl() {
const server = net.createServer((conn) => {
conn.pipe(opcParser()).on('data', handleOpcMessage);
});
server.listen(argv.opc_port, () => {
console.log(`TCP control listening on port ${argv.opc_port}`);
});
}
function startHttpControl() {
const server = express();
server.use(express.text({
type: 'application/octet-stream',
}));
server.post('/', (req, res) => {
console.debug(`HTTP: received ${req.method} request.`);
const buf = Buffer.from(req.body, 'base64');
const readable = new Readable();
// tslint:disable-next-line: no-empty
readable._read = () => {};
readable.push(buf);
readable.pipe(opcParser()).on('data', handleOpcMessage);
res.status(200).send('OK');
});
server.listen(argv.opc_port, () => {
console.log(`HTTP control listening on port ${argv.opc_port}`);
});
}
function startUdpControl() {
const server = dgram.createSocket('udp4');
server.on('message', (msg: Buffer, rinfo: dgram.RemoteInfo) => {
console.debug(`UDP: from ${rinfo.address} got`, msg);
const readable = new Readable();
// tslint:disable-next-line: no-empty
readable._read = () => {};
readable.push(msg);
readable.pipe(opcParser()).on('data', handleOpcMessage);
});
server.on('listening', () => {
console.log(`UDP control listening on port ${argv.opc_port}`);
});
server.bind(argv.opc_port);
}
export function startControl() {
switch (argv.control_protocol) {
case ControlKind.HTTP:
startHttpControl();
break;
case ControlKind.TCP:
startTcpControl();
break;
case ControlKind.UDP:
startUdpControl();
break;
}
}
function handleOpcMessage(message: IOPCMessage) {
console.debug('received command:', message.command, message.data);
switch (message.command) {
case 0: // set-pixel-color
// TODO(proppy): implement channel 0 broadcast
if (!strands.has(message.channel)) {
console.warn('unknown OPC channel:', message.command);
return;
}
strands.set(message.channel, opcStrand(message.data));
// Display updated strands to the console.
for (const [c, strand] of strands) {
for (let i = 0; i < strand.length; i++) {
const pixel = strand.getPixel(i);
process.stdout.write(chalk.rgb(
pixel[0],
pixel[1],
pixel[2],
)(argv.led_char));
}
process.stdout.write('\n');
}
break;
default:
console.warn('Unsupported OPC command:', message.command);
return;
}
} | the_stack |
import * as React from 'react';
import { IPropertyFieldDocumentPickerPropsInternal } from './PropertyFieldDocumentPicker';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { IconButton, DefaultButton, PrimaryButton, IButtonProps } from 'office-ui-fabric-react/lib/Button';
import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel';
import { Async } from 'office-ui-fabric-react/lib/Utilities';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import * as strings from 'sp-client-custom-fields/strings';
/**
* @interface
* PropertyFieldDocumentPickerHost properties interface
*
*/
export interface IPropertyFieldDocumentPickerHostProps extends IPropertyFieldDocumentPickerPropsInternal {
}
export interface IPropertyFieldDocumentPickerHostState {
openPanel?: boolean;
openRecent?: boolean;
openSite?: boolean;
openUpload?: boolean;
recentImages?: string[];
selectedImage: string;
errorMessage?: string;
}
/**
* @class
* Renders the controls for PropertyFieldDocumentPicker component
*/
export default class PropertyFieldDocumentPickerHost extends React.Component<IPropertyFieldDocumentPickerHostProps, IPropertyFieldDocumentPickerHostState> {
private latestValidateValue: string;
private async: Async;
private delayedValidate: (value: string) => void;
/**
* @function
* Constructor
*/
constructor(props: IPropertyFieldDocumentPickerHostProps) {
super(props);
//Bind the current object to the external called onSelectDate method
this.onTextFieldChanged = this.onTextFieldChanged.bind(this);
this.onOpenPanel = this.onOpenPanel.bind(this);
this.onClosePanel = this.onClosePanel.bind(this);
this.onClickRecent = this.onClickRecent.bind(this);
this.onClickSite = this.onClickSite.bind(this);
this.onClickUpload = this.onClickUpload.bind(this);
this.handleIframeData = this.handleIframeData.bind(this);
this.onEraseButton = this.onEraseButton.bind(this);
//Inits the state
this.state = {
selectedImage: this.props.initialValue,
openPanel: false,
openRecent: false,
openSite: true,
openUpload: false,
recentImages: [],
errorMessage: ''
};
this.async = new Async(this);
this.validate = this.validate.bind(this);
this.notifyAfterValidate = this.notifyAfterValidate.bind(this);
this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime);
}
/**
* @function
* Save the image value
*
*/
private saveImageProperty(imageUrl: string): void {
this.delayedValidate(imageUrl);
}
/**
* @function
* Validates the new custom field value
*/
private validate(value: string): void {
if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) {
this.notifyAfterValidate(this.props.initialValue, value);
return;
}
if (this.latestValidateValue === value)
return;
this.latestValidateValue = value;
var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || '');
if (result !== undefined) {
if (typeof result === 'string') {
if (result === undefined || result === '')
this.notifyAfterValidate(this.props.initialValue, value);
this.state.errorMessage = result;
this.setState(this.state);
}
else {
result.then((errorMessage: string) => {
if (errorMessage === undefined || errorMessage === '')
this.notifyAfterValidate(this.props.initialValue, value);
this.state.errorMessage = errorMessage;
this.setState(this.state);
});
}
}
else {
this.notifyAfterValidate(this.props.initialValue, value);
}
}
/**
* @function
* Notifies the parent Web Part of a property value change
*/
private notifyAfterValidate(oldValue: string, newValue: string) {
if (this.props.onPropertyChange && newValue != null) {
this.props.properties[this.props.targetProperty] = newValue;
this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue);
if (!this.props.disableReactivePropertyChanges && this.props.render != null)
this.props.render();
}
}
/**
* @function
* Click on erase button
*
*/
private onEraseButton(): void {
this.state.selectedImage = '';
this.setState(this.state);
this.saveImageProperty('');
}
/**
* @function
* Open the panel
*
*/
private onOpenPanel(element?: any): void {
this.state.openPanel = true;
this.setState(this.state);
}
/**
* @function
* The text field value changed
*
*/
private onTextFieldChanged(newValue: string): void {
this.state.selectedImage = newValue;
this.setState(this.state);
this.saveImageProperty(newValue);
}
/**
* @function
* Close the panel
*
*/
private onClosePanel(element?: any): void {
this.state.openPanel = false;
this.setState(this.state);
}
private onClickRecent(element?: any): void {
//this.state.openRecent = true;
//this.state.openSite = false;
//this.state.openUpload = false;
//this.setState(this.state);
}
/**
* @function
* Intercepts the iframe onedrive messages
*
*/
private handleIframeData(element?: any) {
if (this.state.openSite != true || this.state.openPanel != true)
return;
var data: string = element.data;
var indexOfPicker = data.indexOf("[OneDrive-FromPicker]");
if (indexOfPicker != -1) {
var message = data.replace("[OneDrive-FromPicker]", "");
var messageObject = JSON.parse(message);
if (messageObject.type == "cancel") {
this.onClosePanel();
} else if (messageObject.type == "success") {
var imageUrl: string = messageObject.items[0].sharePoint.url;
var extensions: string[] = this.props.allowedFileExtensions.split(',');
var lowerUrl: string = imageUrl.toLowerCase();
for (var iExt = 0; iExt < extensions.length; iExt++) {
var ext = extensions[iExt].toLowerCase();
if (lowerUrl.indexOf(ext) > -1) {
this.state.selectedImage = imageUrl;
this.setState(this.state);
this.saveImageProperty(imageUrl);
this.onClosePanel();
break;
}
}
}
}
}
/**
* @function
* When component is mount, attach the iframe event watcher
*
*/
public componentDidMount() {
window.addEventListener('message', this.handleIframeData, false);
}
/**
* @function
* Releases the watcher
*
*/
public componentWillUnmount() {
window.removeEventListener('message', this.handleIframeData, false);
if (this.async !== undefined)
this.async.dispose();
}
private onClickSite(element?: any): void {
this.state.openRecent = false;
this.state.openSite = true;
this.state.openUpload = false;
this.setState(this.state);
}
private onClickUpload(element?: any): void {
this.state.openRecent = false;
this.state.openSite = false;
this.state.openUpload = true;
this.setState(this.state);
}
/**
* @function
* Renders the datepicker controls with Office UI Fabric
*/
public render(): JSX.Element {
var iframeUrl = this.props.context.pageContext.web.absoluteUrl;
iframeUrl += '/_layouts/15/onedrive.aspx?picker=';
iframeUrl += '%7B%22sn%22%3Afalse%2C%22v%22%3A%22files%22%2C%22id%22%3A%221%22%2C%22o%22%3A%22';
iframeUrl += encodeURI(this.props.context.pageContext.web.absoluteUrl.replace(this.props.context.pageContext.web.serverRelativeUrl, ""));
iframeUrl += "%22%7D&id=";
iframeUrl += encodeURI(this.props.context.pageContext.web.serverRelativeUrl);
iframeUrl += '&view=2&typeFilters=';
iframeUrl += encodeURI('folder,' + this.props.allowedFileExtensions);
iframeUrl += '&p=2';
var previewUrl = this.props.context.pageContext.web.absoluteUrl;
previewUrl += '/_layouts/15/getpreview.ashx?path=';
previewUrl += encodeURI(this.state.selectedImage);
//Renders content
return (
<div style={{ marginBottom: '8px'}}>
<Label>{this.props.label}</Label>
<table style={{width: '100%', borderSpacing: 0}}>
<tbody>
<tr>
<td width="*">
<TextField
disabled={this.props.disabled}
value={this.state.selectedImage}
style={{width:'100%'}}
onChanged={this.onTextFieldChanged}
readOnly={this.props.readOnly}
/>
</td>
<td width="64">
<table style={{width: '100%', borderSpacing: 0}}>
<tbody>
<tr>
<td><IconButton disabled={this.props.disabled} iconProps={ { iconName: 'FolderSearch' } } onClick={this.onOpenPanel} /></td>
<td><IconButton disabled={this.props.disabled === false && (this.state.selectedImage != null && this.state.selectedImage != '') ? false: true} iconProps={ { iconName: 'Delete' } } onClick={this.onEraseButton} /></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
{ this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ?
<div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div>
<span>
<p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p>
</span>
</div>
: ''}
{this.state.selectedImage != null && this.state.selectedImage != '' && this.props.previewDocument === true ?
<div style={{marginTop: '7px'}}>
<img src={previewUrl} width="225px" height="225px" alt="Preview" />
</div>
: ''}
{ this.state.openPanel === true ?
<Panel
isOpen={this.state.openPanel} hasCloseButton={true} onDismiss={this.onClosePanel}
isLightDismiss={true} type={PanelType.large}
headerText={strings.DocumentPickerTitle}>
<div style={{backgroundColor: '#F4F4F4', width: '100%', height:'80vh', paddingTop: '0px', display: 'inline-flex'}}>
<div style={{width: '206px', backgroundColor: 'white'}}>
<div style={{width: '260px', backgroundColor: '#F4F4F4', height:'40px', marginBottom:'70px'}}>
</div>
<div style={{paddingLeft: '20px', paddingTop: '10px', color:'#A6A6A6', paddingBottom: '10px',
borderLeftWidth: '1px',
borderLeftStyle: 'solid',
borderLeftColor: this.state.openRecent === true ? 'blue' : 'white',
backgroundColor: this.state.openRecent === true ? '#F4F4F4' : '#FFFFFF'
}} onClick={this.onClickRecent} role="menuitem">
<i className="ms-Icon ms-Icon--Clock" style={{fontSize: '30px'}}></i>
{strings.DocumentPickerRecent}
</div>
<div style={{cursor: 'pointer', paddingLeft: '20px', paddingTop: '10px', paddingBottom: '10px',
borderLeftWidth: '1px',
borderLeftStyle: 'solid',
borderLeftColor: this.state.openSite === true ? 'blue' : 'white',
backgroundColor: this.state.openSite === true ? '#F4F4F4' : '#FFFFFF'
}} onClick={this.onClickSite} role="menuitem">
<i className="ms-Icon ms-Icon--Globe" style={{fontSize: '30px'}}></i>
{strings.DocumentPickerSite}
</div>
</div>
{this.state.openRecent == true ?
<div id="recent" style={{marginLeft: '2px', width:'100%', backgroundColor: 'white'}}>
<div style={{width: '100%', backgroundColor: '#F4F4F4', height:'40px', marginBottom:'20px'}}>
</div>
<div style={{paddingLeft: '30px'}}>
<h1 className="ms-font-xl">Recent images</h1>
</div>
</div>
: '' }
<div id="site" style={{marginLeft: '2px',paddingLeft: '0px', paddingTop:'0px', backgroundColor: 'white', visibility: this.state.openSite === true ? 'visible' : 'hidden', width: this.state.openSite === true ? '100%' : '0px', height: this.state.openSite === true ? '80vh' : '0px',}}>
<iframe ref="filePickerIFrame" style={{width: this.state.openSite === true ? '100%':'0px', height: this.state.openSite === true ?'80vh':'0px', borderWidth:'0'}} className="filePickerIFrame_d791363d" role="application" title="Select files from site picker view. Use toolbaar menu to perform operations, breadcrumbs to navigate between folders and arrow keys to navigate within the list"
src={iframeUrl}></iframe>
</div>
</div>
{this.state.openSite === false ?
<div style={{
position: 'absolute',
bottom: '0',
right: '0',
marginBottom: '20px',
marginRight: '20px'
}}>
<PrimaryButton> Open </PrimaryButton>
<DefaultButton onClick={this.onClosePanel}> Cancel </DefaultButton>
</div>
: ''}
</Panel>
: ''}
</div>
);
}
} | the_stack |
import { ActionType } from "../common";
import * as actions from "./actions";
import { getUserProviderInfo } from "./actions";
import { ProvidersState, ProvidersActionsType } from "./types";
import { CodeStreamState } from "..";
import {
CSMe,
CSMSTeamsProviderInfo,
CSProviderInfos,
CSSlackProviderInfo
} from "@codestream/protocols/api";
import { mapFilter, safe } from "@codestream/webview/utils";
import { ThirdPartyProviderConfig } from "@codestream/protocols/agent";
import { createSelector } from "reselect";
import { PROVIDER_MAPPINGS } from "@codestream/webview/Stream/CrossPostIssueControls/types";
import { ContextState } from "../context/types";
import { UsersState } from "../users/types";
import { SessionState } from "../session/types";
type ProviderActions = ActionType<typeof actions>;
const initialState: ProvidersState = {};
interface ThirdPartyTeam {
icon: string;
providerId: string;
teamId: string;
teamName: string;
}
export function reduceProviders(state = initialState, action: ProviderActions) {
switch (action.type) {
case "RESET":
return initialState;
case ProvidersActionsType.Update:
return { ...action.payload };
default:
return state;
}
}
type ProviderPropertyOption = { name: string } | { id: string };
function isNameOption(o: ProviderPropertyOption): o is { name: string } {
return (o as any).name != undefined;
}
export interface LabelHash {
PullRequest: string;
PullRequests: string;
Pullrequest: string;
pullrequest: string;
PR: string;
PRs: string;
pr: string;
AddSingleComment: string;
}
const MRLabel = {
PullRequest: "Merge Request",
PullRequests: "Merge Requests",
Pullrequest: "Merge request",
pullrequest: "merge request",
pullrequests: "merge requests",
PR: "MR",
PRs: "MRs",
pr: "mr",
AddSingleComment: "Add comment now"
};
const PRLabel = {
PullRequest: "Pull Request",
PullRequests: "Pull Requests",
Pullrequest: "Pull request",
pullrequest: "pull request",
pullrequests: "pull requests",
PR: "PR",
PRs: "PRs",
pr: "pr",
AddSingleComment: "Add single comment"
};
export const getPRLabel = createSelector(
(state: CodeStreamState) => state,
(state: CodeStreamState): LabelHash => {
return isConnected(state, { id: "gitlab*com" }) ||
isConnected(state, { id: "gitlab/enterprise" })
? MRLabel
: PRLabel;
}
);
export const getPRLabelForProvider = (provider: string): LabelHash => {
return provider.toLocaleLowerCase().startsWith("gitlab") ? MRLabel : PRLabel;
};
export const isConnected = (
state: CodeStreamState,
option: ProviderPropertyOption,
requiredScope?: string, // ONLY WORKS FOR SLACK AND MSTEAMS
accessTokenError?: { accessTokenError?: any }
) => {
return isConnectedSelectorFriendly(
state.users,
state.context.currentTeamId,
state.session,
state.providers,
option,
requiredScope,
accessTokenError
);
};
// isConnected, as originally written, took `state` as an argument, which means
// that it doesn't work well as a selector since every time anything at all changes
// in state, it wil re-fire. this version takes slices of what's really neeed
// rather than the overall state object.
export const isConnectedSelectorFriendly = (
users: UsersState,
currentTeamId: string,
session: SessionState,
providers: ProvidersState,
option: ProviderPropertyOption,
requiredScope?: string, // ONLY WORKS FOR SLACK AND MSTEAMS
// if the parameter below is provided, it is a container for the token error...
// basically acts like an additional return value that avoids changing the call signature for this method
// if filled, it indicates that the provider is technically connected (we have an access token),
// but the access token has come back from the provider as invalid
accessTokenError?: { accessTokenError?: any }
) => {
const currentUser = users[session.userId!] as CSMe;
// ensure there's provider info for the user
if (currentUser.providerInfo == undefined) return false;
if (isNameOption(option)) {
const providerName = option.name;
const info = getUserProviderInfo(currentUser, providerName, currentTeamId);
switch (providerName) {
case "github_enterprise":
case "gitlab_enterprise":
case "bitbucket_server": {
// these providers now only depend on having a personal access token
if (info != undefined) {
const isConnected = info.accessToken != undefined;
if (isConnected && accessTokenError) {
// see comment on accessTokenError in the method parameters, above
accessTokenError.accessTokenError = info.tokenError;
}
return isConnected;
}
return false;
}
case "jiraserver": {
// jiraserver is now the only enterprise/on-prem provider that actually uses hosts
return (
info != undefined &&
info.hosts != undefined &&
Object.keys(info.hosts).some(host => {
const isConnected =
providers[host] != undefined && info.hosts![host].accessToken != undefined;
if (isConnected && accessTokenError) {
// see comment on accessTokenError in the method parameters, above
accessTokenError.accessTokenError = info.hosts![host].tokenError;
}
return isConnected;
})
);
}
default: {
// is there an accessToken for the provider?
if (info == undefined) return false;
if (info.accessToken != undefined) {
// see comment on accessTokenError in the method parameters, above
if (accessTokenError) accessTokenError.accessTokenError = info.tokenError;
return true;
}
if (["slack", "msteams"].includes(providerName)) {
const infoPerTeam = (info as any).multiple as { [key: string]: CSProviderInfos };
if (requiredScope) {
if (
Object.values(infoPerTeam)[0] &&
// @ts-ignore
Object.values(infoPerTeam)[0].data.scope.indexOf(requiredScope) === -1
)
return false;
}
if (
infoPerTeam &&
Object.values(infoPerTeam).some(i => {
const isConnected = i.accessToken != undefined;
if (isConnected && accessTokenError) {
// see comment on accessTokenError in the method parameters, above
accessTokenError.accessTokenError = i.tokenError;
}
return isConnected;
})
) {
return true;
}
}
return false;
}
}
} else {
const providerConfig = providers[option.id];
if (!providerConfig) return false;
const infoForProvider = getUserProviderInfo(currentUser, providerConfig.name, currentTeamId);
if (infoForProvider == undefined) return false;
if (!providerConfig.isEnterprise) {
if (infoForProvider.accessToken) {
if (accessTokenError) {
// see comment on accessTokenError in the method parameters, above
accessTokenError.accessTokenError = infoForProvider.tokenError;
}
return true;
}
const infoPerTeam = (infoForProvider as any).multiple as { [key: string]: CSProviderInfos };
if (
infoPerTeam &&
Object.values(infoPerTeam).some(i => {
const isConnected = i.accessToken != undefined;
if (isConnected && accessTokenError) {
// see comment on accessTokenError in the method parameters, above
accessTokenError.accessTokenError = i.tokenError;
}
return isConnected;
})
) {
return true;
}
return false;
}
const isConnected = !!(
infoForProvider.hosts &&
infoForProvider.hosts[providerConfig.id] &&
infoForProvider.hosts[providerConfig.id].accessToken
);
if (isConnected && accessTokenError) {
// see comment on accessTokenError in the method parameters, above
accessTokenError.accessTokenError = infoForProvider.hosts![providerConfig.id].tokenError;
}
return isConnected;
}
};
export const getConnectedProviderNames = createSelector(
(state: CodeStreamState) => state,
(state: CodeStreamState) => {
return mapFilter<ThirdPartyProviderConfig, string>(
Object.values(state.providers),
providerConfig => (isConnected(state, providerConfig) ? providerConfig.name : undefined)
);
}
);
export const getConnectedProviders = createSelector(
(state: CodeStreamState) => state,
(state: CodeStreamState) => {
return Object.values(state.providers).filter(providerConfig =>
isConnected(state, providerConfig)
);
}
);
export const getConnectedSharingTargets = (state: CodeStreamState) => {
if (state.session.userId == undefined) return [];
const currentUser = state.users[state.session.userId] as CSMe;
if (currentUser.providerInfo == undefined) return [];
const slackProviderInfo = getUserProviderInfo(
currentUser,
"slack",
state.context.currentTeamId
) as CSSlackProviderInfo;
const msteamsProviderInfo = getUserProviderInfo(
currentUser,
"msteams",
state.context.currentTeamId
) as CSMSTeamsProviderInfo;
let teams: ThirdPartyTeam[] = [];
const slackInfos = safe(() => slackProviderInfo!.multiple);
if (slackInfos)
teams = teams.concat(
Object.entries(slackInfos).map(([teamId, info]) => ({
icon: PROVIDER_MAPPINGS.slack.icon!,
providerId: getProviderConfig(state, "slack")!.id,
teamId,
teamName: info.data!.team_name
}))
);
const msTeamInfos = safe(() => msteamsProviderInfo!.multiple);
if (msTeamInfos) {
const entries = Object.entries(msTeamInfos);
const len = entries.length;
teams = teams.concat(
entries.map(([teamId], index) => {
return {
icon: PROVIDER_MAPPINGS.msteams.icon!,
providerId: getProviderConfig(state, "msteams")!.id,
teamId,
teamName: len === 1 ? "MS Teams Org" : `MS Teams Org ${index + 1}`
};
})
);
}
return teams;
};
export const getProviderConfig = createSelector(
(state: CodeStreamState) => state.providers,
(_, name: string) => name,
(providerConfigs: ProvidersState, name: string) => {
for (let id in providerConfigs) {
if (providerConfigs[id].name === name) return providerConfigs[id];
}
return undefined;
}
);
export const getSupportedPullRequestHosts = createSelector(
(state: CodeStreamState) => state.providers,
(providerConfigs: ProvidersState) => {
return Object.values(providerConfigs).filter(
_ =>
_.id === "github*com" ||
_.id === "github/enterprise" ||
_.id === "gitlab*com" ||
_.id === "gitlab/enterprise"
);
}
);
export const getConnectedSupportedPullRequestHosts = createSelector(
(state: CodeStreamState) => state.users,
(state: CodeStreamState) => state.context.currentTeamId,
(state: CodeStreamState) => state.session,
(state: CodeStreamState) => state.providers,
(users: UsersState, currentTeamId: string, session: SessionState, providers: ProvidersState) => {
return Object.values(providers)
.filter(
_ =>
_.id === "github*com" ||
_.id === "github/enterprise" ||
_.id === "gitlab*com" ||
_.id === "gitlab/enterprise"
)
.map(_ => {
let obj: { accessTokenError?: boolean } = {};
const value = isConnectedSelectorFriendly(
users,
currentTeamId,
session,
providers,
{ id: _.id },
undefined,
obj
);
return {
..._,
hasAccessTokenError: !!obj.accessTokenError,
isConnected: value
};
})
.filter(_ => _.isConnected);
}
);
export const getConnectedGitLabHosts = createSelector(
(state: CodeStreamState) => state.users,
(state: CodeStreamState) => state.context.currentTeamId,
(state: CodeStreamState) => state.session,
(state: CodeStreamState) => state.providers,
(users: UsersState, currentTeamId: string, session: SessionState, providers: ProvidersState) => {
return Object.values(providers)
.filter(_ => _.id === "gitlab*com" || _.id === "gitlab/enterprise")
.map(_ => {
let obj: { accessTokenError?: boolean } = {};
const value = isConnectedSelectorFriendly(
users,
currentTeamId,
session,
providers,
{ id: _.id },
undefined,
obj
);
return {
..._,
hasAccessTokenError: !!obj.accessTokenError,
isConnected: value
};
})
.filter(_ => _.isConnected);
}
); | the_stack |
import { EventEmitter } from 'events'
import { inject, injectable } from 'inversify'
import * as tokens from '@webmonetization/wext/tokens'
import { flatMapSlow } from '../util/flatMapSlow'
import { getFrameSpec } from '../../util/tabs'
import {
Command,
ToBackgroundMessage,
ToContentMessage
} from '../../types/commands'
import { FrameSpec, sameFrame } from '../../types/FrameSpec'
import { timeout } from '../../content/util/timeout'
import { logger, Logger } from './utils'
import GetFrameResultDetails = chrome.webNavigation.GetFrameResultDetails
import MessageSender = chrome.runtime.MessageSender
// eslint-disable-next-line @typescript-eslint/no-explicit-any
interface Frame extends Record<string, any> {
// TODO: this seems useless actually
lastUpdateTimeMS: number
/**
*loading
* The document is still loading.
* interactive
* The document has finished loading and the document has been parsed but
* sub-resources such as images, stylesheets and frames are still loading.
* complete
* The document and all sub-resources have finished loading. The state
* indicates that the load event is about to fire.
*/
state: Document['readyState'] | null
/**
* Url kept up to date via webNavigation apis and content script
* readystatechange listener messages
*/
href: string
/**
* Top iframe
*/
top: boolean
/**
* Will be 0 for topmost iframe
*/
frameId: number
/**
* Will be -1 for topmost iframe
*/
parentFrameId: number
}
/**
* We don't check for state, which could be null (a transient state where
* it is undetermined due to webNavigation api limitations)
*
* Note that in the case where don't have the state we inject a script to send
* a message to the frames content script to send a message with the current
* document.readyState.
*
*/
const isFullFrame = (partial: Partial<Frame>): partial is Frame => {
return Boolean(
// typeof partial.state === 'string' &&
typeof partial.frameId === 'number' &&
typeof partial.parentFrameId === 'number' &&
typeof partial.href === 'string' &&
typeof partial.top === 'boolean' &&
typeof partial.lastUpdateTimeMS === 'number'
)
}
export interface FrameEvent {
type: string
from: string
tabId: number
frameId: number
}
export interface FrameEventWithFrame extends FrameEvent {
frame: Frame
}
export interface FrameRemovedEvent extends FrameEvent {
type: 'frameRemoved'
}
export interface FrameAddedEvent extends FrameEventWithFrame {
type: 'frameAdded'
}
export interface FrameChangedEvent extends FrameEventWithFrame {
type: 'frameChanged'
changed: Partial<Frame>
}
@injectable()
export class BackgroundFramesService extends EventEmitter {
tabs: Record<number, Array<Frame>> = {}
traceLogging = false
logEvents = false
logTabsInterval = 0
// noinspection TypeScriptFieldCanBeMadeReadonly
constructor(
@logger('BackgroundFramesService')
private log: Logger,
@inject(tokens.WextApi)
private api: typeof window.chrome
) {
super()
}
getFrame(frame: FrameSpec): Readonly<Frame> | undefined {
const frames = this.getFrames(frame.tabId)
return frames.find(f => {
return f.frameId == frame.frameId
})
}
async getFrameAsync(
frame: FrameSpec,
waitMs = 2e3
): Promise<Readonly<Frame> | undefined> {
const alreadyHave = this.getFrame(frame)
if (alreadyHave) {
return alreadyHave
}
return new Promise<Readonly<Frame> | undefined>(resolve => {
const handler = (addedFrame: FrameAddedEvent) => {
if (sameFrame(frame, addedFrame)) {
this.removeListener('frameAdded', handler)
resolve(this.getFrame(frame))
}
}
this.on('frameAdded', handler)
timeout(waitMs).then(() => {
this.removeListener('frameAdded', handler)
resolve(undefined)
})
})
}
getChildren(frame: FrameSpec): Array<Readonly<Frame>> {
const frames = this.getFrames(frame.tabId)
const directChildren = frames.filter(f => {
return f.parentFrameId == frame.frameId
})
return directChildren.concat(
flatMapSlow(directChildren, fs =>
this.getChildren({ tabId: frame.tabId, frameId: fs.frameId })
)
)
}
getFrames(tabId: number): Array<Readonly<Frame>> {
return (this.tabs[tabId] = this.tabs[tabId] ?? [])
}
updateOrAddFrame(
from: string,
{ tabId, frameId }: FrameSpec,
partial: Readonly<Partial<Frame>>
) {
const lastUpdateTimeMS = partial.lastUpdateTimeMS ?? Date.now()
const frame = this.getFrame({ tabId, frameId })
if (frame && frame.lastUpdateTimeMS > lastUpdateTimeMS) {
if (this.traceLogging) {
this.log('ignoring frame update', { tabId, frameId, changed: partial })
}
return
}
const update = { lastUpdateTimeMS, ...partial }
const frames = this.getFrames(tabId)
const changed: Partial<Frame> = {}
let changes = 0
if (!frame) {
if (isFullFrame(update)) {
frames.push(update)
const event: FrameAddedEvent = {
type: 'frameAdded',
from,
tabId,
frameId,
frame: update
}
const changedEvent: FrameChangedEvent = {
...event,
type: 'frameChanged',
changed: update
}
this.emit(event.type, event)
this.emit(changedEvent.type, changedEvent)
} else {
this.log(
'ERROR in frameAdded from=%s update=%s',
from,
JSON.stringify(update)
)
}
} else if (frame) {
Object.entries(update).forEach(([key, val]) => {
if (frame[key] !== val && val != null) {
// Mutate the frame in place
;(frame as Frame)[key] = val
changed[key] = val
if (key !== 'lastUpdateTimeMS') {
changes++
}
}
})
if (changes) {
const changedEvent: FrameChangedEvent = {
type: 'frameChanged',
from,
tabId,
frameId,
changed,
frame
}
this.emit(changedEvent.type, changedEvent)
}
}
}
private async getWebNavigationFrame({
tabId,
frameId
}: FrameSpec): Promise<GetFrameResultDetails> {
return new Promise((resolve, reject) => {
this.api.webNavigation.getFrame({ tabId, frameId }, frame => {
if (frame) {
resolve(frame)
} else {
const spec = JSON.stringify({ tabId, frameId })
reject(new Error(`invalid_frame_spec: can not get frame for ${spec}`))
}
})
})
}
monitor() {
const events = ['frameChanged', 'frameAdded', 'frameRemoved'] as const
if (this.logEvents) {
events.forEach(e => {
this.on(e, (event: FrameEvent) => {
this.log(e, JSON.stringify(event, null, 2))
})
})
}
/**
* Be wary of context invalidation during extension reloading causing
* confusion here.
*
* This will pick up state from tabs which need reloading to refresh the
* context state.
*
* Perhaps should periodically prune, at least in dev mode.
*
* TODO: Is there a webNavigation (read: not content script) API for
* determining window unload ?
*
* {@see Frames#sendUnloadMessage}
*/
this.api.tabs.query({}, tabs => {
tabs.forEach(tab => {
if (tab.id) {
this.useWebNavigationToUpdateFrames(tab.id)
}
})
})
if (this.logTabsInterval) {
setInterval(() => {
this.logTabs()
}, this.logTabsInterval)
}
const makeCallback = (event: string) => {
return (details: {
url: string
tabId: number
frameId: number
parentFrameId?: number
}) => {
if (
!details.url.startsWith('http') ||
(details.parentFrameId !== 0 && details.frameId !== 0)
) {
return
}
const frameSpec = {
tabId: details.tabId,
frameId: details.frameId
}
const frame = this.getFrame(frameSpec)
this.log('webNavigation.' + event)
if (this.traceLogging) {
this.log('webNavigation.%s details:%o frame=%o', event, details, {
frame
})
}
const partial = {
href: details.url,
frameId: details.frameId,
parentFrameId: details.parentFrameId,
state: null,
top: details.frameId === 0
}
this.updateOrAddFrame(`webNavigation.${event}`, frameSpec, partial)
if (this.getFrame(frameSpec)?.state == null) {
this.requestFrameState(frameSpec)
}
}
}
// Not available on Safari, last checked version 14.1 (16611.1.21.161.6)
if (this.api.webNavigation.onHistoryStateUpdated) {
this.api.webNavigation.onHistoryStateUpdated.addListener(
makeCallback('onHistoryStateUpdated')
)
} else {
this.log(
'Using tabs.onUpdated workaround for lack of onHistoryStateUpdated'
)
this.api.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.url) {
this.updateOrAddFrame(
`tabs.onUpdated.changeInfo.url`,
{ tabId, frameId: 0 },
{ href: changeInfo.url }
)
}
if (changeInfo.status) {
this.updateOrAddFrame(
`tabs.onUpdated.changeInfo.url`,
{ tabId, frameId: 0 },
{ state: changeInfo.status as 'loading' | 'complete' }
)
}
})
}
// Not available on Safari, last checked version 14.1 (16611.1.21.161.6)
if (this.api.webNavigation.onReferenceFragmentUpdated) {
this.api.webNavigation.onReferenceFragmentUpdated.addListener(
makeCallback('onReferenceFragmentUpdated')
)
}
// These are required otherwise there's a race between usages of getFrameOrDefault()
// and the initial `useWebNavigationToUpdateFrames()`
this.api.webNavigation.onCommitted.addListener(makeCallback('onCommitted'))
this.api.webNavigation.onCompleted.addListener(makeCallback('onCompleted'))
this.api.webNavigation.onBeforeNavigate.addListener(
makeCallback('onBeforeNavigate')
)
this.api.tabs.onRemoved.addListener(tabId => {
this.log('tabs.onTabRemoved %s', tabId)
delete this.tabs[tabId]
})
this.api.runtime.onMessage.addListener(
(message: ToBackgroundMessage, sender) => {
// Important: On Firefox, don't return a Promise directly (e.g. async
// function) else other listeners do not get run!!
// See: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage
void this.onMessageAsync(sender, message)
}
)
}
sendCommandToFramesMatching(
cmd: ToContentMessage,
matcher: (frame: Frame) => boolean
) {
for (const [tabId, framesList] of Object.entries(this.tabs)) {
for (const frame of framesList) {
if (matcher(frame)) {
this.api.tabs.sendMessage(Number(tabId), cmd, {
frameId: frame.frameId
})
}
}
}
}
async sendCommand<C extends Command, R>(
{ tabId, frameId }: FrameSpec,
command: C
): Promise<R> {
return new Promise<R>((resolve, reject) => {
this.api.tabs.sendMessage(tabId, command, { frameId }, (result: R) => {
if (this.api.runtime.lastError) {
reject(this.api.runtime.lastError)
} else {
resolve(result)
}
})
})
}
private async onMessageAsync(
sender: MessageSender,
message: ToBackgroundMessage
) {
if (!sender.tab) {
this.log('onMessage, no tab', JSON.stringify({ message, sender }))
return
}
const { tabId, frameId, spec: frameSpec } = getFrameSpec(sender)
if (message.command === 'unloadFrame') {
this.log('unloadFrame %s', frameId, message.data)
const frames = (this.tabs[tabId] = this.tabs[tabId] ?? [])
const ix = frames.findIndex(f => f.frameId === frameId)
if (ix !== -1) {
this.log('removing', ix)
frames.splice(ix, 1)
const removedEvent: FrameRemovedEvent = {
from: 'unloadFrame',
type: 'frameRemoved',
frameId,
tabId
}
this.emit(removedEvent.type, removedEvent)
}
if (frames.length === 0) {
delete this.tabs[tabId]
}
} else if (message.command === 'frameStateChange') {
if (this.traceLogging) {
this.log(
'frameStateChange, frameId=%s, tabId=%s, message=%s',
sender.frameId,
tabId,
JSON.stringify(message, null, 2)
)
}
const { href, state } = message.data
const frame = this.getFrame(frameSpec)
if (frame) {
// top and frameId, parentFrameId don't change
this.updateOrAddFrame('frameStateChange', frameSpec, {
href,
state
})
} else {
const navFrame = await this.getWebNavigationFrame(frameSpec)
this.updateOrAddFrame('frameStateChange', frameSpec, {
frameId,
href: navFrame.url,
state,
top: frameId === 0,
parentFrameId: navFrame.parentFrameId
})
}
}
}
private useWebNavigationToUpdateFrames(tabId: number) {
this.api.webNavigation.getAllFrames({ tabId }, frames => {
frames?.forEach(frame => {
if (
!frame.url.startsWith('http') ||
(frame.frameId !== 0 && frame.parentFrameId !== 0)
) {
return
}
const frameSpec = { tabId, frameId: frame.frameId }
this.updateOrAddFrame('useWebNavigationToUpdateFrames', frameSpec, {
frameId: frame.frameId,
top: frame.frameId === 0,
href: frame.url,
state: null,
parentFrameId: frame.parentFrameId
})
if (this.getFrame(frameSpec)?.state == null) {
this.requestFrameState(frameSpec)
}
})
})
}
/**
* Somewhat interestingly, this seems to work even when a content script context
* is invalidated.
*/
private requestFrameState({ tabId, frameId }: FrameSpec) {
this.api.tabs.executeScript(
tabId,
{
frameId: frameId,
// language=JavaScript
code: `
(function sendMessage() {
const frameStateChange = {
command: 'frameStateChange',
data: {
state: document.readyState,
href: window.location.href
}
}
chrome.runtime.sendMessage(frameStateChange)
})()
`
},
() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const ignored = this.api.runtime.lastError
}
)
}
private logTabs() {
this.log('tabs', JSON.stringify(this.tabs, null, 2))
}
}
export type FrameEvents =
| FrameAddedEvent
| FrameRemovedEvent
| FrameChangedEvent
export type FramesEventType = FrameEvents['type']
export interface FramesEventMap extends Record<FramesEventType, FrameEvents> {
frameAdded: FrameAddedEvent
frameRemoved: FrameRemovedEvent
frameChanged: FrameChangedEvent
}
export interface BackgroundFramesService extends EventEmitter {
on<T extends FramesEventType>(
event: T,
listener: (ev: FramesEventMap[T]) => void
): this
once<T extends FramesEventType>(
event: T,
listener: (ev: FramesEventMap[T]) => void
): this
emit<T extends FramesEventType>(event: T, ev: FramesEventMap[T]): boolean
} | the_stack |
import execa from 'execa';
import prettyBytes from 'pretty-bytes';
import glob from 'glob-promise';
import fs from 'fs-extra';
import path from 'path';
import tmp from 'tmp';
import { build } from 'esbuild';
import {
isCI,
toInteger,
TSError,
toPascalCase,
set,
toUpperCase
} from '@terascope/utils';
import reply from './reply';
import { wasmPlugin, getPackage } from '../helpers/utils';
interface ZipResults {
name: string;
bytes: string;
}
interface AssetRegistry {
[dir_name: string]: {
[property in OpType]: string
}
}
type OpType = 'API' | 'Fetcher' | 'Processor' | 'Schema' | 'Slicer';
export class AssetSrc {
/**
*
* @param {string} srcDir Path to a valid asset source directory, must
* must contain `asset/asset.json` and `asset/package.json` files.
*/
srcDir: string;
assetFile: string;
packageJson: any;
assetPackageJson: any;
name: string;
version: string;
bundle?: boolean;
bundleTarget?: string;
outputFileName: string;
debug: boolean;
overwrite: boolean;
devMode = false;
constructor(
srcDir: string,
devMode = false,
debug = false,
bundle = false,
bundleTarget = undefined,
overwrite = false
) {
this.bundle = bundle;
this.bundleTarget = bundleTarget;
this.debug = debug;
this.devMode = devMode;
this.overwrite = overwrite;
this.srcDir = path.resolve(srcDir);
this.assetFile = path.join(this.srcDir, 'asset', 'asset.json');
this.packageJson = getPackage(path.join(this.srcDir, 'package.json'));
this.assetPackageJson = getPackage(path.join(this.srcDir, 'asset', 'package.json'));
if (!this.assetFile || !fs.pathExistsSync(this.assetFile)) {
throw new Error(`${this.srcDir} is not a valid asset source directory.`);
}
const asset = fs.readJSONSync(this.assetFile);
this.name = asset.name;
this.version = asset.version;
this.outputFileName = path.join(this.buildDir, this.zipFileName);
}
/** @returns {string} Path to the output directory for the finished asset zipfile */
get buildDir(): string {
return path.join(this.srcDir, 'build');
}
get zipFileName(): string {
let zipName;
let nodeVersion;
if (this.bundle) {
nodeVersion = this.bundleTarget?.replace('node', '');
zipName = `${this.name}-v${this.version}-node-${nodeVersion}-bundle.zip`;
} else {
nodeVersion = process.version.split('.', 1)[0].substr(1);
zipName = `${this.name}-v${this.version}-node-${nodeVersion}-${process.platform}-${process.arch}.zip`;
}
return zipName;
}
// TODO: This has a dependency on the external executable `yarn`,
// we should test that this exists earlier than this and also
// support `npm`.
/**
* runs yarn command
* @param {string} dir - Path to directory containing package.json
* @param {Array} yarnArgs - Array of arguments or options to be passed to yarn command
*/
private async _yarnCmd(dir: string, yarnArgs: string[]) {
return execa('yarn', yarnArgs, { cwd: dir });
}
/**
* operatorFiles finds all of the Teraslice operator files, including:
* api.js
* fetcher.js
* processor.js
* schema.js
* slicer.js
* @returns {Array} array of paths to all of the operator files
*/
async operatorFiles(): Promise<string[]> {
const matchString = path.join(this.srcDir, 'asset', '**/{api,fetcher,processor,schema,slicer}.js');
return glob(matchString, { ignore: ['**/node_modules/**', '**/_*/**', '**/.*/**'] });
}
/**
* generates the registry object that is used to generate the index.js asset
* registry
*/
async generateRegistry(): Promise<AssetRegistry> {
const assetRegistry: AssetRegistry = {};
const files = await this.operatorFiles();
for (const file of files) {
const parsedPath = path.parse(file);
const opDirectory = parsedPath.dir.split(path.sep).pop();
const pathName = parsedPath.name === 'api' ? toUpperCase(parsedPath.name) : toPascalCase(parsedPath.name);
if (opDirectory) {
set(
assetRegistry,
`${opDirectory}.${pathName}`,
parsedPath.base
);
} else {
throw new Error(`Error: unable to get 'op_directory' from ${parsedPath}`);
}
}
return assetRegistry;
}
async build(): Promise<ZipResults> {
let zipOutput;
if (!this.overwrite && fs.pathExistsSync(this.outputFileName)) {
throw new Error(`Zipfile already exists "${this.outputFileName}"`);
}
try {
// make sure the build dir exists in the srcDir directory
await fs.ensureDir(this.buildDir);
} catch (err) {
throw new Error(`Failed to create directory ${this.buildDir}: ${err}`);
}
// make temp dir
const tmpDir = tmp.dirSync();
reply.info(`* copying files to the tmp directory "${tmpDir.name}"`);
// copy entire asset dir (srcDir) to tmpdir
await fs.copy(this.srcDir, tmpDir.name);
const assetJSON = await fs.readJSON(path.join(tmpDir.name, 'asset', 'asset.json'));
// NOTE: The asset.json for bundled assets sets platform and arch to
// false because bundled assets use WASM to avoid node-gyp. If an asset
// included an actual platform specific binary, it use the original
// unbundled asset type
if (!this.devMode) {
const restrictions:string[] = [];
if (assetJSON.node_version === undefined) {
if (this.bundle) {
assetJSON.node_version = toInteger(this.bundleTarget?.replace('node', ''));
} else {
assetJSON.node_version = toInteger(process.version.split('.', 1)[0].substr(1));
}
restrictions.push('node_version');
}
if (assetJSON.platform === undefined) {
assetJSON.platform = (this.bundle ? false : process.platform);
restrictions.push('platform');
}
if (assetJSON.arch === undefined) {
assetJSON.arch = (this.bundle ? false : process.arch);
restrictions.push('arch');
}
if (restrictions.length && !isCI) {
reply.info(
`[NOTE] Automatically added ${restrictions.join(', ')} restrictions for the asset`
+ ' Use --dev to temporarily disable this,'
+ ` or put false for the values ${restrictions.join(', ')} in the asset.json`
);
}
}
// write asset.json into tmpDir
await fs.writeJSON(path.join(tmpDir.name, 'asset', 'asset.json'), assetJSON, {
spaces: 4,
});
if (this.bundle) {
const bundleDir = tmp.dirSync();
reply.info(`* making tmp bundle directory "${bundleDir.name}"`);
// write asset.json into bundleDir
await fs.writeJSON(path.join(bundleDir.name, 'asset.json'), assetJSON, {
spaces: 4,
});
// run npm --cwd srcDir/asset --prod --silent --no-progress
reply.info('* running yarn --prod --no-progress');
await this._yarnCmd(path.join(tmpDir.name, 'asset'), ['--prod', '--no-progress']);
// Since we now require bundled assets to implement a registry, we
// require that Javascript assets place it at `asset/index.js` and
// TypeScript assets place it at `asset/src/index.ts`
let entryPoint = '';
try {
if (await fs.pathExists(path.join(tmpDir.name, 'asset', 'index.js'))) {
entryPoint = path.join(tmpDir.name, 'asset', 'index.js');
} else if (await fs.pathExists(path.join(tmpDir.name, 'asset', 'src', 'index.ts'))) {
entryPoint = path.join(tmpDir.name, 'asset', 'src', 'index.ts');
} else {
reply.fatal('Bundled assets require an asset registry at either asset/index.js or asset/src/index.ts');
}
reply.warning(`* entryPoint: ${entryPoint}`);
} catch (err) {
reply.fatal(`Unable to resolve entry point due to error: ${err}`);
}
const result = await build({
bundle: true,
entryPoints: [entryPoint],
outdir: bundleDir.name,
platform: 'node',
sourcemap: false,
target: this.bundleTarget,
plugins: [wasmPlugin],
keepNames: true
});
// Test require the asset to make sure it loads, if the process node
// version is the same as the buildTarget
if (this.bundleTarget?.replace('node', '') === process.version.split('.', 1)[0].substr(1)) {
try {
const modulePath = require.resolve(bundleDir.name);
reply.info(`* doing a test require of ${modulePath}`);
const requireOut = require(modulePath).ASSETS;
if (this.debug) {
reply.warning(JSON.stringify(requireOut, null, 2));
}
} catch (err) {
reply.fatal(`Bundled asset failed to require: ${err}`);
}
}
if (result.warnings.length > 0) {
reply.warning(result.warnings);
}
try {
if (this.overwrite && fs.pathExistsSync(this.outputFileName)) {
reply.info(`* overwriting ${this.outputFileName}`);
await fs.remove(this.outputFileName);
}
await this._copyStaticAssets(tmpDir.name, bundleDir.name);
reply.info('* zipping the asset bundle');
// create zipfile
// cp include files that are not required, should require as much as possible
zipOutput = await AssetSrc.zip(path.join(bundleDir.name), this.outputFileName);
// remove temp directories
await fs.remove(tmpDir.name);
await fs.remove(bundleDir.name);
} catch (err) {
throw new TSError(err, {
reason: 'Failure creating asset zipfile'
});
}
} else {
// run yarn --cwd srcDir --prod --silent --no-progress asset:build
if (this.packageJson?.scripts && this.packageJson.scripts['asset:build']) {
reply.info('* running yarn asset:build');
await this._yarnCmd(tmpDir.name, ['run', 'asset:build']);
}
if (await fs.pathExists(path.join(tmpDir.name, '.yarnclean'))) {
reply.info('* running yarn autoclean --force');
await this._yarnCmd(tmpDir.name, ['autoclean', '--force']);
}
// run npm --cwd srcDir/asset --prod --silent --no-progress
reply.info('* running yarn --prod --no-progress');
await this._yarnCmd(path.join(tmpDir.name, 'asset'), ['--prod', '--no-progress']);
// run yarn --cwd srcDir --prod --silent --no-progress asset:post-build
if (this.packageJson?.scripts && this.packageJson.scripts['asset:post-build']) {
reply.info('* running yarn asset:post-build');
await this._yarnCmd(tmpDir.name, ['run', 'asset:post-build']);
}
try {
if (this.overwrite && fs.pathExistsSync(this.outputFileName)) {
reply.info(`* overwriting ${this.outputFileName}`);
await fs.remove(this.outputFileName);
}
reply.info('* zipping the asset bundle');
// create zipfile
zipOutput = await AssetSrc.zip(path.join(tmpDir.name, 'asset'), this.outputFileName);
// remove temp directory
await fs.remove(tmpDir.name);
} catch (err) {
throw new TSError(err, {
reason: 'Failure creating asset zipfile'
});
}
}
return zipOutput;
}
/**
* zip - Creates properly named zip archive of asset from tmpAssetDir
* @param {string} tmpAssetDir Path to the temporary asset source directory
* @param {string} outputFileName
* @returns ZipResults
*/
static async zip(tmpAssetDir: string, outputFileName: string): Promise<ZipResults> {
if (!await fs.pathExists(tmpAssetDir)) {
throw new Error(`Missing asset directory "${tmpAssetDir}"`);
}
await execa('zip', ['-q', '-r', '-9', outputFileName, '.'], {
stdio: 'inherit',
cwd: tmpAssetDir
});
const { size } = await fs.stat(outputFileName);
return { name: outputFileName, bytes: prettyBytes(size) };
}
private async _copyStaticAssets(tempDir: string, bundleDir: string): Promise<void> {
const exists = await fs.pathExists(path.join(tempDir, 'asset', '__static_assets'));
if (exists) {
await fs.copy(path.join(tempDir, 'asset', '__static_assets'), path.join(bundleDir, '__static_assets'));
}
}
} | the_stack |
namespace com.keyman.osk {
export class KeyData {
['key']: OSKKey;
['keyId']: string;
['subKeys']?: OSKKeySpec[];
constructor(keyData: OSKKey, keyId: string) {
this['key'] = keyData;
this['keyId'] = keyId;
}
}
export type KeyElement = HTMLDivElement & KeyData;
// Many thanks to https://www.typescriptlang.org/docs/handbook/advanced-types.html for this.
export function link(elem: HTMLDivElement, data: KeyData): KeyElement {
let e = <KeyElement> elem;
// Merges all properties and methods of KeyData onto the underlying HTMLDivElement, creating a merged class.
for(let id in data) {
if(!e.hasOwnProperty(id)) {
(<any>e)[id] = (<any>data)[id];
}
}
return e;
}
export function isKey(elem: Node): boolean {
return elem && ('key' in elem) && ((<any> elem['key']) instanceof OSKKey);
}
export function getKeyFrom(elem: Node): KeyElement {
if(isKey(elem)) {
return <KeyElement> elem;
} else {
return null;
}
}
export class OSKKeySpec implements keyboards.LayoutKey {
id: string;
// Only set (within @keymanapp/keyboard-processor) for keys actually specified in a loaded layout
baseKeyID?: string;
coreID?: string;
elementID?: string;
text?: string;
sp?: number | keyboards.ButtonClass;
width: string;
layer?: string; // The key will derive its base modifiers from this property - may not equal the layer on which it is displayed.
nextlayer?: string;
pad?: string;
sk?: OSKKeySpec[];
constructor(id: string, text?: string, width?: string, sp?: number | keyboards.ButtonClass, nextlayer?: string, pad?: string) {
this.id = id;
this.text = text;
this.width = width ? width : "50";
this.sp = sp;
this.nextlayer = nextlayer;
this.pad = pad;
}
}
export abstract class OSKKey {
// Defines the PUA code mapping for the various 'special' modifier/control keys on keyboards.
// `specialCharacters` must be kept in sync with the same variable in builder.js. See also CompileKeymanWeb.pas: CSpecialText10
static readonly specialCharacters = {
'*Shift*': 8,
'*Enter*': 5,
'*Tab*': 6,
'*BkSp*': 4,
'*Menu*': 11,
'*Hide*': 10,
'*Alt*': 25,
'*Ctrl*': 1,
'*Caps*': 3,
'*ABC*': 16,
'*abc*': 17,
'*123*': 19,
'*Symbol*': 21,
'*Currency*': 20,
'*Shifted*': 8, // set SHIFTED->9 for filled arrow icon
'*AltGr*': 2,
'*TabLeft*': 7,
'*LAlt*': 0x56,
'*RAlt*': 0x57,
'*LCtrl*': 0x58,
'*RCtrl*': 0x59,
'*LAltCtrl*': 0x60,
'*RAltCtrl*': 0x61,
'*LAltCtrlShift*': 0x62,
'*RAltCtrlShift*': 0x63,
'*AltShift*': 0x64,
'*CtrlShift*': 0x65,
'*AltCtrlShift*': 0x66,
'*LAltShift*': 0x67,
'*RAltShift*': 0x68,
'*LCtrlShift*': 0x69,
'*RCtrlShift*': 0x70,
// Added in Keyman 14.0.
'*LTREnter*': 0x05, // Default alias of '*Enter*'.
'*LTRBkSp*': 0x04, // Default alias of '*BkSp*'.
'*RTLEnter*': 0x71,
'*RTLBkSp*': 0x72,
'*ShiftLock*': 0x73,
'*ShiftedLock*': 0x74,
'*ZWNJ*': 0x75, // If this one is specified, auto-detection will kick in.
'*ZWNJiOS*': 0x75, // The iOS version will be used by default, but the
'*ZWNJAndroid*': 0x76, // Android platform has its own default glyph.
};
static readonly BUTTON_CLASSES = [
'default',
'shift',
'shift-on',
'special',
'special-on',
'', // Key classes 5 through 7 are reserved for future use.
'',
'',
'deadkey',
'blank',
'hidden'
];
static readonly HIGHLIGHT_CLASS = 'kmw-key-touched';
readonly spec: OSKKeySpec;
btn: KeyElement;
label: HTMLSpanElement;
square: HTMLDivElement;
/**
* The layer of the OSK on which the key is displayed.
*/
readonly layer: string;
constructor(spec: OSKKeySpec, layer: string) {
this.spec = spec;
this.layer = layer;
}
abstract getId(): string;
/**
* Attach appropriate class to each key button, according to the layout
*
* @param {Object=} layout source layout description (optional, sometimes)
*/
public setButtonClass() {
let key = this.spec;
let btn = this.btn;
var n=0;
if(typeof key['dk'] == 'string' && key['dk'] == '1') {
n=8;
}
if(typeof key['sp'] == 'string') {
n=parseInt(key['sp'],10);
}
if(n < 0 || n > 10) {
n=0;
}
btn.className='kmw-key kmw-key-'+OSKKey.BUTTON_CLASSES[n];
}
/**
* For keys with button classes that support toggle states, this method
* may be used to toggle which state the key's button class is in.
* - shift <=> shift-on
* - special <=> special-on
* @param {boolean=} flag The new toggle state
*/
public setToggleState(flag?: boolean) {
let btnClassId: number;
let classAsString: boolean;
if(classAsString = typeof this.spec['sp'] == 'string') {
btnClassId = parseInt(this.spec['sp'], 10);
} else {
btnClassId = this.spec['sp'];
}
// 1 + 2: shift + shift-on
// 3 + 4: special + special-on
switch(OSKKey.BUTTON_CLASSES[btnClassId]) {
case 'shift':
case 'shift-on':
if(flag === undefined) {
flag = OSKKey.BUTTON_CLASSES[btnClassId] == 'shift';
}
this.spec['sp'] = 1 + (flag ? 1 : 0);
break;
// Added in 15.0: special key highlight toggling.
// Was _intended_ in earlier versions, but not actually implemented.
case 'special':
case 'special-on':
if(flag === undefined) {
flag = OSKKey.BUTTON_CLASSES[btnClassId] == 'special';
}
this.spec['sp'] = 3 + (flag ? 1 : 0);
break;
default:
return;
}
if(classAsString) {
// KMW currently doesn't handle raw numbers for 'sp' properly.
this.spec['sp'] = ('' + this.spec['sp']) as keyboards.ButtonClass;
}
this.setButtonClass();
}
// "Frame key" - generally refers to non-linguistic keys on the keyboard
public isFrameKey(): boolean {
let classIndex = this.spec['sp'] || 0;
switch(OSKKey.BUTTON_CLASSES[classIndex]) {
case 'default':
case 'deadkey':
// Note: will (generally) include the spacebar.
return false;
default:
return true;
}
}
public allowsKeyTip(): boolean {
if(this.isFrameKey()) {
return false;
} else {
return !this.btn.classList.contains('kmw-spacebar');
}
}
public highlight(on: boolean) {
var classes=this.btn.classList;
if(on) {
if(!classes.contains(OSKKey.HIGHLIGHT_CLASS)) {
classes.add(OSKKey.HIGHLIGHT_CLASS);
}
} else {
classes.remove(OSKKey.HIGHLIGHT_CLASS);
}
}
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* @param {String} text The text to be rendered.
* @param {String} style The CSSStyleDeclaration for an element to measure against, without modification.
*
* @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
* This version has been substantially modified to work for this particular application.
*/
static getTextMetrics(text: string, emScale: number, style: {fontFamily?: string, fontSize: string}): TextMetrics {
// Since we may mutate the incoming style, let's make sure to copy it first.
// Only the relevant properties, though.
style = {
fontFamily: style.fontFamily,
fontSize: style.fontSize
};
// A final fallback - having the right font selected makes a world of difference.
if(!style.fontFamily) {
style.fontFamily = getComputedStyle(document.body).fontFamily;
}
if(!style.fontSize || style.fontSize == "") {
style.fontSize = '1em';
}
let fontFamily = style.fontFamily;
let fontSpec = getFontSizeStyle(style.fontSize);
var fontSize: string;
if(fontSpec.absolute) {
// We've already got an exact size - use it!
fontSize = fontSpec.val + 'px';
} else {
fontSize = fontSpec.val * emScale + 'px';
}
// re-use canvas object for better performance
var canvas: HTMLCanvasElement = OSKKey.getTextMetrics['canvas'] ||
(OSKKey.getTextMetrics['canvas'] = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = fontSize + " " + fontFamily;
var metrics = context.measureText(text);
return metrics;
}
getIdealFontSize(vkbd: VisualKeyboard, style: {height?: string, fontFamily?: string, fontSize: string}): string {
let buttonStyle = getComputedStyle(this.btn);
let keyWidth = parseFloat(buttonStyle.width);
let emScale = 1;
const originalSize = getFontSizeStyle(style.fontSize || '1em');
// Not yet available; it'll be handled in a later layout pass.
if(!buttonStyle.fontSize) {
// NOTE: preserves old behavior for use in documentation keyboards, for now.
// Once we no longer need to maintain this code block, we can drop all current
// method parameters safely.
//
// Recompute the new width for use in autoscaling calculations below, just in case.
emScale = vkbd.getKeyEmFontSize();
keyWidth = this.getKeyWidth(vkbd);
} else {
// When available, just use computedStyle instead.
style = buttonStyle;
}
let fontSpec = getFontSizeStyle(style.fontSize || '1em');
let metrics = OSKKey.getTextMetrics(this.spec.text, emScale, style);
const MAX_X_PROPORTION = 0.90;
const MAX_Y_PROPORTION = 0.90;
const X_PADDING = 2;
const Y_PADDING = 2;
var fontHeight: number, keyHeight: number;
if(metrics.fontBoundingBoxAscent) {
fontHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;
}
let textHeight = fontHeight ? fontHeight + Y_PADDING : 0;
if(style.height && style.height.indexOf('px') != -1) {
keyHeight = Number.parseFloat(style.height.substring(0, style.height.indexOf('px')));
}
let xProportion = (keyWidth * MAX_X_PROPORTION) / (metrics.width + X_PADDING); // How much of the key does the text want to take?
let yProportion = textHeight && keyHeight ? (keyHeight * MAX_Y_PROPORTION) / textHeight : undefined;
var proportion: number = xProportion;
if(yProportion && yProportion < xProportion) {
proportion = yProportion;
}
// Never upscale keys past the default - only downscale them.
// Proportion < 1: ratio of key width to (padded [loosely speaking]) text width
// maxProportion determines the 'padding' involved.
//
if(proportion < 1) {
if(originalSize.absolute) {
return proportion * fontSpec.val + 'px';
} else {
return proportion * originalSize.val + 'em';
}
} else {
if(originalSize.absolute) {
return fontSpec.val + 'px';
} else {
return originalSize.val + 'em';
}
}
}
getKeyWidth(vkbd: VisualKeyboard): number {
let key = this.spec as keyboards.ActiveKey;
return key.proportionalWidth * vkbd.width;
}
/**
* Replace default key names by special font codes for modifier keys
*
* @param {string} oldText
* @return {string}
**/
protected renameSpecialKey(oldText: string, vkbd: VisualKeyboard): string {
// If a 'special key' mapping exists for the text, replace it with its corresponding special OSK character.
switch(oldText) {
case '*ZWNJ*':
// Default ZWNJ symbol comes from iOS. We'd rather match the system defaults where
// possible / available though, and there's a different standard symbol on Android.
oldText = vkbd.device.OS == com.keyman.utils.OperatingSystem.Android ?
'*ZWNJAndroid*' :
'*ZWNJiOS*';
break;
case '*Enter*':
oldText = vkbd.isRTL ? '*RTLEnter*' : '*LTREnter*';
break;
case '*BkSp*':
oldText = vkbd.isRTL ? '*RTLBkSp*' : '*LTRBkSp*';
break;
default:
// do nothing.
}
let specialCodePUA = 0XE000 + VisualKeyboard.specialCharacters[oldText];
return VisualKeyboard.specialCharacters[oldText] ?
String.fromCharCode(specialCodePUA) :
oldText;
}
private unicodeKeyIdToString(id: string): string {
// This is similar to defaultOutput.ts:forUnicodeKeynames and could potentially
// be refactored in the future.
if(!id || id.substr(0,2) != 'U_') {
return null;
}
let result = '';
const codePoints = id.substr(2).split('_');
for(let codePoint of codePoints) {
const codePointValue = parseInt(codePoint, 16);
if (((0x0 <= codePointValue) && (codePointValue <= 0x1F)) || ((0x80 <= codePointValue) && (codePointValue <= 0x9F))) {
continue;
} else {
// String.fromCharCode() is inadequate to handle the entire range of Unicode
// Someday after upgrading to ES2015, can use String.fromCodePoint()
result += String.kmwFromCharCode(codePointValue);
}
}
return result ? result : null;
}
// Produces a HTMLSpanElement with the key's actual text.
protected generateKeyText(vkbd: VisualKeyboard): HTMLSpanElement {
let spec = this.spec;
// Add OSK key labels
var keyText;
var t = document.createElement('span'), ts=t.style;
if(spec['text'] == null || spec['text'] == '') {
keyText='\xa0'; // default: nbsp.
if(typeof spec['id'] == 'string') {
// If the ID's Unicode-based, just use that code.
keyText = this.unicodeKeyIdToString(spec['id']) || keyText;
}
} else {
keyText=spec['text'];
// Unique layer-based transformation: SHIFT-TAB uses a different glyph.
if(keyText == '*Tab*' && this.layer == 'shift') {
keyText = '*TabLeft*';
}
}
t.className='kmw-key-text';
let specialText = this.renameSpecialKey(keyText, vkbd);
if(specialText != keyText) {
// The keyboard wants to use the code for a special glyph defined by the SpecialOSK font.
keyText = specialText;
spec['font'] = "SpecialOSK";
}
//Override font spec if set for this key in the layout
if(typeof spec['font'] == 'string' && spec['font'] != '') {
ts.fontFamily=spec['font'];
}
if(typeof spec['fontsize'] == 'string' && spec['fontsize'] != '') {
ts.fontSize=spec['fontsize'];
}
// For some reason, fonts will sometimes 'bug out' for the embedded iOS page if we
// instead assign fontFamily to the existing style 'ts'. (Occurs in iOS 12.)
let styleSpec: {fontFamily?: string, fontSize: string} = {fontSize: ts.fontSize};
if(ts.fontFamily) {
styleSpec.fontFamily = ts.fontFamily;
} else {
styleSpec.fontFamily = vkbd.fontFamily; // Helps with style sheet calculations.
}
// Check the key's display width - does the key visualize well?
let emScale = vkbd.getKeyEmFontSize();
var width: number = OSKKey.getTextMetrics(keyText, emScale, styleSpec).width;
if(width == 0 && keyText != '' && keyText != '\xa0') {
// Add the Unicode 'empty circle' as a base support for needy diacritics.
// Disabled by mcdurdin 2020-10-19; dotted circle display is inconsistent on iOS/Safari
// at least and doesn't combine with diacritic marks. For consistent display, it may be
// necessary to build a custom font that does not depend on renderer choices for base
// mark display -- e.g. create marks with custom base included, potentially even on PUA
// code points and use those in rendering the OSK. See #3039 for more details.
// keyText = '\u25cc' + keyText;
if(vkbd.isRTL) {
// Add the RTL marker to ensure it displays properly.
keyText = '\u200f' + keyText;
}
}
ts.fontSize = this.getIdealFontSize(vkbd, styleSpec);
// Finalize the key's text.
t.innerText = keyText;
return t;
}
public isUnderTouch(input: InputEventCoordinate): boolean {
let x = input.x;
let y = input.y;
let btn = this.btn;
// These functions do not account for 'fixed' positioning.
let x0 = dom.Utils.getAbsoluteX(btn);
let y0 = dom.Utils.getAbsoluteY(btn);
let isFixed = false;
let node: HTMLElement = btn;
while(node) {
if(getComputedStyle(node).position == 'fixed') {
isFixed = true;
break;
} else {
node = node.offsetParent as HTMLElement;
}
}
if(isFixed) {
x0 += window.pageXOffset;
y0 += window.pageYOffset;
}
let x1 = x0 + btn.offsetWidth;
let y1 = y0 + btn.offsetHeight;
return (x > x0 && x < x1 && y > y0 && y < y1);
}
public refreshLayout(vkbd: VisualKeyboard) {
if(this.label) { // space bar may not define the text span!
this.label.style.fontSize = this.getIdealFontSize(vkbd, this.btn.style);
}
}
}
} | the_stack |
import type { KVS, KVSOptions, StoreNames, StoreValue } from "@kvs/types";
import type { JsonValue } from "@kvs/storage";
const debug = {
enabled: false,
log(...args: any[]) {
if (!debug.enabled) {
return;
}
console.log(...args);
}
};
const openDB = ({
name,
version,
tableName,
onUpgrade
}: {
name: string;
version: number;
tableName: string;
onUpgrade: ({
oldVersion,
newVersion,
database
}: {
oldVersion: number;
newVersion: number;
database: IDBDatabase;
}) => any;
}): Promise<IDBDatabase> => {
return new Promise((resolve, reject) => {
const openRequest = indexedDB.open(name, version);
openRequest.onupgradeneeded = function (event) {
const oldVersion = event.oldVersion;
const newVersion = event.newVersion ?? version;
const database = openRequest.result;
try {
// create table at first time
if (!newVersion || newVersion <= 1) {
database.createObjectStore(tableName);
}
} catch (e) {
reject(e);
}
// for drop instance
// https://github.com/w3c/IndexedDB/issues/78
// https://www.w3.org/TR/IndexedDB/#introduction
database.onversionchange = () => {
database.close();
};
// @ts-ignore
event.target.transaction.oncomplete = () => {
Promise.resolve(
onUpgrade({
oldVersion,
newVersion,
database
})
).then(() => {
return resolve(database);
});
};
};
openRequest.onblocked = () => {
reject(openRequest.error);
};
openRequest.onerror = function () {
reject(openRequest.error);
};
openRequest.onsuccess = function () {
const db = openRequest.result;
resolve(db);
};
});
};
const dropInstance = (database: IDBDatabase, databaseName: string): Promise<void> => {
return new Promise((resolve, reject) => {
database.close();
const request = indexedDB.deleteDatabase(databaseName);
request.onupgradeneeded = (event) => {
event.preventDefault();
resolve();
};
request.onblocked = () => {
debug.log("dropInstance:blocked", request);
reject(request.error);
};
request.onerror = function () {
debug.log("dropInstance:error", request);
reject(request.error);
};
request.onsuccess = function () {
resolve();
};
});
};
const getItem = <Schema extends KVSIndexedSchema>(
database: IDBDatabase,
tableName: string,
key: StoreNames<Schema>
): Promise<StoreValue<Schema, StoreNames<Schema>>> => {
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readonly");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.get(String(key));
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
reject(request.error);
};
});
};
const hasItem = async <Schema extends KVSIndexedSchema>(
database: IDBDatabase,
tableName: string,
key: StoreNames<Schema>
): Promise<boolean> => {
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readonly");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.count(String(key));
request.onsuccess = () => {
resolve(request.result !== 0);
};
request.onerror = () => {
reject(request.error);
};
});
};
const setItem = async <Schema extends KVSIndexedSchema>(
database: IDBDatabase,
tableName: string,
key: StoreNames<Schema>,
value: StoreValue<Schema, StoreNames<Schema>> | undefined
): Promise<void> => {
// If the value is undefined, delete the key
// This behavior aim to align localStorage implementation
if (value === undefined) {
await deleteItem<Schema>(database, tableName, key);
return;
}
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readwrite");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.put(value, String(key));
transaction.oncomplete = () => {
resolve();
};
transaction.onabort = () => {
reject(request.error ? request.error : transaction.error);
};
transaction.onerror = () => {
reject(request.error ? request.error : transaction.error);
};
});
};
const deleteItem = async <Schema extends KVSIndexedSchema>(
database: IDBDatabase,
tableName: string,
key: StoreNames<Schema>
): Promise<void> => {
return new Promise<void>((resolve, reject) => {
const transaction = database.transaction(tableName, "readwrite");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.delete(String(key));
transaction.oncomplete = () => {
resolve();
};
transaction.onabort = () => {
reject(request.error ? request.error : transaction.error);
};
transaction.onerror = () => {
reject(request.error ? request.error : transaction.error);
};
});
};
const clearItems = async (database: IDBDatabase, tableName: string): Promise<void> => {
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readwrite");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.clear();
transaction.oncomplete = () => {
resolve();
};
transaction.onabort = () => {
reject(request.error ? request.error : transaction.error);
};
transaction.onerror = () => {
reject(request.error ? request.error : transaction.error);
};
});
};
const iterator = <Schema extends KVSIndexedSchema, K extends StoreNames<Schema>, V extends StoreValue<Schema, K>>(
database: IDBDatabase,
tableName: string
): AsyncIterator<[K, V]> => {
const handleCursor = <T>(request: IDBRequest<T | null>): Promise<{ done: boolean; value?: T }> => {
return new Promise((resolve, reject) => {
request.onsuccess = () => {
const cursor = request.result;
if (!cursor) {
return resolve({
done: true
});
}
return resolve({
done: false,
value: cursor
});
};
request.onerror = () => {
reject(request.error);
};
});
};
const transaction = database.transaction(tableName, "readonly");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.openCursor();
return {
async next() {
const { done, value } = await handleCursor(request);
if (!done) {
const storageKey = value?.key as K;
const storageValue = value?.value as V;
value?.continue();
return { done: false, value: [storageKey, storageValue] };
}
return { done: true, value: undefined };
}
};
};
type IndexedDBOptions = {
tableName?: string;
debug?: boolean;
};
type IndexedDBResults = {
dropInstance(): Promise<void>;
__debug__database__: IDBDatabase;
};
interface StoreOptions {
database: IDBDatabase;
databaseName: string;
tableName: string;
}
const createStore = <Schema extends KVSIndexedSchema>({
database,
databaseName,
tableName
}: StoreOptions): KVSIndexedDB<Schema> => {
const store: KVSIndexedDB<Schema> = {
delete(key: StoreNames<Schema>): Promise<boolean> {
return deleteItem<Schema>(database, tableName, key).then(() => true);
},
get<K extends StoreNames<Schema>>(key: K): Promise<StoreValue<Schema, K> | undefined> {
return getItem<Schema>(database, tableName, key);
},
has(key: StoreNames<Schema>): Promise<boolean> {
return hasItem(database, tableName, key);
},
set<K extends StoreNames<Schema>>(key: K, value: StoreValue<Schema, K>) {
return setItem<Schema>(database, tableName, key, value).then(() => store);
},
clear(): Promise<void> {
return clearItems(database, tableName);
},
dropInstance(): Promise<void> {
return dropInstance(database, databaseName);
},
close() {
return Promise.resolve().then(() => {
database.close();
});
},
[Symbol.asyncIterator]() {
return iterator(database, tableName);
},
__debug__database__: database
};
return store;
};
export type KVSIndexedSchema = {
[index: string]: JsonValue;
};
export type KVSIndexedDB<Schema extends KVSIndexedSchema> = KVS<Schema> & IndexedDBResults;
export type KvsIndexedDBOptions<Schema extends KVSIndexedSchema> = KVSOptions<Schema> & IndexedDBOptions;
export const kvsIndexedDB = async <Schema extends KVSIndexedSchema>(
options: KvsIndexedDBOptions<Schema>
): Promise<KVSIndexedDB<Schema>> => {
const { name, version, upgrade, ...indexDBOptions } = options;
if (indexDBOptions.debug) {
debug.enabled = indexDBOptions.debug;
}
const tableName = indexDBOptions.tableName ?? "kvs";
const database = await openDB({
name,
version,
tableName,
onUpgrade: ({ oldVersion, newVersion, database }) => {
if (!upgrade) {
return;
}
return upgrade({
kvs: createStore({ database: database, tableName: tableName, databaseName: name }),
oldVersion,
newVersion
});
}
});
return createStore({ database: database, tableName: tableName, databaseName: name });
}; | the_stack |
/*global renderingCommonGetTechniqueIndexFn: false*/
/*global Effect: false*/
/*global VertexBufferManager: false*/
/*global Geometry: false*/
/*global Reference: false*/
/*exported loadCustomFileShapeFn*/
//
// loadCustomFileShapeFn
//
/* tslint:disable:no-unused-variable */
var loadCustomFileShape = function loadCustomFileShapeFn(shapeName, shape, fileShape, loadParams)
/* tslint:enable:no-unused-variable */
{
//
// Custom geometry loading function:
//
// This function is a custom implementation to load shape data in a way
// that supports our custom geometry type, in this case morph targets
//
// Differences from standard geometry loading function:
//
// * Optional use of vertexBufferManager (allows vertexBuffer per shape)
// * Custom shape is passed as an argument to the function
var cachedSemantics = [];
var graphicsDevice = loadParams.graphicsDevice;
var dynamicVertexBuffers = false || (loadParams.dynamicVertexBuffers);
var useVertexBufferManager = false || (loadParams.useVertexBufferManager);
var sources = fileShape.sources;
var inputs = fileShape.inputs;
if (graphicsDevice)
{
// First calculate data about the vertex streams
var offset, stride;
var maxOffset = 0;
var vertexSources = [];
for (var input in inputs)
{
if (inputs.hasOwnProperty(input))
{
var fileInput = inputs[input];
offset = fileInput.offset;
if (offset > maxOffset)
{
maxOffset = offset;
}
var fileSource = sources[fileInput.source];
vertexSources.push({
semantic: input,
offset: offset,
data: fileSource.data,
stride: fileSource.stride
});
}
}
var indicesPerVertex = (maxOffset + 1);
if (0 < maxOffset)
{
var vertexSourcesCompare = function (vertexSourceA, vertexSourceB)
{
return (vertexSourceA.offset - vertexSourceB.offset);
};
vertexSources.sort(vertexSourcesCompare);
}
var numVertexSources = vertexSources.length;
var semanticsNames = [];
var attributes = [];
var vs, vertexSource;
for (vs = 0; vs < numVertexSources; vs += 1)
{
vertexSource = vertexSources[vs];
semanticsNames[vs] = vertexSource.semantic;
attributes[vs] = ("FLOAT" + vertexSource.stride);
}
// Now parse the surfaces to work out primitive types and the total vertex count
var numVertices, totalNumVertices = 0;
var noSurfaces = false;
var surfaces = fileShape.surfaces;
if (!surfaces)
{
noSurfaces = true;
surfaces = {
singleSurface: {
triangles: fileShape.triangles,
lines: fileShape.lines,
numPrimitives: fileShape.numPrimitives
}
};
}
var vertexBufferManager = (loadParams.vertexBufferManager || this.vertexBufferManager);
if (!vertexBufferManager)
{
vertexBufferManager = VertexBufferManager.create(graphicsDevice);
this.vertexBufferManager = vertexBufferManager;
}
var surface;
var destSurface;
var faces;
for (var s in surfaces)
{
if (surfaces.hasOwnProperty(s))
{
surface = surfaces[s];
destSurface = {};
shape.surfaces[s] = destSurface;
faces = surface.triangles;
var primitive, vertexPerPrimitive;
if (faces)
{
primitive = graphicsDevice.PRIMITIVE_TRIANGLES;
vertexPerPrimitive = 3;
}
else
{
faces = surface.lines;
if (faces)
{
primitive = graphicsDevice.PRIMITIVE_LINES;
vertexPerPrimitive = 2;
}
}
destSurface.primitive = primitive;
destSurface.faces = faces;
if (faces)
{
if (1 < indicesPerVertex)
{
numVertices = (surface.numPrimitives * vertexPerPrimitive);
destSurface.numVertices = numVertices;
}
else
{
numVertices = (vertexSources[0].data.length / vertexSources[0].stride);
if (numVertices > faces.length)
{
numVertices = faces.length;
}
}
totalNumVertices += numVertices;
}
}
}
var baseIndex;
var vertexbuffer = null;
if (useVertexBufferManager)
{
// Use the vertexBufferManager to allocate a static buffer
var vertexBufferAllocation = vertexBufferManager.allocate(totalNumVertices, attributes);
vertexbuffer = vertexBufferAllocation.vertexBuffer;
if (!vertexbuffer)
{
return undefined;
}
shape.vertexBuffer = vertexbuffer;
shape.vertexBufferManager = vertexBufferManager;
shape.vertexBufferAllocation = vertexBufferAllocation;
baseIndex = vertexBufferAllocation.baseIndex;
}
else
{
// Create a new vertexBuffer for the shape
var vertexbufferParameters =
{
attributes: attributes,
numVertices: totalNumVertices,
dynamic: dynamicVertexBuffers
};
vertexbuffer = graphicsDevice.createVertexBuffer(vertexbufferParameters);
if (!vertexbuffer)
{
return undefined;
}
shape.vertexBuffer = vertexbuffer;
baseIndex = 0;
}
for (s in surfaces)
{
if (surfaces.hasOwnProperty(s))
{
surface = surfaces[s];
destSurface = shape.surfaces[s];
var indexbuffer = null;
var numIndices;
var writer, write;
var data = [];
var sourceData;
var t, i, n;
var nextIndex, index;
var firstVertex = baseIndex;
faces = destSurface.faces;
delete destSurface.faces;
if (faces)
{
if (1 < indicesPerVertex)
{
numVertices = destSurface.numVertices;
var maxSurfaceOffset = (faces.length / numVertices);
writer = vertexbuffer.map(baseIndex, numVertices);
if (writer)
{
write = (writer.write || writer);
if (maxSurfaceOffset === numVertexSources)
{
for (t = 0, i = 0; t < numVertices; t += 1)
{
n = 0;
vs = 0;
do
{
vertexSource = vertexSources[vs];
sourceData = vertexSource.data;
stride = vertexSource.stride;
index = (faces[i] * stride);
nextIndex = (index + stride);
do
{
data[n] = sourceData[index];
n += 1;
index += 1;
}
while (index < nextIndex);
vs += 1;
i += 1;
}
while (vs < numVertexSources);
write.apply(writer, data);
}
}
else
{
for (t = 0, i = 0; t < numVertices; t += 1)
{
n = 0;
vs = 0;
do
{
vertexSource = vertexSources[vs];
sourceData = vertexSource.data;
stride = vertexSource.stride;
offset = vertexSource.offset;
if (offset < maxSurfaceOffset)
{
index = (faces[i + offset] * stride);
nextIndex = (index + stride);
do
{
data[n] = sourceData[index];
n += 1;
index += 1;
}
while (index < nextIndex);
}
else
{
nextIndex = (n + stride);
do
{
data[n] = 0;
n += 1;
}
while (n < nextIndex);
}
vs += 1;
}
while (vs < numVertexSources);
write.apply(writer, data);
i += maxSurfaceOffset;
}
}
vertexbuffer.unmap(writer);
baseIndex += numVertices;
write = null;
writer = null;
}
}
else
{
numIndices = faces.length;
numVertices = (vertexSources[0].data.length / vertexSources[0].stride);
// extract data
if (numVertices === 4 && numIndices === 6 && surface.triangles)
{
destSurface.primitive = graphicsDevice.PRIMITIVE_TRIANGLE_STRIP;
numIndices = 4;
if (faces[3] !== 0 && faces[4] !== 0 && faces[5] !== 0)
{
faces = [0, 2, 1, 3];
}
else if (faces[3] !== 1 && faces[4] !== 1 && faces[5] !== 1)
{
faces = [1, 0, 2, 3];
}
else //if (faces[3] !== 2 && faces[4] !== 2 && faces[5] !== 2)
{
faces = [3, 0, 1, 2];
}
writer = vertexbuffer.map(baseIndex, 4);
if (writer)
{
write = (writer.write || writer);
for (i = 0; i < numIndices; i += 1)
{
n = 0;
vs = 0;
do
{
vertexSource = vertexSources[vs];
sourceData = vertexSource.data;
stride = vertexSource.stride;
index = (faces[i] * stride);
nextIndex = (index + stride);
do
{
data[n] = sourceData[index];
n += 1;
index += 1;
}
while (index < nextIndex);
vs += 1;
}
while (vs < numVertexSources);
write.apply(writer, data);
}
vertexbuffer.unmap(writer);
baseIndex += 4;
write = null;
writer = null;
}
}
else if (numVertices < numIndices)
{
writer = vertexbuffer.map(baseIndex, numVertices);
if (writer)
{
write = (writer.write || writer);
for (t = 0; t < numVertices; t += 1)
{
n = 0;
vs = 0;
do
{
vertexSource = vertexSources[vs];
sourceData = vertexSource.data;
stride = vertexSource.stride;
index = (t * stride);
nextIndex = (index + stride);
do
{
data[n] = sourceData[index];
n += 1;
index += 1;
}
while (index < nextIndex);
vs += 1;
}
while (vs < numVertexSources);
write.apply(writer, data);
}
baseIndex += numVertices;
vertexbuffer.unmap(writer);
write = null;
writer = null;
}
var indexbufferParameters =
{
numIndices: numIndices,
format: ((firstVertex + numVertices) <= 65536 ? 'USHORT' : 'UINT'),
dynamic: false
};
indexbuffer = graphicsDevice.createIndexBuffer(indexbufferParameters);
if (!indexbuffer)
{
window.alert("IndexBuffer not created.");
}
writer = indexbuffer.map();
if (writer)
{
if (0 !== firstVertex)
{
if (surface.triangles)
{
for (t = 0; t < numIndices; t += 3)
{
writer(faces[t + 0] + firstVertex,
faces[t + 1] + firstVertex,
faces[t + 2] + firstVertex);
}
}
else //if (surface.lines)
{
for (t = 0; t < numIndices; t += 2)
{
writer(faces[t + 0] + firstVertex, faces[t + 1] + firstVertex);
}
}
}
else
{
if (surface.triangles)
{
for (t = 0; t < numIndices; t += 3)
{
writer(faces[t + 0], faces[t + 1], faces[t + 2]);
}
}
else //if (surface.lines)
{
for (t = 0; t < numIndices; t += 2)
{
writer(faces[t + 0], faces[t + 1]);
}
}
}
indexbuffer.unmap(writer);
writer = null;
}
}
else
{
numVertices = numIndices;
writer = vertexbuffer.map(baseIndex, numVertices);
if (writer)
{
write = (writer.write || writer);
for (i = 0; i < numIndices; i += 1)
{
n = 0;
vs = 0;
do
{
vertexSource = vertexSources[vs];
sourceData = vertexSource.data;
stride = vertexSource.stride;
index = (faces[i] * stride);
nextIndex = (index + stride);
do
{
data[n] = sourceData[index];
n += 1;
index += 1;
}
while (index < nextIndex);
vs += 1;
}
while (vs < numVertexSources);
write.apply(writer, data);
}
vertexbuffer.unmap(writer);
baseIndex += numVertices;
write = null;
writer = null;
}
}
}
if (indexbuffer)
{
destSurface.indexBuffer = indexbuffer;
destSurface.numIndices = numIndices;
}
else
{
destSurface.numVertices = numVertices;
destSurface.first = firstVertex;
}
}
else
{
delete shape.surfaces[s];
}
}
}
var semanticsHash = semanticsNames.join();
var semantics = cachedSemantics[semanticsHash];
if (!semantics)
{
semantics = graphicsDevice.createSemantics(semanticsNames);
cachedSemantics[semanticsHash] = semantics;
}
shape.semantics = semantics;
shape.semanticsNames = semanticsNames;
if (noSurfaces)
{
surface = shape.surfaces.singleSurface;
if (surface)
{
shape.primitive = surface.primitive;
if (surface.indexBuffer)
{
shape.indexBuffer = surface.indexBuffer;
shape.numIndices = surface.numIndices;
}
else
{
shape.numVertices = surface.numVertices;
shape.first = surface.first;
}
}
delete shape.surfaces;
}
}
if (inputs.POSITION)
{
var positions = sources[inputs.POSITION.source];
var minPos = positions.min;
var maxPos = positions.max;
if (minPos && maxPos)
{
var min0 = minPos[0];
var min1 = minPos[1];
var min2 = minPos[2];
var max0 = maxPos[0];
var max1 = maxPos[1];
var max2 = maxPos[2];
if (min0 !== -max0 || min1 !== -max1 || min2 !== -max2)
{
var c0 = (min0 + max0) * 0.5;
var c1 = (min1 + max1) * 0.5;
var c2 = (min2 + max2) * 0.5;
shape.center = [c0, c1, c2];
shape.halfExtents = [(max0 - c0), (max1 - c1), (max2 - c2)];
}
else
{
shape.halfExtents = [(max0 - min0) * 0.5, (max1 - min1) * 0.5, (max2 - min2) * 0.5];
}
}
}
shape.name = shapeName;
shape.reference.subscribeDestroyed(loadParams.onGeometryDestroyed);
return shape;
};
//
// MorphShape
//
class MorphShape extends Geometry
{
initialWeight: number;
//
// MorphShape Constructor
//
static create(initialWeight?): MorphShape
{
var m = <MorphShape>(Geometry.create());
m.initialWeight = initialWeight;
return m;
}
}
//
// Morph
//
class Morph
{
version = 1;
//The maximum number of morphShapes supported (baseShape + shapes)
maxMorphs = 4;
// Creates the mapping for semantics in file to sematics for the
// morph shader
semanticMap = {
POSITION : [ "ATTR0", "ATTR10", "ATTR12", "ATTR14" ],
NORMAL : [ "ATTR2", "ATTR11", "ATTR13", "ATTR15" ],
TEXCOORD : [ "ATTR8", "ATTR7", "ATTR6", "ATTR5" ],
POSITION0 : [ "ATTR0", "ATTR10", "ATTR12", "ATTR14" ],
NORMAL0 : [ "ATTR2", "ATTR11", "ATTR13", "ATTR15" ],
TEXCOORD0 : [ "ATTR8", "ATTR7", "ATTR6", "ATTR5" ]
};
// Lists the attributes, not used by the shader
remainingAttributes = [ "ATTR1", "ATTR3", "ATTR9"];
// Members
reference: Reference;
baseShape: Geometry;
halfExtents: any; // AABB
center: any; // v3
type: string;
semanticsNamesArray: string[];
shapes: Geometry[];
//
// addShapes
//
addShapes(morphShapes)
{
var result = false;
if (this.generateSemanticsNames(morphShapes))
{
this.shapes = morphShapes;
result = true;
}
return result;
}
//
// generateSemanticsNames
//
generateSemanticsNames(shapes)
{
var baseShape = this.baseShape;
var shapesLen = shapes.length;
var maxMorphs = this.maxMorphs;
var maxTargetShapes = (shapesLen < maxMorphs) ? shapesLen + 1 : maxMorphs;
var semanticsNamesArray = [];
var semanticMap = this.semanticMap;
var remainingAttributes = this.remainingAttributes;
function mapSematicNamesFn(semanticName, index)
{
var mappedNames = semanticMap[semanticName];
if (mappedNames)
{
return mappedNames[index];
}
return null;
}
var inputs, input, semanticsNames, semanticsNamesLen, mappedName, shape, mappedNames;
var remainingAttributesLen, lastRemainingAttribute;
for (var i = 0; i < maxTargetShapes; i += 1)
{
shape = (i === 0) ? baseShape : shapes[i - 1];
semanticsNames = shape.semanticsNames;
mappedNames = [];
lastRemainingAttribute = 0;
if (!semanticsNames)
{
semanticsNames = [];
inputs = shape.inputs;
for (input in inputs)
{
if (inputs.hasOwnProperty(input))
{
semanticsNames[semanticsNames.length] = input;
}
}
}
semanticsNamesLen = semanticsNames.length;
for (var j = 0; j < semanticsNamesLen; j += 1)
{
mappedName = mapSematicNamesFn(semanticsNames[j], i);
if (mappedName)
{
mappedNames[mappedNames.length] = mappedName;
}
else
{
// No mapping available, systematically use remaining attributes
// (Since they are ignored by the shader)
remainingAttributesLen = remainingAttributes.length;
if (lastRemainingAttribute < remainingAttributesLen)
{
mappedNames[mappedNames.length] = remainingAttributes[lastRemainingAttribute];
lastRemainingAttribute += 1;
}
else
{
// Fail when no more attributes exist
return false;
}
}
}
semanticsNamesArray[i] = mappedNames;
}
this.semanticsNamesArray = semanticsNamesArray;
return true;
}
getShapeCount()
{
return (this.shapes.length + 1);
}
//
// destroy
//
destroy()
{
delete this.reference;
delete this.baseShape;
delete this.shapes;
delete this.halfExtents;
delete this.center;
delete this.type;
delete this.semanticsNamesArray;
}
//
// Morph Constructor
//
static create(baseShape): Morph
{
var morph = new Morph();
morph.reference = Reference.create(morph);
morph.baseShape = baseShape;
// Assumes that baseShape extents encapsulate all morphed shapes
// To recalculate accurate extents, implement a custom getWorldExtents function
morph.halfExtents = baseShape.halfExtents;
morph.center = baseShape.center;
morph.type = "morph";
return morph;
}
}
//
// MorphInstance
//
class MorphInstance
{
version = 1;
maxUpdateValue = Number.MAX_VALUE;
morph: Morph;
geometryType: string;
halfExtents: any; // AAB
center: any; // v3
techniqueParameters: TechniqueParameters;
sharedMaterial: Material;
worldExtents: any; // AABB = [];
worldUpdate: number;
worldExtentsUpdate: number;
sorting: any; // TODO: is this used?
rendererInfo: any; // TODO: is this used?
renderUpdate: any; // TODO: is this used?
drawParameters: DrawParameters; // TODO: is this used?;
node: SceneNode;
cachedSemantics: { [hash: string]: Semantics; };
semanticsHashes: string[];
disabled: boolean;
//
// clone
//
clone()
{
var newInstance = MorphInstance.create(this.morph, this.sharedMaterial);
newInstance.halfExtents = this.halfExtents.slice();
if (this.center)
{
newInstance.center = this.center.slice();
}
if (this.disabled)
{
newInstance.disabled = true;
}
newInstance.worldExtents = [];
newInstance.worldExtentsUpdate = -1;
return newInstance;
}
//
// setNode
//
setNode(node)
{
if (this.node)
{
if (this.hasCustomWorldExtents())
{
this.node.renderableWorldExtentsRemoved();
}
}
this.node = node;
if (this.node)
{
if (this.hasCustomWorldExtents())
{
this.node.renderableWorldExtentsUpdated(false);
}
}
this.worldExtentsUpdate = -1;
}
//
// getNode
//
getNode()
{
return this.node;
}
//
// setMaterial
//
setMaterial(material)
{
material.reference.add();
this.sharedMaterial.reference.remove();
this.sharedMaterial = material;
this.renderUpdate = undefined;
this.rendererInfo = undefined;
}
//
// getMaterial
//
getMaterial()
{
return this.sharedMaterial;
}
//
// getWorldExtents
//
getWorldExtents()
{
//Note: This method is only valid on a clean node.
var worldExtents = this.worldExtents;
var node = this.node;
if (node.worldUpdate > this.worldExtentsUpdate)
{
this.worldExtentsUpdate = node.worldUpdate;
var center = this.center;
var halfExtents = this.halfExtents;
var world = node.world;
var m0 = world[0];
var m1 = world[1];
var m2 = world[2];
var m3 = world[3];
var m4 = world[4];
var m5 = world[5];
var m6 = world[6];
var m7 = world[7];
var m8 = world[8];
var ct0 = world[9];
var ct1 = world[10];
var ct2 = world[11];
if (center)
{
var c0 = center[0];
var c1 = center[1];
var c2 = center[2];
ct0 += (m0 * c0 + m3 * c1 + m6 * c2);
ct1 += (m1 * c0 + m4 * c1 + m7 * c2);
ct2 += (m2 * c0 + m5 * c1 + m8 * c2);
}
var h0 = halfExtents[0];
var h1 = halfExtents[1];
var h2 = halfExtents[2];
var ht0 = ((m0 < 0 ? -m0 : m0) * h0 + (m3 < 0 ? -m3 : m3) * h1 + (m6 < 0 ? -m6 : m6) * h2);
var ht1 = ((m1 < 0 ? -m1 : m1) * h0 + (m4 < 0 ? -m4 : m4) * h1 + (m7 < 0 ? -m7 : m7) * h2);
var ht2 = ((m2 < 0 ? -m2 : m2) * h0 + (m5 < 0 ? -m5 : m5) * h1 + (m8 < 0 ? -m8 : m8) * h2);
worldExtents[0] = (ct0 - ht0);
worldExtents[1] = (ct1 - ht1);
worldExtents[2] = (ct2 - ht2);
worldExtents[3] = (ct0 + ht0);
worldExtents[4] = (ct1 + ht1);
worldExtents[5] = (ct2 + ht2);
}
return worldExtents;
}
//
// addCustomWorldExtents
//
addCustomWorldExtents(customWorldExtents)
{
this.worldExtents = customWorldExtents.slice();
var alreadyHadCustomExtents = (this.worldExtentsUpdate === this.maxUpdateValue);
this.worldExtentsUpdate = this.maxUpdateValue;
this.node.renderableWorldExtentsUpdated(alreadyHadCustomExtents);
}
//
// removeCustomWorldExtents
//
removeCustomWorldExtents()
{
this.worldExtentsUpdate = -1;
this.node.renderableWorldExtentsRemoved();
}
//
// getCustomWorldExtents
//
getCustomWorldExtents()
{
if (this.worldExtentsUpdate === this.maxUpdateValue)
{
return this.worldExtents;
}
return undefined;
}
//
// hasCustomWorldExtents
//
hasCustomWorldExtents()
{
return this.worldExtentsUpdate === this.maxUpdateValue;
}
//
// destroy
//
destroy()
{
if (this.morph.reference)
{
this.morph.reference.remove();
}
if (this.sharedMaterial.reference)
{
this.sharedMaterial.reference.remove();
}
delete this.morph;
delete this.sharedMaterial;
delete this.techniqueParameters;
delete this.halfExtents;
delete this.center;
delete this.worldExtentsUpdate;
delete this.drawParameters;
delete this.sorting;
delete this.cachedSemantics;
delete this.semanticsHashes;
}
//
// prepareDrawParameters
//
prepareDrawParameters(drawParameters)
{
var morph = this.morph;
var shapeCount = morph.getShapeCount();
var shapes = morph.shapes;
var baseShape = morph.baseShape;
var surfaces = baseShape.surfaces;
var surface;
// Obtains the primitive from the surface on the baseShape.
// Assumes that the primitive is the same for all surfaces
// If different primitive types are used, the shape should be broken down into multiple drawParameters
for (var s in surfaces)
{
if (surfaces.hasOwnProperty(s))
{
surface = surfaces[s];
}
}
var cachedSemantics = this.cachedSemantics;
var semanticsHashes = this.semanticsHashes;
drawParameters.setVertexBuffer(0, morph.baseShape.vertexBuffer);
// If more vertex buffers exist than available semantics,
// multiple semantic configurations can be created and the setSemantics call can be made during the update call
drawParameters.setSemantics(0, cachedSemantics[semanticsHashes[0]]);
for (var i = 1; i < shapeCount; i += 1)
{
drawParameters.setVertexBuffer(i, shapes[i - 1].vertexBuffer);
drawParameters.setSemantics(i, cachedSemantics[semanticsHashes[i]]);
}
drawParameters.primitive = surface.primitive;
if (surface.indexBuffer)
{
drawParameters.indexBuffer = surface.indexBuffer;
drawParameters.count = surface.numIndices;
}
else
{
drawParameters.firstIndex = surface.first;
drawParameters.count = surface.numVertices;
}
}
//
// generateSemantics
//
generateSemantics(graphicsDevice, semanticsNames)
{
var cachedSemantics = this.cachedSemantics;
var semanticsHash = semanticsNames.join();
var semantics = cachedSemantics[semanticsHash];
if (!semantics)
{
semantics = graphicsDevice.createSemantics(semanticsNames);
cachedSemantics[semanticsHash] = semantics;
}
return semanticsHash;
}
setWeights(weights)
{
/* tslint:disable:no-string-literal */
this.techniqueParameters['morphWeights'] = weights;
/* tslint:enable:no-string-literal */
}
//
// registerEffects
//
static registerEffects(mathDevice, renderer, shaderManager, effectManager)
{
var defaultUpdateFn = renderer.defaultUpdateFn;
var effect;
var effectTypeData;
var morph = "morph";
function morphPrepareFn(morphInstance)
{
DefaultRendering.defaultPrepareFn.call(this, morphInstance);
var techniqueParameters = morphInstance.techniqueParameters;
if (!techniqueParameters.morphWeights)
{
techniqueParameters.morphWeights = mathDevice.v3Build(0.0, 0.0, 0.0);
}
}
function loadTechniques(shaderManager)
{
var that = this;
var callback = function shaderLoadedCallbackFn(shader)
{
that.shader = shader;
that.technique = shader.getTechnique(that.techniqueName);
that.techniqueIndex = renderingCommonGetTechniqueIndexFn(that.techniqueName);
};
shaderManager.load(this.shaderName, callback);
}
//
// morph
//
effect = Effect.create("morph");
effectManager.add(effect);
effectTypeData = { prepare : morphPrepareFn,
shaderName : "shaders/morph.cgfx",
techniqueName : "morph",
update : defaultUpdateFn, // Uses the defaultUpdateFn from default renderer
loadTechniques : loadTechniques };
effectTypeData.loadTechniques(shaderManager);
effect.add(morph, effectTypeData);
//
// debug_normals_morph
//
effect = Effect.create("debug_normals_morph");
effectManager.add(effect);
effectTypeData = { prepare : morphPrepareFn,
shaderName : "shaders/morph.cgfx",
techniqueName : "debug_normals_morph",
update : defaultUpdateFn, // Uses the defaultUpdateFn from default renderer
loadTechniques : loadTechniques };
effectTypeData.loadTechniques(shaderManager);
effect.add(morph, effectTypeData);
//
// blinn_morph
//
effect = Effect.create("blinn_morph");
effectManager.add(effect);
effectTypeData = { prepare : morphPrepareFn,
shaderName : "shaders/morph.cgfx",
techniqueName : "blinn_morph",
update : defaultUpdateFn, // Uses the defaultUpdateFn from default renderer
loadTechniques : loadTechniques };
effectTypeData.loadTechniques(shaderManager);
effect.add(morph, effectTypeData);
}
//
// Constructor function
//
static create(morph: Morph, sharedMaterial: Material): MorphInstance
{
var instance = new MorphInstance();
var graphicsDevice = TurbulenzEngine.getGraphicsDevice(); //Maybe null when running on the server.
instance.morph = morph;
instance.morph.reference.add();
instance.geometryType = morph.type;
instance.halfExtents = morph.halfExtents;
instance.center = morph.center;
instance.techniqueParameters = graphicsDevice ? graphicsDevice.createTechniqueParameters() : null;
instance.sharedMaterial = sharedMaterial;
if (instance.sharedMaterial)
{
instance.sharedMaterial.reference.add();
}
instance.worldExtents = [];
instance.worldUpdate = -1;
instance.sorting = {};
instance.cachedSemantics = {};
instance.semanticsHashes = [];
var semanticsNamesArray = morph.semanticsNamesArray;
var semanticsNamesArrayLen = semanticsNamesArray.length;
for (var i = 0; i < semanticsNamesArrayLen; i += 1)
{
instance.semanticsHashes[i] = instance.generateSemantics(graphicsDevice, semanticsNamesArray[i]);
}
return instance;
}
} | the_stack |
import { Injectable } from '@angular/core';
import { BungieService } from '@app/service/bungie.service';
import { Player, SearchResult, SelectedUser, TriumphRecordNode, Platform, Const, InventoryItem, Character } from '@app/service/model';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { StorageService } from '@app/service/storage.service';
import { SignedOnUserService } from '@app/service/signed-on-user.service';
@Injectable({
providedIn: 'root'
})
export class PlayerStateService {
public filterChar: Character|string = null;
public get sort() {
return this._sort;
}
public set sort(val: string) {
this._sort = val;
this._player.next(this._player.getValue());
}
public get showZeroPtTriumphs() {
return this._showZeroPtTriumphs;
}
public set showZeroPtTriumphs(b: boolean) {
this._showZeroPtTriumphs = b;
localStorage.setItem('show-zero-pt-triumphs', '' + this._showZeroPtTriumphs);
this.requestRefresh();
}
public set showInvisTriumphs(b: boolean) {
this._showInvisTriumphs = b;
localStorage.setItem('show-invis-triumphs', '' + this._showInvisTriumphs);
this.requestRefresh();
}
public get showInvisTriumphs() {
return this._showInvisTriumphs;
}
public get hideCompleteCollectibles() {
return this._hideCompleteCollectibles;
}
public set hideCompleteCollectibles(b: boolean) {
this._hideCompleteCollectibles = b;
localStorage.setItem('hide-completed-collectibles', '' + this._hideCompleteCollectibles);
}
public get hideCompleteTriumphs() {
return this._hideCompleteTriumphs;
}
public set hideCompleteTriumphs(b: boolean) {
this._hideCompleteTriumphs = b;
localStorage.setItem('hide-completed-triumphs', '' + this._hideCompleteTriumphs);
}
public get hideCompletePursuits() {
return this._hideCompletePursuits;
}
public set hideCompletePursuits(b: boolean) {
this._hideCompletePursuits = b;
localStorage.setItem('hide-completed-pursuits', '' + this._hideCompletePursuits);
}
private _sort = 'rewardsDesc';
public trackedTriumphs: BehaviorSubject<TriumphRecordNode[]> = new BehaviorSubject([]);
public trackedPursuits: BehaviorSubject<InventoryItem[]> = new BehaviorSubject([]);
private _player: BehaviorSubject<Player> = new BehaviorSubject<Player>(null);
public player: Observable<Player>;
private _loading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public loading: Observable<boolean> = this._loading.asObservable();
public _signedOnUserIsCurrent: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public signedOnUserIsCurrent: Observable<boolean> = this._signedOnUserIsCurrent.asObservable();
public _isSignedOn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public isSignedOn: Observable<boolean> = this._isSignedOn.asObservable();
private _showZeroPtTriumphs = false;
private _showInvisTriumphs = false;
private _hideCompleteTriumphs = false;
private _hideCompletePursuits = false;
private _hideCompleteCollectibles = false;
public dTrackedTriumphIds = {};
public dTrackedPursuits = {};
public currPlayer(): Player {
return this._player.getValue();
}
public requestRefresh() {
const p = this.currPlayer();
const platform = Const.PLATFORMS_DICT['' + p.profile.userInfo.membershipType];
this.loadPlayer(platform, p.profile.userInfo.membershipId, true);
}
public getPlayerRoute(params: any[]): string[] {
const p = this._player.getValue();
const baseRoute = ['/', '' + p.profile.userInfo.membershipType, p.profile.userInfo.membershipId];
return baseRoute.concat(params);
}
public getPlayerRouteString(params: any[]): string {
const p = this._player.getValue();
const baseRoute = ['' + p.profile.userInfo.membershipType, p.profile.userInfo.membershipId];
const entries = baseRoute.concat(params);
let s = entries[0];
for (let i = 1; i < entries.length; i++) {
s += '/' + entries[i];
}
return s;
}
constructor(
private storageService: StorageService,
private signedOnUserService: SignedOnUserService,
private bungieService: BungieService) {
this.player = this._player.pipe(map(val => {
PlayerStateService.sortMileStones(val, this.sort);
return val;
}));
this.signedOnUserService.signedOnUser$.pipe().subscribe((selectedUser: SelectedUser) => {
this._isSignedOn.next(selectedUser != null);
this.checkSignedOnCurrent(this.currPlayer());
});
this._showZeroPtTriumphs = localStorage.getItem('show-zero-pt-triumphs') === 'true';
this._showInvisTriumphs = localStorage.getItem('show-invis-triumphs') === 'true';
this._hideCompleteTriumphs = localStorage.getItem('hide-completed-triumphs') === 'true';
this._hideCompletePursuits = localStorage.getItem('hide-completed-pursuits') === 'true';
this._hideCompleteCollectibles = localStorage.getItem('hide-completed-collectibles') === 'true';
this.storageService.settingFeed.pipe().subscribe(
x => {
if (x.trackedtriumphs != null) {
this.dTrackedTriumphIds = x.trackedtriumphs;
} else {
this.dTrackedTriumphIds = {};
}
this.applyTrackedTriumphs(this._player.getValue());
if (x.trackedpursuits != null) {
this.dTrackedPursuits = x.trackedpursuits;
} else {
this.dTrackedPursuits = {};
}
this.applyTrackedPursuits(this._player.getValue());
});
}
private checkSignedOnCurrent(currentPlayer: Player) {
const a = this.signedOnUserService.signedOnUser$.getValue();
let isCurrent = false;
if (a != null && currentPlayer != null) {
if (currentPlayer.profile.userInfo.membershipId == a.userInfo.membershipId) {
isCurrent = true;
}
}
this._signedOnUserIsCurrent.next(isCurrent);
}
public async loadPlayer(platform: Platform, memberId: string, refresh: boolean): Promise<void> {
this._loading.next(true);
if (!refresh) {
this.filterChar = null;
this._player.next(null);
}
try {
const x = await this.bungieService.getChars(platform.type, memberId,
['Profiles', 'Characters', 'CharacterProgressions', 'CharacterActivities',
'CharacterEquipment', 'ItemInstances', 'CharacterInventories', 'ProfileInventories',
'ProfileProgression', 'ItemObjectives', 'PresentationNodes', 'Records', 'Collectibles', 'ItemSockets', 'ItemPlugObjectives'
// , '1000'
// 'ItemSockets', 'ItemPlugStates','ItemInstances','ItemPerks','ItemStats'
// 'ItemTalentGrids','ItemCommonData','ProfileInventories'
], false, true, this.showZeroPtTriumphs, this.showInvisTriumphs);
if (x == null || x.characters == null) {
throw new Error('No valid destiny player found for ' + memberId + ' on ' + platform.name);
}
this.checkSignedOnCurrent(x);
this.applyTrackedTriumphs(x);
this.applyTrackedPursuits(x);
x.milestoneList.sort((a, b) => {
if (a.boost.sortVal < b.boost.sortVal) { return 1; }
if (a.boost.sortVal > b.boost.sortVal) { return -1; }
if (a.rewards < b.rewards) { return 1; }
if (a.rewards > b.rewards) { return -1; }
if (a.name > b.name) { return 1; }
if (a.name < b.name) { return -1; }
return 0;
});
if (x.characters && x.characters.length > 0) {
this.filterChar = x.characters[0];
} else {
this.filterChar = null;
}
this._player.next(x);
// this.bungieService.loadWeeklyPowerfulBounties(this._player);
// this.bungieService.observeUpdatePvpStreak(this._player);
// this.bungieService.observeUpdateAggHistoryAndScores(this._player, this.storageService.isDebug());
this.bungieService.loadClans(this._player);
// this.bungieService.loadActivityPseudoMilestones(this._player);
this.bungieService.observeUpdateAggHistory(this._player, this.storageService.isDebug());
}
finally {
this._loading.next(false);
}
}
public static sortMileStones(player: Player, sort: string): Player {
if (player == null || player.milestoneList == null) { return; }
if (sort === 'rewardsDesc') {
player.milestoneList.sort((a, b) => {
if (a.boost.sortVal < b.boost.sortVal) { return 1; }
if (a.boost.sortVal > b.boost.sortVal) { return -1; }
if (a.rewards < b.rewards) { return 1; }
if (a.rewards > b.rewards) { return -1; }
if (a.name > b.name) { return 1; }
if (a.name < b.name) { return -1; }
return 0;
});
} else if (sort === 'rewardsAsc') {
player.milestoneList.sort((a, b) => {
if (a.boost.sortVal < b.boost.sortVal) { return -1; }
if (a.boost.sortVal > b.boost.sortVal) { return 1; }
if (a.rewards < b.rewards) { return -1; }
if (a.rewards > b.rewards) { return 1; }
if (a.name > b.name) { return 1; }
if (a.name < b.name) { return -1; }
return 0;
});
} else if (sort === 'resetDesc') {
player.milestoneList.sort((a, b) => {
if (a.resets == null && b.resets != null) { return 1; }
if (a.resets != null && b.resets == null) { return -1; }
if (a.resets == null && b.resets == null) { return 0; }
if (a.resets < b.resets) { return 1; }
if (a.resets > b.resets) { return -1; }
if (a.name > b.name) { return 1; }
if (a.name < b.name) { return -1; }
return 0;
});
} else if (sort === 'resetAsc') {
player.milestoneList.sort((a, b) => {
if (a.resets == null && b.resets != null) { return -1; }
if (a.resets != null && b.resets == null) { return 1; }
if (a.resets == null && b.resets == null) { return 0; }
if (a.resets < b.resets) { return -1; }
if (a.resets > b.resets) { return 1; }
if (a.name > b.name) { return 1; }
if (a.name < b.name) { return -1; }
return 0;
});
} else if (sort === 'nameAsc') {
player.milestoneList.sort((a, b) => {
if (a.name > b.name) { return 1; }
if (a.name < b.name) { return -1; }
return 0;
});
} else if (sort === 'nameDesc') {
player.milestoneList.sort((a, b) => {
if (a.name > b.name) { return -1; }
if (a.name < b.name) { return 1; }
return 0;
});
}
return player;
}
public trackTriumph(n: TriumphRecordNode) {
this.storageService.trackHashList('trackedtriumphs', n.hash);
}
public untrackTriumph(n: TriumphRecordNode) {
this.storageService.untrackHashList('trackedtriumphs', n.hash);
}
public trackPursuit(n: InventoryItem) {
this.storageService.trackHashList('trackedpursuits', n.hash);
}
public untrackPursuit(n: InventoryItem) {
this.storageService.untrackHashList('trackedpursuits', n.hash);
}
// use this once it works on enough things to be worthwhile
// public async gameTrackPursuit(n: InventoryItem, tracked: boolean) {
// console.log(`GameTrack ${n.name} ${tracked}`);
// const membershipType = this.currPlayer().profile.userInfo.membershipType;
// await this.bungieService.setTrackedState(membershipType, n, tracked);
// }
private applyTrackedPursuits(player: Player) {
if (player == null) {
return;
}
const tempPursuits = [];
if (Object.keys(this.dTrackedPursuits).length > 0) {
for (const t of player.bounties) {
if (this.dTrackedPursuits[t.hash] == true) {
tempPursuits.push(t);
}
}
for (const t of player.quests) {
if (this.dTrackedPursuits[t.hash] == true) {
tempPursuits.push(t);
}
}
for (const t of player.pursuitGear) {
if (this.dTrackedPursuits[t.hash] == true) {
tempPursuits.push(t);
}
}
}
this.trackedPursuits.next(tempPursuits);
}
private applyTrackedTriumphs(player: Player) {
if (player == null) {
return;
}
const tempTriumphs = [];
if (Object.keys(this.dTrackedTriumphIds).length > 0) {
for (const t of player.searchableTriumphs) {
if (this.dTrackedTriumphIds[t.hash] == true) {
tempTriumphs.push(t);
}
}
}
this.trackedTriumphs.next(tempTriumphs);
}
public restoreHiddenClosestTriumphs() {
localStorage.removeItem('hidden-closest-triumphs');
this.requestRefresh();
}
public hideClosestTriumph(n: TriumphRecordNode) {
const sHideMe = localStorage.getItem('hidden-closest-triumphs');
let hidden = [];
if (sHideMe != null) {
try {
hidden = JSON.parse(sHideMe);
} catch (exc) {
console.dir(exc);
}
}
hidden.push(n.hash);
localStorage.setItem('hidden-closest-triumphs', JSON.stringify(hidden));
this.requestRefresh();
}
} | the_stack |
import * as nls from 'vscode-nls'
import * as _ from 'lodash'
const localize = nls.loadMessageBundle()
import * as path from 'path'
import * as vscode from 'vscode'
import { samDeployDocUrl } from '../../shared/constants'
import * as localizedText from '../../shared/localizedText'
import { getLogger } from '../../shared/logger'
import { getRegionsForActiveCredentials } from '../../shared/regions/regionUtilities'
import { createHelpButton } from '../../shared/ui/buttons'
import * as input from '../../shared/ui/input'
import * as picker from '../../shared/ui/picker'
import * as telemetry from '../../shared/telemetry/telemetry'
import { difference, filter, IteratorTransformer } from '../../shared/utilities/collectionUtils'
import {
MultiStepWizard,
WIZARD_GOBACK,
WIZARD_TERMINATE,
wizardContinue,
WizardStep,
WIZARD_RETRY,
} from '../../shared/wizards/multiStepWizard'
import { configureParameterOverrides } from '../config/configureParameterOverrides'
import { getOverriddenParameters, getParameters } from '../config/parameterUtils'
import { ext } from '../../shared/extensionGlobals'
import { EcrRepository } from '../../shared/clients/ecrClient'
import { getSamCliVersion } from '../../shared/sam/cli/samCliContext'
import * as semver from 'semver'
import { MINIMUM_SAM_CLI_VERSION_INCLUSIVE_FOR_IMAGE_SUPPORT } from '../../shared/sam/cli/samCliValidator'
import { ExtContext } from '../../shared/extensions'
import { validateBucketName } from '../../s3/util'
import { showViewLogsMessage } from '../../shared/utilities/messages'
import { getIdeProperties, isCloud9 } from '../../shared/extensionUtilities'
import { SettingsConfiguration } from '../../shared/settingsConfiguration'
import { recentlyUsed } from '../../shared/localizedText'
const CREATE_NEW_BUCKET = localize('AWS.command.s3.createBucket', 'Create Bucket...')
const ENTER_BUCKET = localize('AWS.samcli.deploy.bucket.existingLabel', 'Enter Existing Bucket Name...')
export const CHOSEN_BUCKET_KEY = 'manuallySelectedBuckets'
export interface SavedBuckets {
[profile: string]: { [region: string]: string }
}
export interface SamDeployWizardResponse {
parameterOverrides: Map<string, string>
region: string
template: vscode.Uri
s3Bucket: string
ecrRepo?: EcrRepository
stackName: string
}
export const enum ParameterPromptResult {
Cancel,
Continue,
}
export interface SamDeployWizardContext {
readonly extContext: ExtContext
readonly workspaceFolders: vscode.Uri[] | undefined
additionalSteps: number
/**
* Returns the parameters in the specified template, or `undefined`
* if the template does not include a `Parameters` section. `required`
* is set to `true` if the parameter does not have a default value.
*
* @param templateUri The URL of the SAM template to inspect.
*/
getParameters: typeof getParameters
/**
* Returns true if the teamplate has images and needs an ECR repo to upload them to
* TODO refactor this to not be needed by making getTemplate also return the template in addition
* to the URI
*/
determineIfTemplateHasImages(templatePath: vscode.Uri): Promise<boolean>
/**
* Returns the names and values of parameters from the specified template
* that have been overridden in `templates.json`, or `undefined` if `templates.json`
* does not include a `parameterOverrides` section for the specified template.
*
* @param templateUri
*/
getOverriddenParameters: typeof getOverriddenParameters
/**
* Retrieves the URI of a Sam template to deploy from the user
*
* @returns vscode.Uri of a Sam Template. undefined represents cancel.
*/
promptUserForSamTemplate(initialValue?: vscode.Uri): Promise<vscode.Uri | undefined>
/**
* Prompts the user to configure parameter overrides, then either pre-fills and opens
* `templates.json`, or returns true.
*
* @param options.templateUri The URL of the SAM template to inspect.
* @param options.missingParameters The names of required parameters that are not yet overridden.
* @returns A value indicating whether the wizard should proceed. `false` if `missingParameters` was
* non-empty, or if it was empty and the user opted to configure overrides instead of continuing.
*/
promptUserForParametersIfApplicable(options: {
templateUri: vscode.Uri
missingParameters?: Set<string>
}): Promise<ParameterPromptResult>
promptUserForRegion(step: number, initialValue?: string): Promise<string | undefined>
/**
* Retrieves an S3 Bucket to deploy to from the user.
*
* @param initialValue Optional, Initial value to prompt with
*
* @returns S3 Bucket name. Undefined represents cancel.
*/
promptUserForS3Bucket(
step: number,
selectedRegion: string,
profile?: string,
accountId?: string,
initialValue?: string
): Promise<string | undefined>
/**
* Prompts user to enter a bucket name
*
* @returns S3 Bucket name. Undefined represents cancel.
*/
promptUserForS3BucketName(
step: number,
bucketProps: {
title: string
prompt?: string
placeHolder?: string
value?: string
buttons?: vscode.QuickInputButton[]
buttonHandler?: (
button: vscode.QuickInputButton,
inputBox: vscode.InputBox,
resolve: (value: string | PromiseLike<string | undefined> | undefined) => void,
reject: (value: string | PromiseLike<string | undefined> | undefined) => void
) => void
}
): Promise<string | undefined>
/**
* Retrieves an ECR Repo to deploy to from the user.
*
* @param initialValue Optional, Initial value to prompt with
*
* @returns ECR Repo URI. Undefined represents cancel.
*/
promptUserForEcrRepo(
step: number,
selectedRegion?: string,
initialValue?: EcrRepository
): Promise<EcrRepository | undefined>
/**
* Retrieves a Stack Name to deploy to from the user.
*
* @param initialValue Optional, Initial value to prompt with
* @param validateInput Optional, validates input as it is entered
*
* @returns Stack name. Undefined represents cancel.
*/
promptUserForStackName({
initialValue,
validateInput,
}: {
initialValue?: string
validateInput(value: string): string | undefined
}): Promise<string | undefined>
}
function getSingleResponse(responses: vscode.QuickPickItem[] | undefined): string | undefined {
if (!responses) {
return undefined
}
if (responses.length !== 1) {
throw new Error(`Expected a single response, but got ${responses.length}`)
}
return responses[0].label
}
/**
* The toolkit used to store saved buckets as a stringified JSON object. To ensure compatability,
* we need to check for this and convert them into objects.
*/
export function readSavedBuckets(settings: SettingsConfiguration): SavedBuckets | undefined {
try {
const buckets = settings.readSetting<SavedBuckets | string | undefined>(CHOSEN_BUCKET_KEY)
return typeof buckets === 'string' ? JSON.parse(buckets) : buckets
} catch (e) {
// If we fail to read settings then remove the bad data completely
getLogger().error('Recent bucket JSON not parseable. Rewriting recent buckets from scratch...', e)
settings.writeSetting(CHOSEN_BUCKET_KEY, {}, vscode.ConfigurationTarget.Global)
return undefined
}
}
/**
* Writes a single new saved bucket to the stored buckets setting, combining previous saved data
* if it exists. One saved bucket is limited per region per profile.
*/
export function writeSavedBucket(
settings: SettingsConfiguration,
profile: string,
region: string,
bucket: string
): void {
const oldBuckets = readSavedBuckets(settings)
settings.writeSetting(
CHOSEN_BUCKET_KEY,
{
...oldBuckets,
[profile]: {
...(oldBuckets && oldBuckets[profile] ? oldBuckets[profile] : {}),
[region]: bucket,
},
} as SavedBuckets,
vscode.ConfigurationTarget.Global
)
}
export class DefaultSamDeployWizardContext implements SamDeployWizardContext {
public readonly getParameters = getParameters
public readonly getOverriddenParameters = getOverriddenParameters
private readonly helpButton = createHelpButton()
private readonly totalSteps: number = 4
public additionalSteps: number = 0
public newBucketCalled = false
public constructor(readonly extContext: ExtContext) {}
public get workspaceFolders(): vscode.Uri[] | undefined {
return (vscode.workspace.workspaceFolders || []).map(f => f.uri)
}
public async determineIfTemplateHasImages(templatePath: vscode.Uri): Promise<boolean> {
const template = ext.templateRegistry.getRegisteredItem(templatePath.fsPath)
const resources = template?.item?.Resources
if (resources === undefined) {
return false
} else {
return Object.keys(resources)
.filter(key => resources[key]?.Type === 'AWS::Serverless::Function')
.map(key => resources[key]?.Properties?.PackageType)
.some(it => it === 'Image')
}
}
/**
* Retrieves the URI of a Sam template to deploy from the user
*
* @returns vscode.Uri of a Sam Template. undefined represents cancel.
*/
public async promptUserForSamTemplate(initialValue?: vscode.Uri): Promise<vscode.Uri | undefined> {
const workspaceFolders = this.workspaceFolders || []
const quickPick = picker.createQuickPick<SamTemplateQuickPickItem>({
options: {
ignoreFocusOut: true,
title: localize(
'AWS.samcli.deploy.template.prompt',
'Which SAM Template would you like to deploy to {0}?',
getIdeProperties().company
),
step: 1,
totalSteps: this.totalSteps,
},
buttons: [this.helpButton, vscode.QuickInputButtons.Back],
items: await getTemplateChoices(...workspaceFolders),
})
const choices = await picker.promptUser({
picker: quickPick,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
}
},
})
const val = picker.verifySinglePickerOutput<SamTemplateQuickPickItem>(choices)
return val ? val.uri : undefined
}
public async promptUserForParametersIfApplicable({
templateUri,
missingParameters = new Set<string>(),
}: {
templateUri: vscode.Uri
missingParameters?: Set<string>
}): Promise<ParameterPromptResult> {
if (missingParameters.size < 1) {
const prompt = localize(
'AWS.samcli.deploy.parameters.optionalPrompt.message',
// prettier-ignore
'Template "{0}" contains parameters. Do you want to override their default values?',
templateUri.fsPath
)
const quickPick = picker.createQuickPick<vscode.QuickPickItem>({
options: {
ignoreFocusOut: true,
title: prompt,
step: 2,
totalSteps: this.totalSteps + this.additionalSteps,
},
buttons: [this.helpButton, vscode.QuickInputButtons.Back],
items: [{ label: localizedText.yes }, { label: localizedText.no }],
})
const response = getSingleResponse(
await picker.promptUser({
picker: quickPick,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
}
},
})
)
if (response !== localizedText.yes) {
return ParameterPromptResult.Continue
}
await configureParameterOverrides({
templateUri,
requiredParameterNames: missingParameters.keys(),
})
return ParameterPromptResult.Cancel
} else {
const prompt = localize(
'AWS.samcli.deploy.parameters.mandatoryPrompt.message',
// prettier-ignore
'The template {0} contains parameters without default values. In order to deploy, you must provide values for these parameters. Configure them now?',
templateUri.fsPath
)
const responseConfigure = localize(
'AWS.samcli.deploy.parameters.mandatoryPrompt.responseConfigure',
'Configure'
)
const responseCancel = localizedText.cancel
// no step number needed since this is a dead end?
const quickPick = picker.createQuickPick<vscode.QuickPickItem>({
options: {
ignoreFocusOut: true,
title: prompt,
},
buttons: [this.helpButton, vscode.QuickInputButtons.Back],
items: [{ label: responseConfigure }, { label: responseCancel }],
})
const response = getSingleResponse(
await picker.promptUser({
picker: quickPick,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
}
},
})
)
if (response === responseConfigure) {
await configureParameterOverrides({
templateUri,
requiredParameterNames: missingParameters.keys(),
})
}
return ParameterPromptResult.Cancel
}
}
public async promptUserForRegion(step: number, initialRegionCode?: string): Promise<string | undefined> {
const partitionRegions = getRegionsForActiveCredentials(
this.extContext.awsContext,
this.extContext.regionProvider
)
const quickPick = picker.createQuickPick<vscode.QuickPickItem>({
options: {
title: localize(
'AWS.samcli.deploy.region.prompt',
'Which {0} Region would you like to deploy to?',
getIdeProperties().company
),
value: initialRegionCode,
matchOnDetail: true,
ignoreFocusOut: true,
step: step,
totalSteps: this.totalSteps + this.additionalSteps,
},
items: partitionRegions.map(region => ({
label: region.name,
detail: region.id,
// this is the only way to get this to show on going back
// this will make it so it always shows even when searching for something else
alwaysShow: region.id === initialRegionCode,
description: region.id === initialRegionCode ? localizedText.recentlyUsed : '',
})),
buttons: [this.helpButton, vscode.QuickInputButtons.Back],
})
const choices = await picker.promptUser<vscode.QuickPickItem>({
picker: quickPick,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
}
},
})
const val = picker.verifySinglePickerOutput(choices)
return val?.detail
}
/**
* Retrieves an S3 Bucket to deploy to from the user.
*
* @param selectedRegion Selected region for S3 client usage
* @param initialValue Optional, Initial value to prompt with
* @param messages Passthrough strings for testing
*
* @returns S3 Bucket name. Undefined represents cancel.
*/
public async promptUserForS3Bucket(
step: number,
selectedRegion: string,
profile?: string,
accountId?: string,
initialValue?: string,
messages: {
noBuckets: string
bucketError: string
} = {
noBuckets: localize('AWS.samcli.deploy.s3bucket.picker.noBuckets', 'No buckets found.'),
bucketError: localize('AWS.samcli.deploy.s3bucket.picker.error', 'There was an error loading S3 buckets.'),
}
): Promise<string | undefined> {
const createBucket = {
iconPath: {
light: vscode.Uri.file(ext.iconPaths.light.plus),
dark: vscode.Uri.file(ext.iconPaths.dark.plus),
},
tooltip: CREATE_NEW_BUCKET,
}
const enterBucket = {
iconPath: {
light: vscode.Uri.file(ext.iconPaths.light.edit),
dark: vscode.Uri.file(ext.iconPaths.dark.edit),
},
tooltip: ENTER_BUCKET,
}
const quickPick = picker.createQuickPick<vscode.QuickPickItem>({
buttons: [enterBucket, createBucket, this.helpButton, vscode.QuickInputButtons.Back],
options: {
title: localize(
'AWS.samcli.deploy.s3Bucket.prompt',
'Select an {0} S3 Bucket to deploy code to',
getIdeProperties().company
),
value: initialValue,
matchOnDetail: true,
ignoreFocusOut: true,
step: step,
totalSteps: this.totalSteps + this.additionalSteps,
},
})
quickPick.busy = true
// NOTE: Do not await this promise.
// This will background load the S3 buckets and load them all (in one chunk) when the operation completes.
// Not awaiting lets us display a "loading" quick pick for immediate feedback.
// Does not use an IteratingQuickPick because listing S3 buckets by region is not a paginated operation.
populateS3QuickPick(quickPick, selectedRegion, this.extContext.settings, messages, profile, accountId)
const choices = await picker.promptUser<vscode.QuickPickItem>({
picker: quickPick,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
} else if (button === createBucket) {
resolve([{ label: CREATE_NEW_BUCKET }])
} else if (button === enterBucket) {
resolve([{ label: ENTER_BUCKET }])
}
},
})
const val = picker.verifySinglePickerOutput(choices)
return val?.label && ![messages.noBuckets, messages.bucketError].includes(val.label) ? val.label : undefined
}
public async promptUserForS3BucketName(
step: number,
bucketProps: {
title: string
prompt?: string
placeHolder?: string
value?: string
buttons?: vscode.QuickInputButton[]
buttonHandler?: (
button: vscode.QuickInputButton,
inputBox: vscode.InputBox,
resolve: (value: string | PromiseLike<string | undefined> | undefined) => void,
reject: (value: string | PromiseLike<string | undefined> | undefined) => void
) => void
}
): Promise<string | undefined> {
if (!this.newBucketCalled) {
this.additionalSteps++
this.newBucketCalled = true
}
const inputBox = input.createInputBox({
buttons: [
this.helpButton,
vscode.QuickInputButtons.Back,
...(bucketProps.buttons ? bucketProps.buttons : []),
],
options: {
title: bucketProps.title,
ignoreFocusOut: true,
step: step + 1,
totalSteps: this.totalSteps + this.additionalSteps,
value: bucketProps.value,
prompt: bucketProps.prompt,
placeHolder: bucketProps.placeHolder,
},
})
const response = await input.promptUser({
inputBox: inputBox,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
} else if (bucketProps.buttonHandler) {
bucketProps.buttonHandler(button, inputBox, resolve, reject)
}
},
onValidateInput: validateBucketName,
})
if (!response) {
return undefined
} else {
return response
}
}
public async promptUserForEcrRepo(
step: number,
selectedRegion: string,
initialValue?: EcrRepository
): Promise<EcrRepository | undefined> {
const quickPick = picker.createQuickPick<vscode.QuickPickItem>({
buttons: [this.helpButton, vscode.QuickInputButtons.Back],
options: {
title: localize('AWS.samcli.deploy.ecrRepo.prompt', 'Select a ECR repo to deploy images to'),
value: initialValue?.repositoryName,
matchOnDetail: true,
ignoreFocusOut: true,
step: step,
totalSteps: this.totalSteps + this.additionalSteps,
},
})
const populator = new IteratorTransformer<EcrRepository, vscode.QuickPickItem>(
() => ext.toolkitClientBuilder.createEcrClient(selectedRegion).describeRepositories(),
response => (response === undefined ? [] : [{ label: response.repositoryName, repository: response }])
)
const controller = new picker.IteratingQuickPickController(quickPick, populator)
controller.startRequests()
const choices = await picker.promptUser({
picker: quickPick,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
}
},
})
const result = picker.verifySinglePickerOutput(choices)
const repository: EcrRepository | undefined = (result as any)?.repository
const label = result?.label
if (!repository || label === picker.IteratingQuickPickController.NO_ITEMS_ITEM.label) {
return undefined
}
return repository
}
/**
* Retrieves a Stack Name to deploy to from the user.
*
* @param initialValue Optional, Initial value to prompt with
* @param validateInput Optional, validates input as it is entered
*
* @returns Stack name. Undefined represents cancel.
*/
public async promptUserForStackName({
initialValue,
validateInput,
}: {
initialValue?: string
validateInput(value: string): string | undefined
}): Promise<string | undefined> {
const inputBox = input.createInputBox({
buttons: [this.helpButton, vscode.QuickInputButtons.Back],
options: {
title: localize('AWS.samcli.deploy.stackName.prompt', 'Enter the name to use for the deployed stack'),
ignoreFocusOut: true,
step: 4 + this.additionalSteps,
totalSteps: this.totalSteps + this.additionalSteps,
},
})
// Pre-populate the value if it was already set
if (initialValue) {
inputBox.value = initialValue
}
return await input.promptUser({
inputBox: inputBox,
onValidateInput: validateInput,
onDidTriggerButton: (button, resolve, reject) => {
if (button === vscode.QuickInputButtons.Back) {
resolve(undefined)
} else if (button === this.helpButton) {
vscode.env.openExternal(vscode.Uri.parse(samDeployDocUrl))
}
},
})
}
}
export class SamDeployWizard extends MultiStepWizard<SamDeployWizardResponse> {
private readonly response: Partial<SamDeployWizardResponse> = {}
/**
* If the selected template has Image based lambdas. If it does, we also need to prompt for
* an ECR repo to push the images to
*/
private hasImages: boolean = false
/**
* Initial treenode passed as a command arg to the "Deploy" command
* (typically, when invoked from the File Explorer context-menu).
*/
private regionNode: any | undefined
/**
* Initial template.yaml path passed as a command arg to the "Deploy"
* command (typically, when invoked from the File Explorer context-menu).
*/
private samTemplateFile: vscode.Uri | undefined
/**
*
* @param context
* @param commandArg Argument given by VSCode when the "Deploy" command was invoked from a context-menu.
*/
public constructor(private readonly context: SamDeployWizardContext, commandArg?: any) {
super()
if (commandArg && commandArg.path) {
// "Deploy" command was invoked on a template.yaml file.
// The promptUserForSamTemplate() call will be skipped.
this.samTemplateFile = commandArg as vscode.Uri
} else if (commandArg && commandArg.regionCode) {
this.regionNode = commandArg
this.response.region = this.regionNode.regionCode
}
}
protected get startStep() {
return this.TEMPLATE
}
protected getResult(): SamDeployWizardResponse | undefined {
if (
!this.response.parameterOverrides ||
!this.response.template ||
!this.response.region ||
!this.response.s3Bucket ||
!this.response.stackName
) {
return undefined
}
return {
parameterOverrides: this.response.parameterOverrides,
template: this.response.template,
region: this.response.region,
s3Bucket: this.response.s3Bucket,
ecrRepo: this.response.ecrRepo,
stackName: this.response.stackName,
}
}
private readonly TEMPLATE: WizardStep = async () => {
// set steps back to 0 since the next step determines if additional steps are needed
this.context.additionalSteps = 0
if (this.samTemplateFile && this.response.template) {
// This state means:
// 1. wizard was started from a context-menu (`this.samTemplateFile` was set)
// 2. user canceled the REGION step.
// => User wants to exit the wizard.
return WIZARD_TERMINATE
} else if (this.samTemplateFile) {
this.response.template = this.samTemplateFile
} else {
this.response.template = await this.context.promptUserForSamTemplate(this.response.template)
}
if (!this.response.template) {
return WIZARD_TERMINATE
}
// also ask user to setup CFN parameters if they haven't already done so
const getNextStep = (result: ParameterPromptResult) => {
switch (result) {
case ParameterPromptResult.Cancel:
return WIZARD_TERMINATE
case ParameterPromptResult.Continue:
return wizardContinue(this.skipOrPromptRegion(this.S3_BUCKET))
}
}
this.hasImages = await this.context.determineIfTemplateHasImages(this.response.template)
if (this.hasImages) {
// TODO: remove check when min version is high enough
const samCliVersion = await getSamCliVersion(this.context.extContext.samCliContext())
if (semver.lt(samCliVersion, MINIMUM_SAM_CLI_VERSION_INCLUSIVE_FOR_IMAGE_SUPPORT)) {
vscode.window.showErrorMessage(
localize(
'AWS.output.sam.no.image.support',
'Support for Image-based Lambdas requires a minimum SAM CLI version of 1.13.0.'
)
)
return WIZARD_TERMINATE
}
this.context.additionalSteps++
}
const parameters = await this.context.getParameters(this.response.template)
if (parameters.size < 1) {
this.response.parameterOverrides = new Map<string, string>()
return wizardContinue(this.skipOrPromptRegion(this.S3_BUCKET))
}
const requiredParameterNames = new Set<string>(
filter(parameters.keys(), name => parameters.get(name)!.required)
)
const overriddenParameters = await this.context.getOverriddenParameters(this.response.template)
if (!overriddenParameters) {
// In there are no missing required parameters case, it isn't mandatory to override any parameters,
// but we still want to inform users of the option to override. Once we have prompted (i.e., if the
// parameter overrides section is empty instead of undefined), don't prompt again unless required.
this.context.additionalSteps++
const options = {
templateUri: this.response.template,
missingParameters: requiredParameterNames.size > 0 ? requiredParameterNames : undefined,
}
this.response.parameterOverrides = new Map<string, string>()
return getNextStep(await this.context.promptUserForParametersIfApplicable(options))
}
const missingParameters = difference(requiredParameterNames, overriddenParameters.keys())
if (missingParameters.size > 0) {
this.context.additionalSteps++
return getNextStep(
await this.context.promptUserForParametersIfApplicable({
templateUri: this.response.template,
missingParameters,
})
)
}
this.response.parameterOverrides = overriddenParameters
return wizardContinue(this.skipOrPromptRegion(this.S3_BUCKET))
}
private readonly REGION: WizardStep = async step => {
this.response.region = await this.context.promptUserForRegion(step, this.response.region)
return this.response.region ? wizardContinue(this.S3_BUCKET) : WIZARD_GOBACK
}
private readonly S3_BUCKET: WizardStep = async step => {
const profile = this.context.extContext.awsContext.getCredentialProfileName() || ''
const accountId = this.context.extContext.awsContext.getCredentialAccountId() || ''
const response = await this.context.promptUserForS3Bucket(
step,
this.response.region!,
profile,
accountId,
this.response.s3Bucket
)
if (!response) {
return WIZARD_GOBACK
}
if (response === CREATE_NEW_BUCKET) {
const newBucketRequest = await this.context.promptUserForS3BucketName(step, {
title: localize('AWS.s3.createBucket.prompt', 'Enter a new bucket name'),
})
if (!newBucketRequest) {
return WIZARD_RETRY
}
try {
const s3Client = ext.toolkitClientBuilder.createS3Client(this.response.region!)
const newBucketName = (await s3Client.createBucket({ bucketName: newBucketRequest })).bucket.name
this.response.s3Bucket = newBucketName
getLogger().info('Created bucket: %O', newBucketName)
vscode.window.showInformationMessage(
localize('AWS.s3.createBucket.success', 'Created bucket: {0}', newBucketName)
)
telemetry.recordS3CreateBucket({ result: 'Succeeded' })
} catch (e) {
showViewLogsMessage(
localize('AWS.s3.createBucket.error.general', 'Failed to create bucket: {0}', newBucketRequest),
vscode.window
)
telemetry.recordS3CreateBucket({ result: 'Failed' })
return WIZARD_RETRY
}
} else if (response === ENTER_BUCKET) {
const bucket = await this.context.promptUserForS3BucketName(step, {
title: localize('AWS.samcli.deploy.bucket.existingTitle', 'Enter Existing Bucket Name'),
value: this.response.s3Bucket,
})
if (!bucket) {
return WIZARD_RETRY
}
this.response.s3Bucket = bucket
} else {
this.response.s3Bucket = response
}
return this.hasImages ? wizardContinue(this.ECR_REPO) : wizardContinue(this.STACK_NAME)
}
private readonly ECR_REPO: WizardStep = async step => {
const response = await this.context.promptUserForEcrRepo(step, this.response.region, this.response.ecrRepo)
this.response.ecrRepo = response
return response ? wizardContinue(this.STACK_NAME) : WIZARD_GOBACK
}
private readonly STACK_NAME: WizardStep = async () => {
this.response.stackName = await this.context.promptUserForStackName({
initialValue: this.response.stackName,
validateInput: validateStackName,
})
return this.response.stackName ? WIZARD_TERMINATE : WIZARD_GOBACK
}
private skipOrPromptRegion(skipToStep: WizardStep): WizardStep {
return this.regionNode && Object.prototype.hasOwnProperty.call(this.regionNode, 'regionCode')
? skipToStep
: this.REGION
}
}
class SamTemplateQuickPickItem implements vscode.QuickPickItem {
public readonly label: string
public description?: string
public detail?: string
public constructor(public readonly uri: vscode.Uri, showWorkspaceFolderDetails: boolean) {
this.label = SamTemplateQuickPickItem.getLabel(uri)
if (showWorkspaceFolderDetails) {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri)
if (workspaceFolder) {
this.description = `in ${workspaceFolder.uri.fsPath}`
}
}
}
public compareTo(rhs: SamTemplateQuickPickItem): number {
const labelComp = this.label.localeCompare(rhs.label)
if (labelComp !== 0) {
return labelComp
}
const descriptionComp = (this.description || '').localeCompare(rhs.description || '')
if (descriptionComp !== 0) {
return descriptionComp
}
return (this.detail || '').localeCompare(rhs.detail || '')
}
public static getLabel(uri: vscode.Uri): string {
const logger = getLogger()
const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri)
if (workspaceFolder) {
// If workspace is /usr/foo/code and uri is /usr/foo/code/processor/template.yaml,
// show "processor/template.yaml"
return path.relative(workspaceFolder.uri.fsPath, uri.fsPath)
}
// We shouldn't find sam templates outside of a workspace folder. If we do, show the full path.
logger.warn(`Unexpected situation: detected SAM Template ${uri.fsPath} not found within a workspace folder.`)
return uri.fsPath
}
}
// https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html
// A stack name can contain only alphanumeric characters (case sensitive) and hyphens.
// It must start with an alphabetic character and cannot be longer than 128 characters.
function validateStackName(value: string): string | undefined {
if (!/^[a-zA-Z\d\-]+$/.test(value)) {
return localize(
'AWS.samcli.deploy.stackName.error.invalidCharacters',
'A stack name may contain only alphanumeric characters (case sensitive) and hyphens'
)
}
if (!/^[a-zA-Z]/.test(value)) {
return localize(
'AWS.samcli.deploy.stackName.error.firstCharacter',
'A stack name must begin with an alphabetic character'
)
}
if (value.length > 128) {
return localize(
'AWS.samcli.deploy.stackName.error.length',
'A stack name must not be longer than 128 characters'
)
}
// TODO: Validate that a stack with this name does not already exist.
return undefined
}
async function getTemplateChoices(...workspaceFolders: vscode.Uri[]): Promise<SamTemplateQuickPickItem[]> {
const templateUris = ext.templateRegistry.registeredItems.map(o => vscode.Uri.file(o.path))
const uriToLabel: Map<vscode.Uri, string> = new Map<vscode.Uri, string>()
const labelCounts: Map<string, number> = new Map()
templateUris.forEach(uri => {
const label = SamTemplateQuickPickItem.getLabel(uri)
uriToLabel.set(uri, label)
labelCounts.set(label, 1 + (labelCounts.get(label) || 0))
})
return Array.from(uriToLabel, ([uri, label]) => {
const showWorkspaceFolderDetails: boolean = (labelCounts.get(label) || 0) > 1
return new SamTemplateQuickPickItem(uri, showWorkspaceFolderDetails)
}).sort((a, b) => a.compareTo(b))
}
/**
* Loads S3 buckets into a quick pick.
* Fully replaces the quick pick's `items` field on loading S3 buckets.
* Operation is not paginated as S3 does not offer paginated listing of regionalized buckets.
* @param quickPick Quick pick to modify the items and busy/enabled state of.
* @param selectedRegion AWS region to display buckets for
* @param settings SettingsConfiguration object to get stored settings
* @param messages Messages to denote no available buckets and errors.
*/
async function populateS3QuickPick(
quickPick: vscode.QuickPick<vscode.QuickPickItem>,
selectedRegion: string,
settings: SettingsConfiguration,
messages: { noBuckets: string; bucketError: string },
profile?: string,
accountId?: string
): Promise<void> {
return new Promise(async resolve => {
const goBack: string = localize('AWS.picker.dynamic.noItemsFound.detail', 'Click here to go back')
const baseItems: vscode.QuickPickItem[] = []
const cloud9Bucket = `cloud9-${accountId}-sam-deployments-${selectedRegion}`
let recent: string = ''
try {
const existingBuckets = readSavedBuckets(settings)
if (existingBuckets && profile && existingBuckets[profile] && existingBuckets[profile][selectedRegion]) {
recent = existingBuckets[profile][selectedRegion]
baseItems.push({
label: recent,
description: recentlyUsed,
})
}
} catch (e) {
getLogger().error('Recent bucket JSON not parseable.', e)
}
if (isCloud9() && recent !== cloud9Bucket) {
baseItems.push({
label: cloud9Bucket,
detail: localize(
'AWS.samcli.deploy.bucket.cloud9name',
'Default {0} Cloud9 Bucket',
getIdeProperties().company
),
})
}
try {
const s3Client = ext.toolkitClientBuilder.createS3Client(selectedRegion)
quickPick.items = [...baseItems]
const buckets = (await s3Client.listBuckets()).buckets
if (buckets.length === 0) {
quickPick.items = [
...baseItems,
{ label: CREATE_NEW_BUCKET },
{ label: ENTER_BUCKET },
{
label: messages.noBuckets,
description: goBack,
},
]
} else {
const bucketItems = buckets
.filter(bucket => bucket.name !== recent && !(isCloud9() && bucket.name === cloud9Bucket))
.map(bucket => {
return {
label: bucket.name,
}
})
quickPick.items = [...baseItems, ...bucketItems]
}
} catch (e) {
const err = e as Error
quickPick.items = [
...baseItems,
{ label: CREATE_NEW_BUCKET },
{ label: ENTER_BUCKET },
{
label: messages.bucketError,
description: goBack,
detail: err.message,
},
]
} finally {
quickPick.busy = false
resolve()
}
})
} | the_stack |
type ContextMenuSettings = import("../thirdParty/handsontable/handsontable").contextMenu.Settings
type GridSettings = import("../thirdParty/handsontable/handsontable").GridSettings
/* --- common helpers --- */
/**
* displayed or hides the options bar content
* @param shouldCollapse
*/
function toggleOptionsBar(shouldCollapse?: boolean) {
const el = _getById('options-bar-icon')
if (shouldCollapse === undefined) {
if (el.classList.contains('fa-chevron-down')) {
//down is expanded and we want to toggle
shouldCollapse = true
} else {
shouldCollapse = false
}
}
document.documentElement.style
.setProperty('--extension-options-bar-display', shouldCollapse ? `none` : `block`)
if (vscode) {
const lastState = _getVsState()
vscode.setState({
...lastState,
previewIsCollapsed: shouldCollapse
})
}
if (shouldCollapse) {
el.classList.remove('fa-chevron-down')
el.classList.add('fa-chevron-right')
onResizeGrid()
_setPreviewCollapsedVsState(shouldCollapse)
return
}
el.classList.add('fa-chevron-down')
el.classList.remove('fa-chevron-right')
onResizeGrid()
_setPreviewCollapsedVsState(shouldCollapse)
}
/* --- read options --- */
/**
* if input value is set programmatically this is NOT called
*
* when the settings apply header {@link startRenderData} we need to reset the status text here
*
* @param fromUndo true: only update col headers, do not change the table data (will be done by undo/redo), false: normal
*/
function _applyHasHeader(displayRenderInformation: boolean, fromUndo = false) {
const el = hasHeaderReadOptionInput //or defaultCsvReadOptions._hasHeader
const autoApplyHasHeader = shouldApplyHasHeaderAfterRowsAdded
setShouldAutpApplyHasHeader(false)
const elWrite = _getById('has-header-write') as HTMLInputElement //or defaultCsvWriteOptions.header
let func = () => {
if (!hot) throw new Error('table was null')
if (el.checked || autoApplyHasHeader) {
//this checked state is set from csvReadOptions._hasHeader
const dataWithIndex = getFirstRowWithIndex()
if (dataWithIndex === null) {
//disable input...
const el3 = _getById('has-header') as HTMLInputElement
el3.checked = false
headerRowWithIndex = null
return
}
if (fromUndo) return
headerRowWithIndex = dataWithIndex
el.checked = true //sync ui in case we get here via autoApplyHasHeader
hot.updateSettings({
fixedRowsTop: 0,
fixedColumnsLeft: 0,
}, false)
let hasAnyChangesBefore = getHasAnyChangesUi()
hot.alter('remove_row', headerRowWithIndex.physicalIndex)
elWrite.checked = true
defaultCsvWriteOptions.header = true
defaultCsvReadOptions._hasHeader = true
if (isFirstHasHeaderChangedEvent) {
if (hasAnyChangesBefore === false) {
_setHasUnsavedChangesUiIndicator(false)
}
isFirstHasHeaderChangedEvent = false
}
//we now always clear the undo after changing the read has header option
//because it's too complicated to get this right...
//@ts-ignore
let undoPlugin = hot.undoRedo
undoPlugin.clear()
//maybe we don't need this... worked without...
hot.render()
return
}
if (fromUndo) return
if (headerRowWithIndex === null) {
throw new Error('could not insert header row')
}
let hasAnyChangesBefore = getHasAnyChangesUi()
hot.alter('insert_row', headerRowWithIndex.physicalIndex)
const visualRow = hot.toVisualRow(headerRowWithIndex.physicalIndex)
const visualCol = hot.toVisualColumn(0)
//see https://handsontable.com/docs/6.2.2/Core.html#populateFromArray
hot.populateFromArray(visualRow, visualCol, [[...headerRowWithIndex.row]])
headerRowWithIndex = null
elWrite.checked = false
defaultCsvWriteOptions.header = false
defaultCsvReadOptions._hasHeader = false
hot.updateSettings({
fixedRowsTop: fixedRowsTop,
fixedColumnsLeft: fixedColumnsLeft,
}, false)
if (isFirstHasHeaderChangedEvent) {
if (hasAnyChangesBefore === false) {
_setHasUnsavedChangesUiIndicator(false)
}
isFirstHasHeaderChangedEvent = false
}
//we now always clear the undo after changing the read has header option
//because it's too complicated to get this right...
//@ts-ignore
let undoPlugin = hot.undoRedo
undoPlugin.clear()
//we changed headerRowWithIndex / header row so force a re-render so that hot calls defaultColHeaderFunc again
hot.render()
}
if (displayRenderInformation) {
statusInfo.innerText = `Rendering table...`
call_after_DOM_updated(() => {
func()
setTimeout(() => {
statusInfo.innerText = '';
}, 0)
})
return
}
func()
}
/**
* sets or removes if the has header should be applies automatically (not applies, only sets flag and ui)
*/
function setShouldAutpApplyHasHeader(shouldSet: boolean) {
if (shouldSet) {
shouldApplyHasHeaderAfterRowsAdded = true
hasHeaderReadOptionInput.classList.add(`toggle-auto-future`)
hasHeaderLabel.title = `Activated automatically, if table has >= 2 rows`
} else {
hasHeaderReadOptionInput.classList.remove(`toggle-auto-future`)
shouldApplyHasHeaderAfterRowsAdded = false
hasHeaderLabel.title = ``
}
}
/**
* checks if {@link shouldApplyHasHeaderAfterRowsAdded} is set and if so, tries to apply it
*/
function checkAutoApplyHasHeader() {
if (!shouldApplyHasHeaderAfterRowsAdded) return
tryApplyHasHeader()
}
/**
* tries to set the has header read option
* can fail if we have only 1 row
* in this case we set {@link shouldApplyHasHeaderAfterRowsAdded} so we know we need to watch if rows are added and then apply it afterwards
*/
function tryApplyHasHeader() {
if (!hot) return
const uiShouldApply = hasHeaderReadOptionInput.checked
//this might also change the (ui) option
const canApply = checkIfHasHeaderReadOptionIsAvailable(false)
if (uiShouldApply) {
if (!canApply) {
if (shouldApplyHasHeaderAfterRowsAdded) {
//toggle to false (not auto apply)
setShouldAutpApplyHasHeader(false)
return
}
setShouldAutpApplyHasHeader(true)
return
}
}
//else just apply
_applyHasHeader(true, false)
}
function setDelimiterString() {
const el = _getById('delimiter-string') as HTMLInputElement
defaultCsvReadOptions.delimiter = el.value
}
function setCommentString() {
const el = _getById('comment-string') as HTMLInputElement
defaultCsvReadOptions.comments = el.value === '' ? false : el.value
}
function setQuoteCharString() {
const el = _getById('quote-char-string') as HTMLInputElement
ensuredSingleCharacterString(el)
defaultCsvReadOptions.quoteChar = el.value
}
function setEscapeCharString() {
const el = _getById('escape-char-string') as HTMLInputElement
ensuredSingleCharacterString(el)
defaultCsvReadOptions.escapeChar = el.value
}
/**
* @deprecated not longer supported
*/
function setSkipEmptyLines() {
// const el = _getById('skip-empty-lines')
// if (el) {
// //currently disabled...
// csvReadOptions.skipEmptyLines = el.checked
// }
}
/**
* sets the read delimiter programmatically
* @param {string} delimiter
*/
function setReadDelimiter(delimiter: string) {
const el = _getById('delimiter-string') as HTMLInputElement
el.value = delimiter
defaultCsvReadOptions.delimiter = delimiter
}
/* --- write options --- */
function setHasHeaderWrite() {
const el = _getById('has-header-write') as HTMLInputElement
defaultCsvWriteOptions.header = el.checked
}
function setDelimiterStringWrite() {
const el = _getById('delimiter-string-write') as HTMLInputElement
defaultCsvWriteOptions.delimiter = el.value
}
function setCommentStringWrite() {
const el = _getById('comment-string-write') as HTMLInputElement
defaultCsvWriteOptions.comments = el.value === '' ? false : el.value
}
function setQuoteCharStringWrite() {
const el = _getById('quote-char-string-write') as HTMLInputElement
ensuredSingleCharacterString(el)
defaultCsvWriteOptions.quoteChar = el.value
}
function setEscapeCharStringWrite() {
const el = _getById('escape-char-string-write') as HTMLInputElement
ensuredSingleCharacterString(el)
defaultCsvWriteOptions.escapeChar = el.value
}
function setQuoteAllFieldsWrite() {
const el = _getById('quote-all-fields-write') as HTMLInputElement
defaultCsvWriteOptions.quoteAllFields = el.checked
}
/**
* NOT USED CURRENTLY (ui is hidden)
* only in browser version
*/
function setNewLineWrite() {
const el = _getById('newline-select-write') as HTMLInputElement
if (el.value === '') {
defaultCsvWriteOptions.newline = newLineFromInput
}
else if (el.value === 'lf') {
defaultCsvWriteOptions.newline = '\n'
}
else if (el.value === 'crlf') {
defaultCsvWriteOptions.newline = '\r\n'
}
}
/**
* sets the write delimiter programmatically
* @param {string} delimiter
*/
function setWriteDelimiter(delimiter: string) {
const el = _getById('delimiter-string-write') as HTMLInputElement
el.value = delimiter
defaultCsvWriteOptions.delimiter = delimiter
}
/* --- preview --- */
/**
* updates the preview
*/
function generateCsvPreview() {
const value = getDataAsCsv(defaultCsvReadOptions, defaultCsvWriteOptions)
const el = _getById('csv-preview') as HTMLTextAreaElement
el.value = value
//open preview
toggleOptionsBar(false)
}
function copyPreviewToClipboard() {
generateCsvPreview()
const el = _getById('csv-preview') as HTMLTextAreaElement
postCopyToClipboard(el.value)
}
/**
* renders the hot table again
*/
function reRenderTable(callback?: () => void) {
if (!hot) return
statusInfo.innerText = `Rendering table...`
call_after_DOM_updated(() => {
hot!.render()
setTimeout(() => {
statusInfo.innerText = ``
if (callback) {
//use another timeout so we clear the status text first
setTimeout(() => {
callback()
})
}
}, 0)
})
}
/**
* after resetting data the autoColumnSize plugin is disabled (don't know why)
* but this is ok as we want our saved column width on reset {@link allColWidths}
*
* but after clicking force resize columns we want to enable it again...
*/
function forceResizeColumns() {
if (!hot) return
//note that setting colWidths will disable the auto size column plugin (see Plugin AutoColumnSize.isEnabled)
//it is enabled if (!colWidths)
let plugin = hot.getPlugin('autoColumnSize')
let setColSizeFunc = () => {
if (!hot) return
hot.getSettings().manualColumnResize = false //this prevents setting manual col size?
hot.updateSettings({ colWidths: plugin.widths }, false)
hot.getSettings().manualColumnResize = true
hot.updateSettings({}, false) //change to manualColumnResize is only applied after updating setting?
plugin.enablePlugin()
}
if (plugin.widths.length === 0) {
plugin.enablePlugin()
reRenderTable(setColSizeFunc)
// hot.render() //this is needed else calculate will not get widths
//apparently render sets the column widths in the plugin if it's enabled?
// plugin.calculateAllColumnsWidth()
return
}
setColSizeFunc()
}
/* --- other --- */
/**
* display the given data in the handson table
* if we have rows this sets the
* @see headerRow and enables the has header option
* if we have data we convert it to match a rectangle (every row must have the same number of columns / cells)
* @param {string[][]} csvParseResult array with the rows or null to just destroy the old table
*/
function displayData(this: any, csvParseResult: ExtendedCsvParseResult | null, csvReadConfig: CsvReadOptions) {
if (csvParseResult === null) {
if (hot) {
hot.getInstance().destroy()
hot = null
}
return
}
//this will also expand comment rows but we only use the first column value...
_normalizeDataArray(csvParseResult, csvReadConfig)
columnIsQuoted = csvParseResult.columnIsQuoted
//reset header row
headerRowWithIndex = null
// if (data.length > 0) {
// headerRowWithIndex = getFirstRowWithIndexByData(data)
// }
const container = csvEditorDiv
if (hot) {
hot.destroy()
hot = null
}
const initiallyHideComments = initialConfig ? initialConfig.initiallyHideComments : false
if (initiallyHideComments && typeof csvReadConfig.comments === 'string') {
hiddenPhysicalRowIndices = _getCommentIndices(csvParseResult.data, csvReadConfig)
}
//enable all find connected stuff
//we need to setup this first so we get the events before handsontable... e.g. document keydown
findWidgetInstance.setupFind()
const showColumnHeaderNamesWithLettersLikeExcel = initialConfig?.showColumnHeaderNamesWithLettersLikeExcel ?? false
let defaultColHeaderFuncBound = defaultColHeaderFunc.bind(this, showColumnHeaderNamesWithLettersLikeExcel)
isInitialHotRender = true
hot = new Handsontable(container, {
data: csvParseResult.data,
readOnly: isReadonlyMode,
trimWhitespace: false,
rowHeaderWidth: getRowHeaderWidth(csvParseResult.data.length),
//false to enable virtual rendering
renderAllRows: false, //use false and small table size for fast initial render, see https://handsontable.com/docs/7.0.2/Options.html#renderAllRows
rowHeaders: function (row: number) { //the visual row index
let text = (row + 1).toString()
if (csvParseResult.data.length === 1 || isReadonlyMode) {
return `${text} <span class="remove-row clickable" onclick="removeRow(${row})" style="visibility: hidden"><i class="fas fa-trash"></i></span>`
}
return `${text} <span class="remove-row clickable" onclick="removeRow(${row})"><i class="fas fa-trash"></i></span>`
//why we would always disallow to remove first row?
// return row !== 0
// ? `${text} <span class="remove-row clickable" onclick="removeRow(${row})"><i class="fas fa-trash"></i></span>`
// : `${text} <span class="remove-row clickable" onclick="removeRow(${row})" style="visibility: hidden"><i class="fas fa-trash"></i></span>`
} as any,
afterChange: onAnyChange, //only called when cell value changed (e.g. not when col/row removed)
fillHandle: false,
undo: true,
colHeaders: defaultColHeaderFuncBound as any,
currentColClassName: 'foo', //actually used to overwrite highlighting
currentRowClassName: 'foo', //actually used to overwrite highlighting
//plugins
comments: false,
search: {
queryMethod: customSearchMethod,
searchResultClass: 'search-result-cell',
} as any, //typing is wrong, see https://handsontable.com/docs/6.2.2/demo-searching.html
wordWrap: enableWrapping,
autoColumnSize: initialColumnWidth > 0 ? {
maxColumnWidth: initialColumnWidth
} : true,
//keep this undefined/disabled because else performance is very very very bad for large files
//(for every row the height is calculated even if not rendered, on plugin startup and when a col is resized?)
//i also don't understand the benefit of it... maybe for non text content?
// autoRowSize: true,
manualRowMove: true,
manualRowResize: true,
manualColumnMove: true,
manualColumnResize: true,
columnSorting: true,
fixedRowsTop: fixedRowsTop,
fixedColumnsLeft: fixedColumnsLeft,
//see https://handsontable.com/docs/7.1.0/demo-context-menu.html
contextMenu: {
items: {
'row_above': {
callback: function () { //key, selection, clickEvent
insertRowAbove()
},
disabled: function() {
return isReadonlyMode
}
},
'row_below': {
callback: function () { //key, selection, clickEvent
insertRowBelow()
},
disabled: function() {
return isReadonlyMode
}
},
'---------': {
name: '---------'
},
'col_left': {
callback: function () { //key, selection, clickEvent
insertColLeft()
},
disabled: function() {
return isReadonlyMode
}
},
'col_right': {
callback: function () { //key, selection, clickEvent
insertColRight()
},
disabled: function() {
return isReadonlyMode
}
},
'---------2': {
name: '---------'
},
'remove_row': {
disabled: function () {
if (isReadonlyMode) return true
const selection = hot!.getSelected()
let allRowsAreSelected = false
if (selection) {
const selectedRowsCount = Math.abs(selection[0][0] - selection[0][2]) //starts at 0 --> +1
allRowsAreSelected = hot!.countRows() === selectedRowsCount + 1
}
return hot!.countRows() === 1 || allRowsAreSelected
},
},
'remove_col': {
disabled: function () {
if (isReadonlyMode) return true
const selection = hot!.getSelected()
let allColsAreSelected = false
if (selection) {
const selectedColsCount = Math.abs(selection[0][1] - selection[0][3]) //starts at 0 --> +1
allColsAreSelected = hot!.countCols() === selectedColsCount + 1
}
return hot!.countCols() === 1 || allColsAreSelected
}
},
'---------3': {
name: '---------'
},
'alignment': {},
'edit_header_cell': {
name: 'Edit header cell',
hidden: function () {
//there is no selection for header cells...
let selectedRanges = hot!.getSelected()
//only one range is selected
if (selectedRanges?.length !== 1) return true
//only one column is selected
if (selectedRanges[0][1] !== selectedRanges[0][3]) return true
//the whole col must be selected then we clicked the header cell
let maxRowIndex = hot!.countRows() - 1
if (selectedRanges[0][0] !== 0 || selectedRanges[0][2] !== maxRowIndex) return true
//must have custom header cells
if (!defaultCsvReadOptions._hasHeader) return true
if (!headerRowWithIndex) return true
return false
},
callback: function (key: string, selection: Array<{ start: { col: number, row: number }, end: { col: number, row: number } }>, clickEvent: Event) {
if (!headerRowWithIndex) return
if (selection.length > 1) return
let targetCol = selection[0].start.col
showColHeaderNameEditor(targetCol)
},
disabled: function() {
return isReadonlyMode
}
}
}
} as ContextMenuSettings,
beforeColumnSort: function(currentSortConfig, destinationSortConfigs) {
//we cannot use the setting columnSorting because this would remove the hidden indicators, this would change the coulmn width...
if (isReadonlyMode) return false
return
},
afterOnCellMouseUp: function () {
//we need this because after we click on header edit this event is called and focuses some editor on the hot instance
if (editHeaderCellTextInputEl) {
setTimeout(() => {
editHeaderCellTextInputEl!.focus()
}, 0)
}
},
afterOnCellMouseDown: function (event, coords, th) {
if (coords.row !== -1) return
lastClickedHeaderCellTh = th
},
outsideClickDeselects: false, //keep selection
cells: highlightCsvComments
? function (row, col) {
var cellProperties: GridSettings = {};
cellProperties.renderer = 'commentValueRenderer' //is registered in util
// cellProperties.renderer = 'invisiblesCellValueRenderer' //is registered in util
// if (row === undefined || row === null) return cellProperties
// if (col === undefined || col === null) return cellProperties
//@ts-ignore
// const _hot = this.instance as Handsontable
// const tableData = _hot.getData() //this is slooooooow, getDataAtCell is much faster
//we should always have 1 col
// const visualRowIndex = _hot.toVisualRow(row); //this is toooooo slow for e.g. 100.000 rows (takes ~3.3 mins vs 12s with just cell renderer)
// const firstCellVal = _hot.getDataAtCell(row, 0) //tableData[row][0]
// if (firstCellVal === null) return cellProperties
// if (typeof csvReadConfig.comments === 'string' && firstCellVal.trim().startsWith(csvReadConfig.comments)) {
// //@ts-ignore
// cellProperties._isComment = true
// } else {
// //@ts-ignore
// cellProperties._isComment = false
// }
return cellProperties
}
: undefined,
//not fully working... we would handle already comment cells
// beforeChange: function (changes) {
// if (!changes || changes.length !== 1) return
// console.log(changes)
// const rowIndex = changes[0][0]
// const colIndex = changes[0][1] as number
// const oldVal = changes[0][2]
// const newVal = changes[0][3]
// if (oldVal === newVal) return //user only started editing then canceled
// if (typeof csvReadConfig.comments === 'string' && colIndex === 0 && newVal.trim().startsWith(csvReadConfig.comments)) {
// //this is now a merged comment row
// const _tmp = transformIntoCommentRow(rowIndex, csvReadConfig)
// changes[0][3] = _tmp
// console.log(_tmp)
// }
// },
//see https://github.com/handsontable/handsontable/issues/3328
//ONLY working because first argument is actually the old size, which is a bug
beforeColumnResize: function (oldSize, newSize, isDoubleClick) { //after change but before render
if (oldSize === newSize) {
//e.g. we have a large column and the auto size is too large...
if (initialConfig) {
return initialConfig.doubleClickColumnHandleForcedWith
} else {
console.log(`initialConfig is falsy`)
}
}
},
afterColumnResize: function () {
// syncColWidths() //covered by afterRender
},
afterPaste: function () {
//could create new columns
// syncColWidths() //covered by afterRender
},
enterMoves: function (event: KeyboardEvent) {
if (!hot) throw new Error('table was null')
lastHandsonMoveWas = 'enter'
const selection = hot.getSelected()
const _default = {
row: 1,
col: 0
}
if (!initialConfig || initialConfig.lastRowEnterBehavior !== 'createRow') return _default
if (!selection || selection.length === 0) return _default
if (selection.length > 1) return _default
const rowCount = hot.countRows()
//see https://handsontable.com/docs/3.0.0/Core.html#getSelected
//[startRow, startCol, endRow, endCol].
const selected = selection[0]
if (selected[0] !== selected[2] || selected[0] !== rowCount - 1) return _default
if (event.key.toLowerCase() === 'enter' && event.shiftKey === false) {
addRow(false)
}
return _default
},
tabMoves: function (event: KeyboardEvent) {
if (!hot) throw new Error('table was null')
lastHandsonMoveWas = 'tab'
const selection = hot.getSelected()
const _default = {
row: 0,
col: 1
}
// console.log(initialConfig.lastColumnTabBehavior);
if (!initialConfig || initialConfig.lastColumnTabBehavior !== 'createColumn') return _default
if (!selection || selection.length === 0) return _default
if (selection.length > 1) return _default
const colCount = hot.countCols()
//see https://handsontable.com/docs/3.0.0/Core.html#getSelected
//[startRow, startCol, endRow, endCol]
const selected = selection[0]
if (selected[1] !== selected[3] || selected[1] !== colCount - 1) return _default
if (event.key.toLowerCase() === 'tab' && event.shiftKey === false) {
addColumn(false)
}
return _default
},
afterBeginEditing: function () {
if (!initialConfig || !initialConfig.selectTextAfterBeginEditCell) return
const textarea = document.getElementsByClassName("handsontableInput")
if (!textarea || textarea.length === 0 || textarea.length > 1) return
const el = textarea.item(0) as HTMLTextAreaElement | null
if (!el) return
el.setSelectionRange(0, el.value.length)
},
// data -> [[1, 2, 3], [4, 5, 6]]
//coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
beforeCopy: function (data, coords) {
//we could change data to 1 element array containing the finished data? log to console then step until we get to SheetClip.stringify
// console.log('data');
},
beforeUndo: function (_action: EditHeaderCellAction | RemoveColumnAction | InsertColumnAction | any) {
let __action = _action as EditHeaderCellAction | RemoveColumnAction | InsertColumnAction
//when we change has header this is not a prolbem because the undo stack is cleared when we toggle has header
if (__action.actionType === 'changeHeaderCell' && headerRowWithIndex) {
let action = __action as EditHeaderCellAction
let visualColIndex: number = action.change[1]
let beforeValue = action.change[2]
let undoPlugin = (hot as any).undoRedo
let undoneStack = undoPlugin.undoneActions as any[]
undoneStack.push(action)
headerRowWithIndex.row[visualColIndex] = beforeValue
setTimeout(() => {
hot!.render()
}, 0)
return false
} else if (__action.actionType === 'remove_col' && headerRowWithIndex) {
// let action = __action as RemoveColumnAction
let lastAction = headerRowWithIndexUndoStack.pop()
if (lastAction && lastAction.action === "removed") {
headerRowWithIndex.row.splice(lastAction.visualIndex,0, ...lastAction.headerData)
headerRowWithIndexRedoStack.push({
action: 'removed',
visualIndex: lastAction.visualIndex,
headerData: lastAction.headerData
})
}
} else if (__action.actionType === 'insert_col' && headerRowWithIndex) {
// let action = __action as InsertColumnAction
let lastAction = headerRowWithIndexUndoStack.pop()
if (lastAction && lastAction.action === "added") {
headerRowWithIndex.row.splice(lastAction.visualIndex,lastAction.headerData.length)
headerRowWithIndexRedoStack.push({
action: 'added',
visualIndex: lastAction.visualIndex,
headerData: lastAction.headerData
})
}
}
},
afterUndo: function (action: any) {
// console.log(`afterUndo`, action)
// //this is the case when we have a header row -> undo -> then we should have no header row
// if (headerRowWithIndex && action.actionType === 'remove_row' && action.index === headerRowWithIndex.physicalIndex) {
// //remove header row
// //set all settings manually because we don't use much of applyHasHeader
// //because this would insert/remove the header row but this is already done by the undo/redo
// defaultCsvReadOptions._hasHeader = false
// const el = _getById('has-header') as HTMLInputElement
// const elWrite = _getById('has-header-write') as HTMLInputElement
// el.checked = false
// elWrite.checked = false
// headerRowWithIndex = null
// applyHasHeader(true, true)
// }
//could remove columns
// syncColWidths() //covered by afterRender
},
beforeRedo: function (_action: EditHeaderCellAction | RemoveColumnAction | InsertColumnAction | any) {
let __action = _action as EditHeaderCellAction | RemoveColumnAction | InsertColumnAction
//when we change has header this is not a prolbem because the undo stack is cleared when we toggle has header
if (__action.actionType === 'changeHeaderCell' && headerRowWithIndex) {
let action = __action as EditHeaderCellAction
let visualColIndex: number = action.change[1]
let afterValue = action.change[3]
let undoPlugin = (hot as any).undoRedo
let doneStack = undoPlugin.doneActions as any[]
doneStack.push(action)
headerRowWithIndex.row[visualColIndex] = afterValue
setTimeout(() => {
hot!.render()
}, 0)
return false
} else if (__action.actionType === 'remove_col' && headerRowWithIndex) {
// let action = __action as RemoveColumnAction
let lastAction = headerRowWithIndexRedoStack.pop()
if (lastAction && lastAction.action === "removed") {
headerRowWithIndex.row.splice(lastAction.visualIndex, lastAction.headerData.length)
headerRowWithIndexUndoStack.push({
action: 'removed',
visualIndex: lastAction.visualIndex,
headerData: lastAction.headerData
})
}
} else if (__action.actionType === 'insert_col' && headerRowWithIndex) {
let lastAction = headerRowWithIndexRedoStack.pop()
if (lastAction && lastAction.action === "added") {
headerRowWithIndex.row.splice(lastAction.visualIndex, 0, ...lastAction.headerData)
headerRowWithIndexUndoStack.push({
action: 'added',
visualIndex: lastAction.visualIndex,
headerData: lastAction.headerData
})
}
}
// if (headerRowWithIndex && action.actionType === 'remove_row' && action.index === headerRowWithIndex.physicalIndex) { //first row cannot be removed normally so it must be the header row option
// //we re insert header row
// defaultCsvReadOptions._hasHeader = true
// const el = _getById('has-header') as HTMLInputElement
// const elWrite = _getById('has-header-write') as HTMLInputElement
// el.checked = true
// elWrite.checked = true
// applyHasHeader(true, true)
// }
},
/**
* isForced: Is true if rendering was triggered by a change of settings or data; or
* false if rendering was triggered by scrolling or moving selection.
*
* WE now do this in an additional hook
*/
// afterRender: function (isForced: boolean) {
// if (!isForced || isInitialHotRender) return
// //e.g. when we edit a cell and the cell must adjust the width because of the content
// //there is no other hook?
// //this is also fired on various other event (e.g. col resize...) but better sync more than miss an event
// syncColWidths()
// },
/**
* this is an array if we e.g. move consecutive columns (2,3)
* but maybe there is a way... this func should handle this anyway
* endColVisualIndex: the column is inserted left to this index
*/
afterColumnMove: (function (startColVisualIndices: number[], endColVisualIndex: number) {
if (!hot) throw new Error('table was null')
//DO not update settings while we are in some hooks!
//else the index mapping might get corrupted
// hot.updateSettings({
// colHeaders: defaultColHeaderFunc as any
// }, false)
//clear all undo redo because handsontable do not undo the col moves but the edits... which leads to wrong data!
headerRowWithIndexUndoStack.splice(0)
headerRowWithIndexRedoStack.splice(0)
let undoPlugin = (hot as any).undoRedo
undoPlugin.clear()
//dirty copy of below!!!
if (headerRowWithIndex !== null) {
//same as in columnIsQuoted... see below for docs
let temp = headerRowWithIndex
const headerRowTexts: (string | null)[] = startColVisualIndices.map(p => temp.row[p]) //for some reason we need tmp here else can be null??
let headerRowCopy: Array<string | null> = []
for (let i = 0; i <= headerRowWithIndex.row.length; i++) {
const colText = i < headerRowWithIndex.row.length ? headerRowWithIndex.row[i] : null;
let startIndex = startColVisualIndices.indexOf(i)
if (startIndex !== -1) {
continue
}
if (i === endColVisualIndex) {
headerRowCopy.push(...headerRowTexts)
}
if (i >= headerRowWithIndex.row.length) continue
headerRowCopy.push(colText)
}
headerRowWithIndex.row = headerRowCopy
}
if (columnIsQuoted) {
//we can use visual indices here because we keep {@link columnIsQuoted} up-to-date
//so after e.g. col 3 is moved to 0 columnIsQuoted[0] will contain the data from the old columnIsQuoted[3]
const startQuoteInformation: boolean[] = startColVisualIndices.map(p => columnIsQuoted[p])
//we could calculate with the indices and mutate them...
//i guess it's easier to just create a new array...
let quoteCopy: boolean[] = []
//endColVisualIndex can be columnIsQuoted.length
//e.g. when we move the first col behind the last we need to iterate to columnIsQuoted.length
//else we won't insert the quote information from the first field
for (let i = 0; i <= columnIsQuoted.length; i++) {
const quoteInfo = i < columnIsQuoted.length ? columnIsQuoted[i] : false;
let startIndex = startColVisualIndices.indexOf(i)
if (startIndex !== -1) {
continue
}
if (i === endColVisualIndex) {
//insert all moved
quoteCopy.push(...startQuoteInformation)
}
//we iterate more than we have columnIsQuoted information
//e.g. when we move the first col behind the last we need to iterate to columnIsQuoted.length
if (i >= columnIsQuoted.length) continue
quoteCopy.push(quoteInfo)
}
columnIsQuoted = quoteCopy
}
// syncColWidths() //covered by afterRender
onAnyChange()
} as any),
afterRowMove: function (startRow: number, endRow: number) {
if (!hot) throw new Error('table was null')
onAnyChange()
},
afterGetRowHeader: function (visualRowIndex: number, th: any) {
const tr = th.parentNode as HTMLTableRowElement
if (!tr || !hot) return
//is row hidden?
let physicalIndex = hot.toPhysicalRow(visualRowIndex)
if (hiddenPhysicalRowIndices.indexOf(physicalIndex) === -1) {
tr.classList.remove('hidden-row')
if (tr.previousElementSibling) {
tr.previousElementSibling.classList.remove('hidden-row-previous-row')
}
} else {
tr.classList.add('hidden-row')
//css cannot select previous elements...add a separate class
if (tr.previousElementSibling) {
tr.previousElementSibling.classList.add('hidden-row-previous-row')
}
}
},
afterCreateCol: function (visualColIndex, amount, source?: string) {
if (!hot) return
if (headerRowWithIndex) {
// const physicalIndex = hot.toPhysicalColumn(visualColIndex)
if (source !== `UndoRedo.undo` && source !== `UndoRedo.redo`) { //undo redo is already handled
headerRowWithIndexUndoStack.push({
action: 'added',
visualIndex: visualColIndex,
headerData: [...Array(amount).fill(null)],
})
headerRowWithIndex.row.splice(visualColIndex, 0, ...Array(amount).fill(null))
}
}
if (columnIsQuoted) {
// const physicalIndex = hot.toPhysicalColumn(visualColIndex)
columnIsQuoted.splice(visualColIndex, 0, ...Array(amount).fill(newColumnQuoteInformationIsQuoted))
}
// syncColWidths() //covered by afterRender
onAnyChange()
//dont' call this as it corrupts hot index mappings (because all other hooks need to finish first before we update hot settings)
//also it's not needed as handsontable already handles this internally
// updateFixedRowsCols()
},
afterRemoveCol: function (visualColIndex, amount, someting?: any, source?: string) {
let isFromUndoRedo = (source === `UndoRedo.undo` || source === `UndoRedo.redo`)
if (headerRowWithIndex && !isFromUndoRedo) { //undo redo is already handled
headerRowWithIndexUndoStack.push({
action: 'removed',
visualIndex: visualColIndex,
headerData: [headerRowWithIndex.row[visualColIndex]]
})
}
//added below
//critical because we could update hot settings here
pre_afterRemoveCol(visualColIndex, amount, isFromUndoRedo)
},
//inspired by https://github.com/handsontable/handsontable/blob/master/src/plugins/hiddenRows/hiddenRows.js
//i absolutely don't understand how handsontable implementation is working...
//their this.hiddenRows should be physical indices (see https://github.com/handsontable/handsontable/blob/master/src/plugins/hiddenRows/hiddenRows.js#L254)
//but in onAfterCreateRow & onAfterRemoveRow they check against `visualRow` which is actually the physical row (see above)
//and then they increment the physical row via the amount
//however, it works somehow...
afterCreateRow: function (visualRowIndex, amount) {
//added below
//critical because we could update hot settings here
pre_afterCreateRow(visualRowIndex, amount)
//don't do this as we are inside a hook and the next listerners will change the indices and when we call
//hot.updateSettings (inside this func) the plugin internal states are changed and the indices/mappings are corrupted
// updateFixedRowsCols()
},
afterRemoveRow: function (visualRowIndex, amount) {
//we need to modify some or all hiddenPhysicalRowIndices...
if (!hot) return
for (let i = 0; i < hiddenPhysicalRowIndices.length; i++) {
const hiddenPhysicalRowIndex = hiddenPhysicalRowIndices[i];
if (hiddenPhysicalRowIndex >= visualRowIndex) {
hiddenPhysicalRowIndices[i] -= amount
}
}
//when we have a header row and the original index was 10 and now we have only 5 rows... change index to be the last row
//so that when we disable has header we insert it correctly
// const physicalIndex = hot.toPhysicalRow(visualRowIndex)
if (headerRowWithIndex) {
const lastValidIndex = hot.countRows()
if (headerRowWithIndex.physicalIndex > lastValidIndex) {
headerRowWithIndex.physicalIndex = lastValidIndex
}
}
onAnyChange()
//dont' call this as it corrupts hot index mappings (because all other hooks need to finish first before we update hot settings)
//also it's not needed as handsontable already handles this internally
// updateFixedRowsCols()
},
//called when we select a row via row header
beforeSetRangeStartOnly: function (coords) {
},
beforeSetRangeStart: function (coords) {
if (!hot) return
if (hiddenPhysicalRowIndices.length === 0) return
const lastPossibleRowIndex = hot.countRows() - 1
const lastPossibleColIndex = hot.countCols() - 1
const actualSelection = hot.getSelectedLast()
let columnIndexModifier = 0
const isLastOrFirstRowHidden = hiddenPhysicalRowIndices.indexOf(lastPossibleRowIndex) !== -1
|| hiddenPhysicalRowIndices.indexOf(0) !== -1
let direction = 1 // or -1
if (actualSelection) {
const actualPhysicalIndex = hot.toPhysicalRow(actualSelection[0])
direction = actualPhysicalIndex < coords.row ? 1 : -1
//direction is invalid if actualPhysicalIndex === 0 && coords.row === lastPossibleRowIndex
//this is because the last row is hidden...
//move up but last row is hidden
if (isLastOrFirstRowHidden && coords.row === lastPossibleRowIndex && actualPhysicalIndex === 0) { //
direction = -1
}
//move down on last row but first row is hidden
else if (isLastOrFirstRowHidden && coords.row === 0 && actualPhysicalIndex === lastPossibleRowIndex) {
direction = 1
}
}
const getNextRow: (a: number) => number = (visualRowIndex: number) => {
let visualRow = visualRowIndex;
//@ts-ignore
let physicalIndex = hot.toPhysicalRow(visualRowIndex)
if (visualRow > lastPossibleRowIndex) { //moved under the last row
columnIndexModifier = 1
return getNextRow(0)
}
if (visualRow < 0) { //we moved above row 0
columnIndexModifier = -1
return getNextRow(lastPossibleRowIndex)
}
if (hiddenPhysicalRowIndices.indexOf(physicalIndex) !== -1) {
//row is hidden
return getNextRow(visualRow + direction)
}
return visualRow
}
coords.row = getNextRow(coords.row)
if (lastHandsonMoveWas !== 'tab') {
coords.col = coords.col + (isLastOrFirstRowHidden ? columnIndexModifier : 0)
}
if (coords.col > lastPossibleColIndex) {
coords.col = 0
}
else if (coords.col < 0) {
coords.col = lastPossibleColIndex
}
lastHandsonMoveWas = null
},
//called multiple times when we move mouse while selecting...
beforeSetRangeEnd: function () {
},
rowHeights: function (visualRowIndex: number) {
//see https://handsontable.com/docs/6.2.2/Options.html#rowHeights
let defaultHeight = 23
if (!hot) return defaultHeight
const actualPhysicalIndex = hot.toPhysicalRow(visualRowIndex)
//some hack so that the renderer still respects the row... (also see http://embed.plnkr.co/lBmuxU/)
//this is needed else we render all hidden rows as blank spaces (we see a scrollbar but not rows/cells)
//but this means we will lose performance because hidden rows are still managed and rendered (even if not visible)
if (hiddenPhysicalRowIndices.includes(actualPhysicalIndex)) {
//sub 1 height is treated by the virtual renderer as height 0??
//we better add some more zeros
return 0.000001
}
return defaultHeight
} as any,
beforeKeyDown: function (event: KeyboardEvent) {
//we need this because when editing header cell the hot instance thinks some editor is active and would pass the inputs to the next cell...
if (editHeaderCellTextInputEl) {
event.stopImmediatePropagation()
return
}
//NOTE that this can prevent all vs code shortcuts... e.g. cmd+p (on mac)!!!
if (event.ctrlKey && event.shiftKey && event.altKey && event.key === 'ArrowDown') {
event.stopImmediatePropagation()
insertRowBelow()
} else if (event.ctrlKey && event.shiftKey && event.altKey && event.key === 'ArrowUp') {
event.stopImmediatePropagation()
insertRowAbove()
} else if (event.ctrlKey && event.shiftKey && event.altKey && event.key === 'ArrowLeft') {
event.stopImmediatePropagation()
insertColLeft()
} else if (event.ctrlKey && event.shiftKey && event.altKey && event.key === 'ArrowRight') {
event.stopImmediatePropagation()
insertColRight()
}
} as any,
})
//@ts-ignore
Handsontable.dom.addEvent(window as any, 'resize', throttle(onResizeGrid, 200))
if (typeof afterHandsontableCreated !== 'undefined') afterHandsontableCreated(hot)
hot.addHook('afterRender', afterRenderForced as any)
hot.getPlugin('copyPaste').rowsLimit = copyPasteRowLimit
hot.getPlugin('copyPaste').columnsLimit = copyPasteColLimit
const oldShouldApplyHeaderReadOption = defaultCsvReadOptions._hasHeader
const settingsApplied = checkIfHasHeaderReadOptionIsAvailable(true)
//if we have only 1 row and header is enabled by default...this would be an error (we cannot display something)
if (oldShouldApplyHeaderReadOption === true) {
if (settingsApplied === true) { //this must be applied else we get duplicate first row
_applyHasHeader(true, false)
updateFixedRowsCols()
} else {
//head cannot be applied (because only 1 or 0 rows) ... but settings say user want to has header...
//set auto enable if we have enough rows
setShouldAutpApplyHasHeader(true)
}
}
isInitialHotRender = false
if (allColWidths && allColWidths.length > 0) {
//apply old width
applyColWidths()
}
//make sure we see something (right size)...
onResizeGrid()
//because main.ts is loaded before this the first init must be manually...
afterHandsontableCreated(hot!)
setupScrollListeners()
if (hot) {
//select first cell by default so we have always a context
hot.selectCell(0, 0)
}
}
/**
* should be called if anything was changes
* then we set the editor to has changes
*/
function onAnyChange(changes?: CellChanges[] | null, reason?: string) {
//this is the case on init (because initial data set)
//also when we reset data (button)
//when we trim all cells (because this sets the data value via hot.updateSettings)
if (changes === null && reason && reason.toLowerCase() === 'loaddata') {
return
}
if (reason && reason === 'edit' && changes && changes.length > 0) {
//handsontable even emits an event if the value stayed the same...
const hasChanges = changes.some(p => p[2] !== p[3])
if (!hasChanges) return
}
//we need to check the value cache because the user could have cleared the input and then closed the widget
//but if we have an old search we re-open the old search which is now invalid...
if (findWidgetInstance.findWidgetInputValueCache !== '') {
findWidgetInstance.tableHasChangedAfterSearch = true
findWidgetInstance.showOrHideOutdatedSearchIndicator(true)
}
postSetEditorHasChanges(true)
}
/**
* updates the handson table to fill available space (will trigger scrollbars)
*/
function onResizeGrid() {
if (!hot) return
const widthString = getComputedStyle(csvEditorWrapper).width
if (!widthString) {
_error(`could not resize table, width string was null`)
return
}
const width = parseInt(widthString.substring(0, widthString.length - 2))
const heightString = getComputedStyle(csvEditorWrapper).height
if (!heightString) {
_error(`could not resize table, height string was null`)
return
}
const height = parseInt(heightString.substring(0, heightString.length - 2))
hot.updateSettings({
width: width,
height: height,
}, false)
//get all col sizes
syncColWidths()
}
/**
* applies the stored col widths to the ui
*/
function applyColWidths() {
if (!hot) return
//this is a bit messy but it works...??
// console.log(`col widths applies`, allColWidths)
//snatched from https://github.com/YaroslavOvdii/fliplet-widget-data-source/blob/master/js/spreadsheet.js
hot.getSettings().manualColumnResize = false
let autoSizedWidths = _getColWidths()
//maybe the user removed columns so we don't have all widths... e.g. remove cols then reset data...
//we keep the col widths we have and add the auto size ones for the columns where we don't have old sizes...
//NOTE we don't store the column names so we probably apply the wrong size to the wrong columns, e.g. 2 cols, reset 5 columns -> first 2 columns will get the old size of the old 2 columns
for (let i = allColWidths.length; i < autoSizedWidths.length; i++) {
const colWidth = autoSizedWidths[i]
allColWidths.push(colWidth)
}
//note that setting colWidths will disable the auto size column plugin (see Plugin AutoColumnSize.isEnabled)
//it is enabled if (!colWidths)
hot.updateSettings({ colWidths: allColWidths }, false)
hot.getSettings().manualColumnResize = true
hot.updateSettings({}, false)
hot.getPlugin('autoColumnSize').enablePlugin()
}
/**
* syncs the {@link allColWidths} with the ui/handsonable state
*/
function syncColWidths() {
allColWidths = _getColWidths()
// console.log('col widths synced', allColWidths);
}
function _getColWidths(): number[] {
if (!hot) return []
//@ts-ignore
return hot.getColHeader().map(function (header, index) {
return hot!.getColWidth(index)
})
}
/**
* generates the default html wrapper code for the given column name OR uses {@link headerRowWithIndex}
* we add a delete icon
* @param {number} colIndex the physical column index (user could have moved cols so visual first col is not the physical second) use https://handsontable.com/docs/6.2.2/RecordTranslator.html to translate
* call like hot.toVisualColumn(colIndex)
* @param {string | undefined | null} colName
* @param useLettersAsColumnNames true: use excel like letters for column names, false: use the index BUT an explicit colName will take precedence over this setting
*/
function defaultColHeaderFunc(useLettersAsColumnNames: boolean, colIndex: number, colName: string | undefined | null) {
let text = useLettersAsColumnNames
? spreadsheetColumnLetterLabel(colIndex)
: getSpreadsheetColumnLabel(colIndex)
if (headerRowWithIndex !== null && colIndex < headerRowWithIndex.row.length) {
let visualIndex = colIndex
if (hot) {
visualIndex = hot.toVisualColumn(colIndex) //use visual column because we keep headerRowWithIndex up-to-date
//when adding/removing/moving columns
}
const data = headerRowWithIndex.row[visualIndex]
//however, after opening the cell editor null becomes the empty string (after committing the value)...
if (data !== null) {
text = data
}
}
//null can also happen if we enable header, add column, disable header, enable header (then the new column have null values)
if (colName !== undefined && colName !== null) {
text = colName
}
let visualIndex = colIndex
if (!hot) return ``
// if (!hot) {
// return `${text} <span class="remove-col clickable" onclick="removeColumn(${visualIndex})" style="visibility: hidden"><i class="fas fa-trash"></i></span>`
// }
visualIndex = hot.toVisualColumn(colIndex)
if (hot.countCols() === 1 || isReadonlyMode) {
return `${text} <span class="remove-col clickable" onclick="removeColumn(${visualIndex})" style="visibility: hidden"><i class="fas fa-trash"></i></span>`
}
return `${text} <span class="remove-col clickable" onclick="removeColumn(${visualIndex})"><i class="fas fa-trash"></i></span>`
}
/**
* displays or hides the help modal
* @param isVisible
*/
function toggleHelpModal(isVisible: boolean) {
if (isVisible) {
helModalDiv.classList.add('is-active')
return
}
helModalDiv.classList.remove('is-active')
}
/**
* displays or hides the ask read again modal
* @param isVisible
*/
function toggleAskReadAgainModal(isVisible: boolean) {
if (isVisible) {
askReadAgainModalDiv.classList.add('is-active')
return
}
askReadAgainModalDiv.classList.remove('is-active')
}
/**
* displays or hides the ask read file gain modal
* @param isVisible
*/
function toggleAskReloadFileModalDiv(isVisible: boolean) {
if (isVisible) {
askReloadFileModalDiv.classList.add('is-active')
return
}
askReloadFileModalDiv.classList.remove('is-active')
}
/**
* displays or hides the source file changed modal
* @param isVisible
*/
function toggleSourceFileChangedModalDiv(isVisible: boolean) {
if (isVisible) {
sourceFileChangedDiv.classList.add('is-active')
return
}
sourceFileChangedDiv.classList.remove('is-active')
}
/**
* parses and displays the given data (csv)
* @param {string} content
*/
function resetData(content: string, csvReadOptions: CsvReadOptions) {
const _data = parseCsv(content, csvReadOptions)
// console.log(`_data`, _data)
displayData(_data, csvReadOptions)
//might be bigger than the current view
onResizeGrid()
toggleAskReadAgainModal(false)
}
/**
* a wrapper for resetData to display status text when rendering
*/
function resetDataFromResetDialog() {
toggleAskReadAgainModal(false)
postSetEditorHasChanges(false)
startRenderData()
}
/**
* we need this method first because in case we have unsaved changes we need to display a dialog
* if all changes are written to the file we can proceed without displaying a dialog
*/
function preReloadFileFromDisk() {
const hasAnyChanges = getHasAnyChangesUi()
if (hasAnyChanges) {
toggleAskReloadFileModalDiv(true)
return
}
reloadFileFromDisk()
}
/**
* reloads the file from disk
*/
function reloadFileFromDisk() {
toggleAskReloadFileModalDiv(false)
toggleSourceFileChangedModalDiv(false)
_setHasUnsavedChangesUiIndicator(false)
postReloadFile()
}
function startReceiveCsvProgBar() {
receivedCsvProgBar.value = 0
receivedCsvProgBarWrapper.style.display = "block"
}
function intermediateReceiveCsvProgBar() {
receivedCsvProgBar.attributes.removeNamedItem('value')
}
function stopReceiveCsvProgBar() {
receivedCsvProgBarWrapper.style.display = "none"
}
/**
* called from ui
* @param saveSourceFile
*/
function postApplyContent(saveSourceFile: boolean) {
if (isReadonlyMode) return
const csvContent = getDataAsCsv(defaultCsvReadOptions, defaultCsvWriteOptions)
//used to clear focus... else styles are not properly applied
//@ts-ignore
if (document.activeElement !== document.body) document.activeElement.blur();
_postApplyContent(csvContent, saveSourceFile)
}
/**
* the height for the th element
* @param rows total number of rows
*/
function getRowHeaderWidth(rows: number) {
const parentPadding = 5 * 2 //th has 1 border + 4 padding on both sides
const widthMultiplyFactor = 10 //0-9 are all <10px width (with the current font)
const iconPadding = 4
const binIcon = 14
const hiddenRowIcon = 10
const len = rows.toString().length * widthMultiplyFactor + binIcon + iconPadding + parentPadding + hiddenRowIcon
return len
//or Math.ceil(Math.log10(num + 1)) from https://stackoverflow.com/questions/10952615/length-of-number-in-javascript
}
function trimAllCells() {
if (!hot) throw new Error('table was null')
const numRows = hot.countRows()
const numCols = hot.countCols()
const allData = getData()
let data: string = ''
let hasAnyChanges = false
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
data = allData[row][col]
if (typeof data !== "string") {
// console.log(`${row}, ${col} no string`)
continue
}
allData[row][col] = data.trim()
if (allData[row][col] !== data) {
hasAnyChanges = true
}
//tooo slow for large tables
// hot.setDataAtCell(row, col, data.trim())
}
}
if (headerRowWithIndex) {
for (let col = 0; col < headerRowWithIndex.row.length; col++) {
const data = headerRowWithIndex.row[col]
if (typeof data !== "string") {
continue
}
headerRowWithIndex.row[col] = data.trim();
if (headerRowWithIndex.row[col] !== data) {
hasAnyChanges = true
}
}
}
hot.updateSettings({
data: allData
}, false)
//hot.updateSettings reloads data and thus afterChange hook is triggered
//BUT the change reason is loadData and thus we ignore it...
if (hasAnyChanges) {
onAnyChange()
}
// const afterData = getData()
// for (let row = 0; row < numRows; row++) {
// for (let col = 0; col < numCols; col++) {
// if (afterData[row][col] !== allData[row][col]) {
// console.log(`${row}, ${col}`)
// }
// }
// }
}
function showOrHideAllComments(show: boolean) {
if (show) {
showCommentsBtn.style.display = 'none'
hideCommentsBtn.style.display = 'initial'
hiddenPhysicalRowIndices = []
}
else {
showCommentsBtn.style.display = 'initial'
hideCommentsBtn.style.display = 'none'
if (hot) {
hiddenPhysicalRowIndices = _getCommentIndices(getData(), defaultCsvReadOptions)
hiddenPhysicalRowIndices = hiddenPhysicalRowIndices.map(p => hot!.toPhysicalRow(p))
}
}
if (!hot) return
hot.render()
}
function getAreCommentsDisplayed(): boolean {
return showCommentsBtn.style.display === 'none'
}
function _setHasUnsavedChangesUiIndicator(hasUnsavedChanges: boolean) {
if (hasUnsavedChanges) {
unsavedChangesIndicator.classList.remove('op-hidden')
} else {
unsavedChangesIndicator.classList.add('op-hidden')
}
}
function getHasAnyChangesUi(): boolean {
return unsavedChangesIndicator.classList.contains("op-hidden") === false
}
function _setIsWatchingSourceFileUiIndicator(isWatching: boolean) {
if (isWatching) {
sourceFileUnwatchedIndicator.classList.add('op-hidden')
} else {
sourceFileUnwatchedIndicator.classList.remove('op-hidden')
}
}
/**
* changes to font size via updating the css variable and applying css classes
* also re renders the table to update the column widths (manually changed column width will stay the same (tested) on rerender)
*/
function changeFontSizeInPx(fontSizeInPx: number) {
document.documentElement.style.setProperty('--extension-font-size', `${fontSizeInPx.toString()}px`)
if (fontSizeInPx <= 0) {
//remove custom font size and use editor font size
document.body.classList.remove('extension-settings-font-size')
document.body.classList.add('vs-code-settings-font-size')
} else {
document.body.classList.add('extension-settings-font-size')
document.body.classList.remove('vs-code-settings-font-size')
}
reRenderTable()
}
/**
* applies the fixed rows and cols settings (normally called after a row/col added/removed)
* ONLY call this if all other hot hooks have run else the data gets out of sync
* this is because the manualRowMove (and other) plugins update index mappings and when we call
* updateSettings during that the plugins get disabled and enabled and the data gets out of sync (the mapping)
* ONLY if the {@link defaultCsvReadOptions._hasHeader} is false
*/
function updateFixedRowsCols() {
if (!hot) return
hot.updateSettings({
fixedRowsTop: Math.max(fixedRowsTop, 0),
fixedColumnsLeft: Math.max(fixedColumnsLeft, 0),
}, false)
}
/**
* increments the {@link fixedRowsTop} by 1
*/
function incFixedRowsTop() {
_changeFixedRowsTop(fixedRowsTop + 1)
}
/**
* decrements the {@link fixedRowsTop} by 1
*/
function decFixedRowsTop() {
_changeFixedRowsTop(fixedRowsTop - 1)
}
/**
* no use this directly in the ui as {@link fixedRowsTop} name could change
* @param newVal
*/
function _changeFixedRowsTop(newVal: number) {
fixedRowsTop = Math.max(newVal, 0)
fixedRowsTopInfoSpan.innerText = fixedRowsTop.toString()
updateFixedRowsCols()
}
function _toggleFixedRowsText() {
const isHidden = fixedRowsTopText.classList.contains('dis-hidden')
if (isHidden) {
fixedRowsTopText.classList.remove('dis-hidden')
} else {
fixedRowsTopText.classList.add('dis-hidden')
}
}
/**
* increments the {@link fixedColumnsLeft} by 1
*/
function incFixedColsLeft() {
_changeFixedColsLeft(fixedColumnsLeft + 1)
}
/**
* decrements the {@link fixedColumnsLeft} by 1
*/
function decFixedColsLeft() {
_changeFixedColsLeft(fixedColumnsLeft - 1)
}
/**
* no use this directly in the ui as {@link fixedColumnsLeft} name could change
* @param newVal
*/
function _changeFixedColsLeft(newVal: number) {
fixedColumnsLeft = Math.max(newVal, 0)
fixedColumnsTopInfoSpan.innerText = fixedColumnsLeft.toString()
updateFixedRowsCols()
}
function _toggleFixedColumnsText() {
const isHidden = fixedColumnsTopText.classList.contains('dis-hidden')
if (isHidden) {
fixedColumnsTopText.classList.remove('dis-hidden')
} else {
fixedColumnsTopText.classList.add('dis-hidden')
}
}
const minSidebarWidthInPx = 150
const collapseSidePanelThreshold = 60 //if we drag the handle e.g. between left: [0, 80] we collapse the side panel, so this is the left space to the left window border
/**
* setsup the sidedbar resize handle events
*/
function setupSideBarResizeHandle() {
let downX: number | null = null
let _style = window.getComputedStyle(sidePanel)
let downWidth: number = minSidebarWidthInPx
sideBarResizeHandle.addEventListener(`mousedown`, (e) => {
downX = e.clientX
_style = window.getComputedStyle(sidePanel)
downWidth = parseInt(_style.width.substring(0, _style.width.length - 2))
if (isNaN(downWidth)) downWidth = minSidebarWidthInPx
})
document.addEventListener(`mousemove`, throttle((e: MouseEvent) => {
if (downX === null) return
const delta = e.clientX - downX
sidePanel.style.width = `${Math.max(downWidth + delta, minSidebarWidthInPx)}px`
sidePanel.style.maxWidth = `${Math.max(downWidth + delta, minSidebarWidthInPx)}px`
if (vscode) {
const isSidePanelCollapsed = getIsSidePanelCollapsed()
if (e.clientX <= collapseSidePanelThreshold) {
//we want to collapse the side panel
if (!isSidePanelCollapsed) toggleSidePanel(true)
} else {
//this is not really possible because we cannot drag the collapsed panel...
//ensude the side panel is not collapsed (expanded)
if (isSidePanelCollapsed) toggleSidePanel(false)
}
}
onResizeGrid()
}, 200))
document.addEventListener(`mouseup`, (e) => {
downX = null
})
}
function getHandsontableOverlayScrollLeft(): HTMLDivElement | null {
const overlayWrapper = document.querySelector(`#csv-editor-wrapper .ht_master .wtHolder`)
if (!overlayWrapper) {
console.warn(`could not find handsontable overlay wrapper`)
return null
}
return overlayWrapper as HTMLDivElement
}
function setupScrollListeners() {
let overlayWrapper = getHandsontableOverlayScrollLeft()!
if (_onTableScrollThrottled) {
overlayWrapper.removeEventListener(`scroll`, _onTableScrollThrottled)
}
_onTableScrollThrottled = throttle(_onTableScroll, 100)
overlayWrapper.addEventListener(`scroll`, _onTableScrollThrottled)
}
function _onTableScroll(e: Event) {
if (!editHeaderCellTextInputEl) return
let scrollLeft = (e.target as HTMLElement).scrollLeft
editHeaderCellTextInputEl.style.left = `${editHeaderCellTextInputLeftOffsetInPx - (scrollLeft - handsontableOverlayScrollLeft)}px`
}
/**
* gets if the side panel is collapsed (true) or not (false)
*/
function getIsSidePanelCollapsed(): boolean {
//only in vs code
if (vscode) {
return window.getComputedStyle(leftPanelToggleIconExpand).display === 'block'
}
//panel cannot be collapsed in browser
return false
}
/**
* toggles the side panel
*/
function toggleSidePanel(shouldCollapse?: boolean) {
//only in extension (not in browser)
if (vscode && shouldCollapse === undefined) {
const isSidePanelCollapsed = getIsSidePanelCollapsed()
if (isSidePanelCollapsed) {
shouldCollapse = false
} else {
shouldCollapse = true
}
}
document.documentElement.style
.setProperty('--extension-side-panel-display', shouldCollapse ? `none` : `flex`)
document.documentElement.style
.setProperty('--extension-side-panel-expand-icon-display', shouldCollapse ? `block` : `none`)
document.documentElement.style
.setProperty('--extension-side-panel-collapse-icon-display', shouldCollapse ? `none` : `block`)
onResizeGrid()
if (shouldCollapse) {
//will be hidden
} else {
//we now display the stats ... calculate it
recalculateStats()
}
}
// ------------------------------------------------------
/*maybe this is not needed but it can be dangerous to call hot.updateSettings while indices/mappings are updated
e.g. when we call {@link updateFixedRowsCols} during afterCreateRow and
move row 5 below row 1 then try to add a row below row 1 it is added 2 rows below and row 5 is at is't ols position...
so we only store the events we get and call them after a rerender (which is hopefully are called last)
*/
type RecordedHookAction = 'afterRemoveCol' | 'afterCreateRow'
let recordedHookActions: RecordedHookAction[]
type HookItem = {
actionName: RecordedHookAction
action: Function
}
let hook_list: HookItem[] = []
function afterRenderForced(isForced: boolean) {
if (!isForced) {
hook_list = []
recordedHookActions = []
return
}
//hot.alter forced a rerender
//and we can only run our hooks after hot has updated internal mappings and indices
//so we kepp track if our hooks were fired and execute them after the rerender
for (let i = 0; i < hook_list.length; i++) {
const hookItem = hook_list[i];
if (!recordedHookActions.includes(hookItem.actionName)) continue
//prevent infinite loop if we render in action
hook_list.splice(i, 1)
hookItem.action()
}
hook_list = []
recordedHookActions = []
if (!isForced || isInitialHotRender) return
//e.g. when we edit a cell and the cell must adjust the width because of the content
//there is no other hook?
//this is also fired on various other event (e.g. col resize...) but better sync more than miss an event
syncColWidths()
}
function pre_afterRemoveCol(this: any, visualColIndex: number, amount: number, isFromUndoRedo: boolean) {
recordedHookActions.push("afterRemoveCol")
hook_list.push({
actionName: 'afterRemoveCol',
action: afterRemoveCol.bind(this, visualColIndex, amount, isFromUndoRedo)
})
}
function afterRemoveCol(visualColIndex: number, amount: number, isFromUndoRedo: boolean) {
if (!hot) return
if (headerRowWithIndex && !isFromUndoRedo) {
headerRowWithIndex.row.splice(visualColIndex, amount)
//hot automatically re-renders after this
}
const sortConfigs = hot.getPlugin('columnSorting').getSortConfig()
const sortedColumnIds = sortConfigs.map(p => hot!.toPhysicalColumn(p.column))
let removedColIds: number[] = []
for (let i = 0; i < amount; i++) {
removedColIds.push(hot.toPhysicalColumn(visualColIndex + i))
}
//if we removed some col that was sorted then clear sorting...
if (sortedColumnIds.some(p => removedColIds.includes(p))) {
hot.getPlugin('columnSorting').clearSort()
}
if (columnIsQuoted) {
// const physicalIndex = hot.toPhysicalColumn(visualColIndex)
columnIsQuoted.splice(visualColIndex, amount)
}
allColWidths.splice(visualColIndex, 1)
//critical might update settings
applyColWidths()
// syncColWidths() //covered by afterRender
onAnyChange()
//dont' call this as it corrupts hot index mappings (because all other hooks need to finish first before we update hot settings)
//also it's not needed as handsontable already handles this internally
// updateFixedRowsCols()
}
function pre_afterCreateRow(this: any, visualRowIndex: number, amount: number) {
recordedHookActions.push("afterCreateRow")
hook_list.push({
actionName: 'afterCreateRow',
action: afterCreateRow.bind(this, visualRowIndex, amount)
})
}
//inspired by https://github.com/handsontable/handsontable/blob/master/src/plugins/hiddenRows/hiddenRows.js
//i absolutely don't understand how handsontable implementation is working...
//their this.hiddenRows should be physical indices (see https://github.com/handsontable/handsontable/blob/master/src/plugins/hiddenRows/hiddenRows.js#L254)
//but in onAfterCreateRow & onAfterRemoveRow they check against `visualRow` which is actually the physical row (see above)
//and then they increment the physical row via the amount
//however, it works somehow...
function afterCreateRow(visualRowIndex: number, amount: number) {
//added below
//critical because we could update hot settings here
//we need to modify some or all hiddenPhysicalRowIndices...
for (let i = 0; i < hiddenPhysicalRowIndices.length; i++) {
const hiddenPhysicalRowIndex = hiddenPhysicalRowIndices[i];
if (hiddenPhysicalRowIndex >= visualRowIndex) {
hiddenPhysicalRowIndices[i] += amount
}
}
onAnyChange()
//dont' call this as it corrupts hot index mappings (because all other hooks need to finish first before we update hot settings)
//also it's not needed as handsontable already handles this internally
// updateFixedRowsCols()
checkAutoApplyHasHeader()
}
function showColHeaderNameEditor(visualColIndex: number) {
if (!headerRowWithIndex) return
if (!lastClickedHeaderCellTh) return
//see https://stackoverflow.com/questions/18348437/how-do-i-edit-the-header-text-of-a-handsontable
//update hot
//col resizing? ok because input loses focus
//long render indicators are not really necessary at this point because 100k row files only takes 1-2s
//does work with virtual indices (e.g. when we reordered the columns)
let rect = lastClickedHeaderCellTh.getBoundingClientRect()
let input = document.createElement(`input`)
input.setAttribute(`type`, `text`)
input.style.position = `absolute`
input.style.left = `${rect.left}px`
editHeaderCellTextInputLeftOffsetInPx = rect.left
input.style.top = `${rect.top}px`
input.style.width = `${rect.width}px`
input.style.height = `${rect.height}px`
input.style.zIndex = `1000`
input.value = headerRowWithIndex.row[visualColIndex] ?? ''
editHeaderCellTextInputEl = input
let overlayWrapper = getHandsontableOverlayScrollLeft()!
handsontableOverlayScrollLeft = overlayWrapper.scrollLeft
let inputWasRemoved = false
const removeInput = () => {
editHeaderCellTextInputEl = null
//this also calls blur
if (inputWasRemoved) return
inputWasRemoved = true
input.remove()
}
//blur -> commit
//esc -> revert
const beforeValue = input.value
//set to false initially e.g. when we focus some other window we don't want to apply changes
let shouldApplyChanges = true
let applyChange = () => {
shouldApplyChanges = false
if (headerRowWithIndex && beforeValue !== input.value) {
headerRowWithIndex.row[visualColIndex] = input.value
let undoPlugin = (hot as any).undoRedo
let doneStack = undoPlugin.doneActions as any[]
let editHeaderRow: EditHeaderCellAction = {
actionType: 'changeHeaderCell',
change: [0, visualColIndex, beforeValue, input.value]
}
doneStack.push(editHeaderRow)
//TODO show indicator?
hot!.render()
}
}
let addListeners = () => {
input.addEventListener(`blur`, () => {
if (shouldApplyChanges) {
applyChange()
}
removeInput()
})
input.addEventListener(`keyup`, (e) => {
if (e.key.toLocaleLowerCase() === `escape`) {
shouldApplyChanges = false
removeInput()
}
if (e.key.toLocaleLowerCase() === `enter`) {
shouldApplyChanges = true
applyChange()
removeInput()
}
})
}
document.body.appendChild(input)
setTimeout(() => {
addListeners()
// input.select()
})
}
function _updateToggleReadonlyModeUi() {
console.log(`asdasdasdas`)
//new state is isReadonlyMode
if (isReadonlyMode) {
isReadonlyModeToggleSpan.classList.add(`active`)
isReadonlyModeToggleSpan.title = `Sets the table to edit mode`
//disable edit ui
const btnEditableUi = document.querySelectorAll(`.on-readonly-disable-btn`)
for (let i = 0; i < btnEditableUi.length; i++) {
btnEditableUi.item(i).setAttribute('disabled','true')
}
const divEditableUi = document.querySelectorAll(`.on-readonly-disable-div`)
for (let i = 0; i < divEditableUi.length; i++) {
divEditableUi.item(i).classList.add('div-readonly-disabled')
}
} else {
isReadonlyModeToggleSpan.classList.remove(`active`)
isReadonlyModeToggleSpan.title = `Sets the table to readonly mode`
//enable edit ui
const btnEditableUi = document.querySelectorAll(`.on-readonly-disable-btn`)
for (let i = 0; i < btnEditableUi.length; i++) {
btnEditableUi.item(i).removeAttribute('disabled')
}
const divEditableUi = document.querySelectorAll(`.on-readonly-disable-div`)
for (let i = 0; i < divEditableUi.length; i++) {
divEditableUi.item(i).classList.remove('div-readonly-disabled')
}
}
}
function toggleReadonlyMode() {
if (!hot) return
isReadonlyMode = !isReadonlyMode
hot.updateSettings({
readOnly: isReadonlyMode,
manualRowMove: !isReadonlyMode,
manualColumnMove: !isReadonlyMode,
undo: !isReadonlyMode
}, false)
_updateToggleReadonlyModeUi()
} | the_stack |
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
EyeOutlined,
EyeInvisibleOutlined,
NodeIndexOutlined,
DisconnectOutlined,
TagOutlined,
SearchOutlined,
HighlightOutlined,
} from '@ant-design/icons';
const isBrowser = typeof window !== 'undefined';
const G6 = isBrowser ? require('@antv/g6') : null;
const insertCss = isBrowser ? require('insert-css') : null;
const modifyCSS = isBrowser ? require('@antv/dom-util/lib/modify-css').default : null;
if (isBrowser) {
insertCss(`
#canvas-menu {
position: absolute;
z-index: 2;
left: 16px;
top: 80px;
width: fit-content;
padding: 8px 16px;
background-color: rgba(54, 59, 64, 0);
border-radius: 24px;
box-shadow: 0 5px 18px 0 rgba(0, 0, 0, 0);
font-family: PingFangSC-Semibold;
transition: all 0.2s linear;
}
#canvas-menu:hover {
background-color: rgba(54, 59, 64, 1);
box-shadow: 0 5px 18px 0 rgba(0, 0, 0, 0.6);
}
.icon-span {
padding-left: 8px;
padding-right: 8px;
cursor: pointer;
}
#search-node-input {
background-color: rgba(60, 60, 60, 0.95);
border-radius: 21px;
width: 100px;
border-color: rgba(80, 80, 80, 0.95);
border-style: solid;
color: rgba(255, 255, 255, 0.85);
}
#submit-button {
background-color: rgba(82, 115, 224, 0.2);
border-radius: 21px;
border-color: rgb(82, 115, 224);
border-style: solid;
color: rgba(152, 165, 254, 1);
margin-left: 4px;
}
.menu-tip {
position: absolute;
right: calc(30% + 32px);
width: fit-content;
height: 40px;
line-height: 40px;
top: 80px;
padding-left: 16px;
padding-right: 16px;
background-color: rgba(54, 59, 64, 0.5);
color: rgba(255, 255, 255, 0.65);
border-radius: 8px;
transition: all 0.2s linear;
font-family: PingFangSC-Semibold;
}
#g6-canavs-menu-item-tip {
position: absolute;
background-color: rgba(0,0,0, 0.65);
padding: 10px;
box-shadow: rgba(0, 0, 0, 0.6) 0px 0px 10px;
width: fit-content;
color: #fff;
border-radius: 8px;
font-size: 12px;
height: fit-content;
font-family: PingFangSC-Semibold;
transition: all 0.2s linear;
}
`);
}
let fishEye = null;
const CanvasMenu: React.FC<{
graph: any;
clickFisheyeIcon: (onlyDisable?: boolean) => void;
clickLassoIcon: (onlyDisable?: boolean) => void;
fisheyeEnabled: boolean;
lassoEnabled: boolean;
edgeLabelVisible: boolean;
setEdgeLabelVisible: (vis: boolean) => void;
searchNode: (id: string) => boolean;
handleFindPath: () => void;
stopLayout: () => void;
}> = ({
graph,
clickFisheyeIcon,
clickLassoIcon,
fisheyeEnabled,
lassoEnabled,
stopLayout,
edgeLabelVisible,
setEdgeLabelVisible,
searchNode,
handleFindPath,
}) => {
const { t } = useTranslation();
// menu tip, 例如 “按下 ESC 退出鱼眼”
const [menuTip, setMenuTip] = useState({
text: '',
display: 'none',
opacity: 0,
});
// menu item tip
const [menuItemTip, setMenuItemTip] = useState({
text: '',
display: 'none',
opacity: 0,
});
const [enableSearch, setEnableSearch] = useState(false);
const [enableSelectPathEnd, setEnableSelectPathEnd] = useState(false);
const clickEdgeLabelController = () => {
setEdgeLabelVisible(!edgeLabelVisible);
};
const handleEnableSearch = () => {
// 关闭 lasso 框选
if (lassoEnabled) clickLassoIcon(true);
// 关闭选择路径端点
if (enableSelectPathEnd) setEnableSelectPathEnd(false);
// 关闭搜索节点框
if (enableSearch) setEnableSearch(false);
// 关闭 fisheye
if (fisheyeEnabled && fishEye) {
graph.removePlugin(fishEye);
clickFisheyeIcon(true);
}
setEnableSearch((old) => {
if (old) {
// 设置 menuTip
setMenuTip({
text: '',
display: 'none',
opacity: 0,
});
return false;
}
// 设置 menuTip
setMenuTip({
text: t('输入需要搜索的节点 ID,并点击 Submit 按钮'),
display: 'block',
opacity: 1,
});
return true;
});
};
// 放大
const handleZoomOut = () => {
if (!graph || graph.destroyed) return;
const current = graph.getZoom();
const canvas = graph.get('canvas');
const point = canvas.getPointByClient(canvas.get('width') / 2, canvas.get('height') / 2);
const pixelRatio = canvas.get('pixelRatio') || 1;
const ratio = 1 + 0.05 * 5;
if (ratio * current > 5) {
return;
}
graph.zoom(ratio, { x: point.x / pixelRatio, y: point.y / pixelRatio });
};
// 缩小
const handleZoomIn = () => {
if (!graph || graph.destroyed) return;
const current = graph.getZoom();
const canvas = graph.get('canvas');
const point = canvas.getPointByClient(canvas.get('width') / 2, canvas.get('height') / 2);
const pixelRatio = canvas.get('pixelRatio') || 1;
const ratio = 1 - 0.05 * 5;
if (ratio * current < 0.3) {
return;
}
graph.zoom(ratio, { x: point.x / pixelRatio, y: point.y / pixelRatio });
};
const handleFitViw = () => {
if (!graph || graph.destroyed) return;
graph.fitView(16);
};
const handleSearchNode = () => {
const value = (document.getElementById('search-node-input') as HTMLInputElement).value;
const found = searchNode(value);
if (!found)
setMenuTip({
text: t('没有找到该节点'),
display: 'block',
opacity: 1,
});
};
const showItemTip = (e, text) => {
const { clientX: x, clientY: y } = e;
setMenuItemTip({
text,
display: 'block',
opacity: 1,
});
const tipDom = document.getElementById('g6-canavs-menu-item-tip');
modifyCSS(tipDom, {
top: `${124}px`,
left: `${x - 20}px`,
zIndex: 100,
});
};
const hideItemTip = () => {
setMenuItemTip({
text: '',
display: 'none',
opacity: 0,
});
const tipDom = document.getElementById('g6-canavs-menu-item-tip');
modifyCSS(tipDom, {
zIndex: -100,
});
};
/**
* 打开或关闭鱼眼放大功能
*/
const toggleFishEye = () => {
if (!graph || graph.destroyed) return;
// 设置鼠标样式为默认
graph.get('canvas').setCursor('default');
// 关闭 FishEye
if (fisheyeEnabled && fishEye) {
graph.removePlugin(fishEye);
graph.setMode('default');
// 设置 menuTip
setMenuTip({
text: t('按下 Esc 键退出鱼眼放大镜'),
display: 'none',
opacity: 0,
});
} else {
// 停止布局
stopLayout();
// 关闭 lasso 框选
if (lassoEnabled) clickLassoIcon(true);
// 关闭选择路径端点
if (enableSelectPathEnd) setEnableSelectPathEnd(false);
// 关闭搜索节点框
if (enableSearch) setEnableSearch(false);
// 设置 menuTip
setMenuTip({
text: t('按下 Esc 键退出鱼眼放大镜'),
display: 'block',
opacity: 1,
});
// 将交互模式切换到鱼眼只读模式,即不能缩放画布、框选节点、拉索选择节点等可能和鱼眼有冲突的操作
graph.setMode('fisheyeMode');
// 开启 FishEye
fishEye = new G6.Fisheye({
r: 249,
scaleRByWheel: true,
minR: 100,
maxR: 500,
// showLabel: true,
});
graph.addPlugin(fishEye);
}
clickFisheyeIcon();
};
// 开启 lasso select 功能
const enabledLassoSelect = () => {
if (!graph || graph.destroyed) return;
clickLassoIcon();
if (!lassoEnabled) {
graph.setMode('lassoSelect');
// 设置鼠标样式为十字形
graph.get('canvas').setCursor('crosshair');
// 关闭 fisheye
if (fisheyeEnabled && fishEye) {
graph.removePlugin(fishEye);
clickFisheyeIcon(true);
}
// 关闭选择路径端点
if (enableSelectPathEnd) setEnableSelectPathEnd(false);
// 关闭搜索节点框
if (enableSearch) setEnableSearch(false);
// 设置 menuTip
setMenuTip({
text: t('按下 Esc 键退出拉索选择模式'),
display: 'block',
opacity: 1,
});
} else {
graph.setMode('default');
// 设置鼠标样式为默认
graph.get('canvas').setCursor('default');
// 设置 menuTip
setMenuTip({
text: t('按下 Esc 键退出拉索选择模式'),
display: 'none',
opacity: 0,
});
}
};
// 开启选择两个节点显示最短路径
const handleEnableSelectPathEnd = () => {
setEnableSelectPathEnd((old) => {
if (!old) {
graph.setMode('default');
// 关闭 fisheye
if (fishEye) {
graph.removePlugin(fishEye);
clickFisheyeIcon(true);
}
// 关闭 lasso 框选
if (lassoEnabled) clickLassoIcon(true);
// 关闭搜索节点框
if (enableSearch) setEnableSearch(false);
// 设置 menuTip
setMenuTip({
text: t('按住 SHIFT 键并点选两个节点作为路径起终点'),
display: 'block',
opacity: 1,
});
return true;
}
// 设置 menuTip
setMenuTip({
text: '',
display: 'none',
opacity: 0,
});
return false;
});
};
const escListener = (e) => {
if (!graph || graph.destroyed) return;
if (e.key !== 'Escape') return;
if (fishEye) {
graph.removePlugin(fishEye);
clickFisheyeIcon(true);
}
// 关闭 lasso 框选
graph.setMode('default');
// 关闭搜索节点框
setEnableSearch(false);
// 关闭选择路径端点
setEnableSelectPathEnd(false);
// 设置鼠标样式为默认
graph.get('canvas').setCursor('default');
clickLassoIcon(true);
// 设置 menuTip
setMenuTip({
text: t('按下 Esc 键退出当前模式'),
display: 'none',
opacity: 0,
});
};
useEffect(() => {
if (typeof window !== 'undefined') {
window.addEventListener('keydown', escListener.bind(this));
return window.removeEventListener('keydown', escListener.bind(this));
}
}, []);
const iconStyle = {
disable: { color: 'rgba(255, 255, 255, 0.85)' },
enable: { color: 'rgba(82, 115, 224, 1)' },
};
return (
<>
<div id="canvas-menu">
<div className="icon-container">
<span
className="icon-span"
style={{ backgroundColor: 'rgba(0, 0, 0, 0)' }}
onClick={clickEdgeLabelController}
onMouseEnter={(e) =>
showItemTip(e, edgeLabelVisible ? t('隐藏边标签') : t('显示边标签'))
}
onMouseLeave={hideItemTip}
>
{edgeLabelVisible ? (
<DisconnectOutlined style={iconStyle.enable} />
) : (
<TagOutlined style={iconStyle.disable} />
)}
</span>
<span
className="icon-span"
onClick={toggleFishEye}
onMouseEnter={(e) =>
showItemTip(e, fisheyeEnabled ? t('关闭鱼眼放大镜') : t('打开鱼眼放大镜'))
}
onMouseLeave={hideItemTip}
>
{fisheyeEnabled ? (
<EyeInvisibleOutlined style={iconStyle.enable} />
) : (
<EyeOutlined style={iconStyle.disable} />
)}
</span>
<span
className="icon-span"
onClick={enabledLassoSelect}
onMouseEnter={(e) =>
showItemTip(e, lassoEnabled ? t('关闭拉索选择模式') : t('打开拉索选择模式'))
}
onMouseLeave={hideItemTip}
>
<HighlightOutlined style={lassoEnabled ? iconStyle.enable : iconStyle.disable} />
</span>
<span
className="icon-span"
onClick={handleEnableSelectPathEnd}
onMouseEnter={(e) => showItemTip(e, t('搜索最短路径'))}
onMouseLeave={hideItemTip}
>
<NodeIndexOutlined style={enableSelectPathEnd ? iconStyle.enable : iconStyle.disable} />
</span>
<span className="icon-span" style={{ width: 'fit-content', ...iconStyle.disable }}>
<span
className="zoom-icon"
onClick={handleZoomIn}
onMouseEnter={(e) => showItemTip(e, t('缩小'))}
onMouseLeave={hideItemTip}
>
-
</span>
<span
className="zoom-icon"
onClick={handleFitViw}
onMouseEnter={(e) => showItemTip(e, t('图内容适配容器,快捷键:ctrl + 1'))}
onMouseLeave={hideItemTip}
style={{ paddingLeft: '8px', paddingRight: '8px' }}
>
FIT
</span>
<span
className="zoom-icon"
onClick={handleZoomOut}
onMouseEnter={(e) => showItemTip(e, t('放大'))}
onMouseLeave={hideItemTip}
>
+
</span>
</span>
<span
className="icon-span"
onClick={handleEnableSearch}
onMouseEnter={(e) => showItemTip(e, t('输入 ID 搜索节点'))}
onMouseLeave={hideItemTip}
>
<SearchOutlined style={enableSearch ? iconStyle.enable : iconStyle.disable} />
</span>
{enableSearch && (
<span
onMouseEnter={(e) => showItemTip(e, t('输入需要搜索的节点 ID,并点击 Submit 按钮'))}
onMouseLeave={hideItemTip}
>
<input type="text" id="search-node-input" />
<button id="submit-button" onClick={handleSearchNode}>
Submit
</button>
</span>
)}
{enableSelectPathEnd && (
<span
onMouseEnter={(e) =>
showItemTip(e, t('选择有且仅有两个节点作为端点,并点击 Find Path 按钮'))
}
onMouseLeave={hideItemTip}
>
<button id="submit-button" onClick={handleFindPath}>
Find Path
</button>
</span>
)}
</div>
</div>
<div className="menu-tip" style={{ opacity: menuTip.opacity }}>
{menuTip.text}
</div>
<div id="g6-canavs-menu-item-tip" style={{ opacity: menuItemTip.opacity }}>
{menuItemTip.text}
</div>
</>
);
};
export default CanvasMenu; | the_stack |
import { } from 'jasmine';
import * as td from 'testdouble'
import { TestBed, inject, async, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { DragulaDirective } from '../components/dragula.directive';
import { DragulaService } from '../components/dragula.service';
import { DrakeWithModels } from '../DrakeWithModels';
import { Group } from '../Group';
import { DrakeFactory } from '../DrakeFactory';
import { EventTypes } from '../EventTypes';
import { MockDrake, MockDrakeFactory } from '../MockDrake';
import { Component, ElementRef } from "@angular/core";
import { TestHostComponent, TwoWay, Asynchronous } from './test-host.component';
import { Subject, BehaviorSubject, Observable, empty } from 'rxjs';
import { DragulaOptions } from '../DragulaOptions';
import { StaticService } from './StaticService';
const GROUP = "GROUP";
type SimpleDrake = Partial<DrakeWithModels>;
describe('DragulaDirective', () => {
let fixture: ComponentFixture<TestHostComponent>;
let component: TestHostComponent;
let service: StaticService;
beforeEach(() => {
service = new StaticService();
TestBed.configureTestingModule({
declarations: [ DragulaDirective, TestHostComponent, TwoWay, Asynchronous ],
providers: [
{ provide: DrakeFactory, useValue: MockDrakeFactory },
{ provide: DragulaService, useValue: service }
]
})
.compileComponents();
fixture = TestBed.createComponent(TestHostComponent);
component = fixture.componentInstance;
component.group = GROUP;
});
afterEach(() => {
fixture.destroy();
td.reset();
service.clear();
});
const mockMultipleDrakes = (...pairs: [Partial<DrakeWithModels>, string][]) => {
const find = td.function();
pairs.forEach(([drake, name]) => {
let group = new Group(name, drake as any as DrakeWithModels, {});
td.when(find(name)).thenReturn(group);
});
td.replace(service, 'find', find);
return find;
};
const mockDrake = (drake: Partial<DrakeWithModels>, name = GROUP) => {
return mockMultipleDrakes([drake, name]);
};
const simpleDrake = (containers: Element[] = [], models: any[][] = []) => {
return { containers, models } as SimpleDrake;
}
const expectFindsInSequence = (find: any, seq: any[]) => {
let captor = td.matchers.captor();
td.verify(find(captor.capture()));
let i = 0;
expect(captor.values.length).toBe(seq.length);
seq.forEach(val => expect(captor.values[i++]).toBe(val));
}
// ngOnInit AND checkModel
it('should initialize with new drake and call DragulaService.createGroup', () => {
component.group = GROUP;
component.model = [];
fixture.detectChanges();
let group = service.find(GROUP);
expect(group).toBeTruthy('group not created');
expect(group.drake.models).toBeTruthy('group.drake should have models');
});
// checkModel: no dragulaModel
it('should not setup with drake.models when dragulaModel == null', () => {
component.group = GROUP;
component.model = null;
fixture.detectChanges();
let group = service.find(GROUP);
expect(group.drake.models).toBeFalsy();
});
// ngOnInit
// checkModel: dragulaModel, drake, push to drake.models
it('should initialize and add to existing drake', () => {
let theirs = [ { someVar: 'theirs' } ];
let mine = [ { someVar: 'mine' } ];
let drake = simpleDrake([document.createElement('div')], [ theirs ]);
mockDrake(drake);
component.model = mine;
fixture.detectChanges();
expect(drake.containers.length).toBe(2);
expect(drake.models.length).toBe(2);
});
// ngOnChanges
// there is no way to mock direct array mutation of a drake's models
// it('should do nothing for no model changes', () => {
// });
// ngOnChanges
it('should update the model value on existing drake.models', () => {
let myModel = [ 'something' ];
let newModel = [ 'something new' ];
let drake = simpleDrake([document.createElement('div')], [myModel]);
mockDrake(drake);
component.model = myModel;
fixture.detectChanges();
component.model = newModel;
fixture.detectChanges();
expect(drake.models[0]).toEqual(newModel);
});
// ngOnChanges
it('should update the model value on an existing drake, with no models', () => {
let drake = simpleDrake();
mockDrake(drake);
let myModel = ["something"];
let newModel = ["something new"];
component.model = myModel;
fixture.detectChanges();
component.model = newModel;
fixture.detectChanges();
expect(drake.models[0]).toEqual(newModel);
});
// ngOnChanges
it('should add a container and a model on init, take 2', () => {
let theirModel = [ "someone else's model" ];
let myModel = [ "something" ];
// create an existing drake with models
let drake = simpleDrake([document.createElement('div')], [theirModel]);
mockDrake(drake);
component.model = myModel;
fixture.detectChanges();
expect(drake.containers.length).toBe(2);
expect(drake.containers).toContain(component.host.nativeElement);
expect(drake.models).toContain(myModel);
});
// ngOnChanges
it('should do nothing if there is no bag name', () => {
// if DragulaDirective is initialized, it tries to find the bag
let drake = simpleDrake();
let find = mockDrake(drake)
component.group = null;
component.model = [];
fixture.detectChanges();
expect().toVerify({ called: find(), times: 0, ignoreExtraArgs: true });
});
// ngOnChanges
it('should cleanly move to another drake when bag name changes', () => {
let CAT = "CAT", DOG = "DOG";
let catDrake = simpleDrake();
let dogDrake = simpleDrake();
let find = mockMultipleDrakes([catDrake, CAT], [dogDrake, DOG])
component.group = CAT;
component.model = [ { animal: 'generic four-legged creature' } ];
fixture.detectChanges();
component.group = DOG;
fixture.detectChanges();
// setup CAT, teardown CAT, setup DOG
expectFindsInSequence(find, [CAT, CAT, DOG])
// clean move to another drake
expect(catDrake.models.length).toBe(0);
expect(catDrake.containers.length).toBe(0);
expect(dogDrake.models.length).toBe(1);
expect(dogDrake.models).toContain(component.model);
expect(dogDrake.containers.length).toBe(1);
expect(dogDrake.containers).toContain(component.host.nativeElement);
});
// ngOnChanges
it('should clean up when un-setting bag name', () => {
let drake = simpleDrake();
let find = mockDrake(drake);
component.group = GROUP;
component.model = [];
fixture.detectChanges();
component.group = null;
fixture.detectChanges();
// setup, then teardown
expectFindsInSequence(find, [ GROUP, GROUP ]);
expect(drake.models.length).toBe(0);
expect(drake.containers.length).toBe(0);
});
const testUnsettingModel = (drake: SimpleDrake) => {
let find = mockDrake(drake);
const initialContainers = drake.containers.length;
const initialModels = drake.models.length;
let firstModel = [{ first: 'model' }];
let nextModel = [{ next: 'model' }];
component.group = GROUP;
component.model = firstModel;
fixture.detectChanges();
component.model = null;
fixture.detectChanges();
// setup, then teardown
expectFindsInSequence(find, [ GROUP ]);
expect(drake.models).not.toContain(firstModel, 'old model not removed');
expect(drake.containers).toContain(component.host.nativeElement, 'newly added container should still be there');
component.model = nextModel;
fixture.detectChanges();
expect(drake.models).not.toContain(firstModel, 'old model not removed');
expect(drake.models).toContain(nextModel, 'new model not inserted');
};
// ngOnChanges
it('should clean up when un-setting the model, with no other members', () => {
const drake = simpleDrake();
testUnsettingModel(drake);
});
// ngOnChanges
it('should clean up when un-setting the model, with other active models in the drake', () => {
const existingContainer = document.createElement('div');
const existingModel = [{ existing: 'model' }];
const drake = simpleDrake([existingContainer], [existingModel]);
testUnsettingModel(drake);
expect(drake.containers).toContain(existingContainer);
expect(drake.models).toContain(existingModel);
});
// set up fake event subscription so we can fire events manually
const mockServiceEvent = (eventName: EventTypes) => {
let fn = td.function();
let evts = new Subject();
td.when(fn(GROUP)).thenReturn(evts)
td.replace(service, 'dropModel', fn);
return evts;
};
it('should fire dragulaModelChange on dropModel', () => {
let dropModel = mockServiceEvent(EventTypes.DropModel);
// called via (dragulaModelChange)="modelChange($event)" in the test component
let modelChange = td.replace(component, 'modelChange');
let item = { a: 'dragged' };
let myModel = [{ a: 'static' }];
let theirModel = [item];
component.group = GROUP;
component.model = myModel;
fixture.detectChanges();
let source = document.createElement('ul');
let target = component.host.nativeElement;
let myNewModel = myModel.slice(0);
myNewModel.push(item);
let theirNewModel: any[] = [];
dropModel.next({
name: GROUP,
source,
target,
sourceModel: theirNewModel,
targetModel: myNewModel
});
expect().toVerify(modelChange(myNewModel));
});
it('should fire dragulaModelChange on removeModel', () => {
let removeModel = mockServiceEvent(EventTypes.RemoveModel);
// called via (dragulaModelChange)="modelChange($event)" in the test component
let modelChange = td.replace(component, 'modelChange');
let item = { a: 'to be removed' };
let myModel = [item];
component.group = GROUP;
component.model = myModel;
fixture.detectChanges();
let source = component.host.nativeElement;
let myNewModel: any[] = [];
removeModel.next({
name: GROUP,
item,
source,
sourceModel: myNewModel
});
expect().toVerify(modelChange(myNewModel));
});
const testModelChange = <T extends TestHostComponent | TwoWay | Asynchronous>(
componentClass: { new(...args: any[]): T},
saveToComponent = true,
) => {
let fixture = TestBed.createComponent(componentClass);
let component = fixture.componentInstance;
let removeModel = mockServiceEvent(EventTypes.RemoveModel);
let same = { a: 'same' };
let same2 = { same2: '2' };
let item = { a: 'to be removed' };
let myModel = [same, item, same2];
component.group = GROUP;
component.model = myModel;
fixture.detectChanges();
let bag = service.find(GROUP);
// if(componentClass === Asynchronous) console.log( bag.drake )
expect(bag).toBeTruthy('bag not truthy');
expect(bag.drake.models).toBeTruthy('bag.drake.models not truthy');
expect(bag.drake.models && bag.drake.models[0]).toBe(myModel);
let source = component.host.nativeElement;
let myNewModel: any[] = [same, same2];
bag.drake.models[0] = myNewModel; // simulate the drake.on(remove) handler
removeModel.next({
name: GROUP,
item,
source,
sourceModel: myNewModel
});
if (saveToComponent) {
expect(component.model).toBe(
myNewModel,
"[(dragulaModel)] didn't save model to component"
);
}
// now test whether the new array causes a teardown/setup cycle
let setup = td.replace(component.directive, 'setup');
let teardown = td.replace(component.directive, 'teardown');
// before change detection
expect(component.directive.dragulaModel).not.toBe(myNewModel, "directive didn't save the new model");
// now propagate dragulaModelChange to the directive
fixture.detectChanges();
// after change detection
if (saveToComponent) {
expect(component.model).toBe(myNewModel, "component didn't save model");
}
expect(component.directive.dragulaModel).toBe(myNewModel);
// the directive shouldn't trigger a teardown/re-up
expect().toVerify({ called: teardown(), times: 0, ignoreExtraArgs: true });
expect().toVerify({ called: setup(), times: 0, ignoreExtraArgs: true });
expect(bag.drake.models[0]).toBe(myNewModel);
};
describe('(dragulaModelChange)', () => {
it('should work with (event) binding', () => {
testModelChange(TestHostComponent);
});
it('should work with two-way binding', () => {
testModelChange(TwoWay);
});
it('should work with an async pipe', () => {
testModelChange(Asynchronous, false);
});
});
}); | the_stack |
import { Immutable } from '../format/format';
import {
decodeBech32,
encodeBech32,
isBech32CharacterSet,
regroupBits,
} from './bech32';
export enum CashAddressNetworkPrefix {
mainnet = 'bitcoincash',
testnet = 'bchtest',
regtest = 'bchreg',
}
export const cashAddressBitToSize = {
0: 160,
1: 192,
2: 224,
3: 256,
4: 320,
5: 384,
6: 448,
7: 512,
} as const;
export const cashAddressSizeToBit = {
160: 0,
192: 1,
224: 2,
256: 3,
320: 4,
384: 5,
448: 6,
512: 7,
} as const;
/**
* The CashAddress specification standardizes the format of the version byte:
* - Most significant bit: reserved, must be `0`
* - next 4 bits: Address Type
* - 3 least significant bits: Hash Size
*
* Only two Address Type values are currently standardized:
* - 0 (`0b0000`): P2PKH
* - 1 (`0b0001`): P2SH
*
* While both P2PKH and P2SH addresses always use 160 bit hashes, the
* CashAddress specification standardizes other sizes for future use (or use by
* other systems), see `CashAddressSizeBit`.
*
* With these constraints, only two version byte values are currently standard.
*/
export enum CashAddressVersionByte {
/**
* Pay to Public Key Hash (P2PKH): `0b00000000`
*
* - Most significant bit: `0` (reserved)
* - Address Type bits: `0000` (P2PKH)
* - Size bits: `000` (160 bits)
*/
P2PKH = 0b00000000,
/**
* Pay to Script Hash (P2SH): `0b00001000`
*
* - Most significant bit: `0` (reserved)
* - Address Type bits: `0001` (P2SH)
* - Size bits: `000` (160 bits)
*/
P2SH = 0b00001000,
}
/**
* The address types currently defined in the CashAddress specification. See
* also: `CashAddressVersionByte`.
*/
export enum CashAddressType {
/**
* Pay to Public Key Hash (P2PKH)
*/
P2PKH = 0,
/**
* Pay to Script Hash (P2SH)
*/
P2SH = 1,
}
const cashAddressTypeBitShift = 3;
export type CashAddressAvailableTypes =
// prettier-ignore
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15;
export type CashAddressAvailableSizesInBits = keyof typeof cashAddressSizeToBit;
export type CashAddressAvailableSizes = keyof typeof cashAddressBitToSize;
/**
* Encode a CashAddress version byte for the given address type and hash length.
* See `CashAddressVersionByte` for more information.
*
* The `type` parameter must be a number between `0` and `15`, and `bitLength`
* must be one of the standardized lengths. To use the contents of a variable,
* cast it to `CashAddressType` or `CashAddressSize` respectively, e.g.:
* ```ts
* const type = 3 as CashAddressType;
* const size = 160 as CashAddressSize;
* getCashAddressVersionByte(type, size);
* ```
* @param type - the address type of the hash being encoded
* @param bitLength - the bit length of the hash being encoded
*/
export const encodeCashAddressVersionByte = (
type: CashAddressAvailableTypes,
bitLength: CashAddressAvailableSizesInBits
// eslint-disable-next-line no-bitwise
) => (type << cashAddressTypeBitShift) | cashAddressSizeToBit[bitLength];
const cashAddressReservedBitMask = 0b10000000;
const cashAddressTypeBits = 0b1111;
const cashAddressSizeBits = 0b111;
const empty = 0;
export enum CashAddressVersionByteDecodingError {
reservedBitSet = 'Reserved bit is set.',
}
/**
* Decode a CashAddress version byte.
* @param version - the version byte to decode
*/
export const decodeCashAddressVersionByte = (version: number) =>
// eslint-disable-next-line no-negated-condition, no-bitwise
(version & cashAddressReservedBitMask) !== empty
? CashAddressVersionByteDecodingError.reservedBitSet
: {
bitLength:
cashAddressBitToSize[
// eslint-disable-next-line no-bitwise
(version & cashAddressSizeBits) as keyof typeof cashAddressBitToSize
],
// eslint-disable-next-line no-bitwise
type: (version >>> cashAddressTypeBitShift) & cashAddressTypeBits,
};
/**
* In ASCII, each pair of upper and lower case characters share the same 5 least
* significant bits.
*/
const asciiCaseInsensitiveBits = 0b11111;
/**
* Convert a string into an array of 5-bit numbers, representing the
* characters in a case-insensitive way.
* @param prefix - the prefix to mask
*/
export const maskCashAddressPrefix = (prefix: string) => {
const result = [];
// eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus
for (let i = 0; i < prefix.length; i++) {
// eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data
result.push(prefix.charCodeAt(i) & asciiCaseInsensitiveBits);
}
return result;
};
// prettier-ignore
const bech32GeneratorMostSignificantByte = [0x98, 0x79, 0xf3, 0xae, 0x1e]; // eslint-disable-line @typescript-eslint/no-magic-numbers
// prettier-ignore
const bech32GeneratorRemainingBytes = [0xf2bc8e61, 0xb76d99e2, 0x3e5fb3c4, 0x2eabe2a8, 0x4f43e470]; // eslint-disable-line @typescript-eslint/no-magic-numbers
/**
* Perform the CashAddress polynomial modulo operation, which is based on the
* Bech32 polynomial modulo operation, but the returned checksum is 40 bits,
* rather than 30.
*
* A.K.A. `PolyMod`
*
* @remarks
* Notes from Bitcoin ABC:
* This function will compute what 8 5-bit values to XOR into the last 8 input
* values, in order to make the checksum 0. These 8 values are packed together
* in a single 40-bit integer. The higher bits correspond to earlier values.
*
* The input is interpreted as a list of coefficients of a polynomial over F
* = GF(32), with an implicit 1 in front. If the input is [v0,v1,v2,v3,v4],
* that polynomial is v(x) = 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4.
* The implicit 1 guarantees that [v0,v1,v2,...] has a distinct checksum
* from [0,v0,v1,v2,...].
*
* The output is a 40-bit integer whose 5-bit groups are the coefficients of
* the remainder of v(x) mod g(x), where g(x) is the cashaddr generator, x^8
* + [19]*x^7 + [3]*x^6 + [25]*x^5 + [11]*x^4 + [25]*x^3 + [3]*x^2 + [19]*x
* + [1]. g(x) is chosen in such a way that the resulting code is a BCH
* code, guaranteeing detection of up to 4 errors within a window of 1025
* characters. Among the various possible BCH codes, one was selected to in
* fact guarantee detection of up to 5 errors within a window of 160
* characters and 6 errors within a window of 126 characters. In addition,
* the code guarantee the detection of a burst of up to 8 errors.
*
* Note that the coefficients are elements of GF(32), here represented as
* decimal numbers between []. In this finite field, addition is just XOR of
* the corresponding numbers. For example, [27] + [13] = [27 ^ 13] = [22].
* Multiplication is more complicated, and requires treating the bits of
* values themselves as coefficients of a polynomial over a smaller field,
* GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example,
* [5] * [26] = (a^2 + 1) * (a^4 + a^3 + a) = (a^4 + a^3 + a) * a^2 + (a^4 +
* a^3 + a) = a^6 + a^5 + a^4 + a = a^3 + 1 (mod a^5 + a^3 + 1) = [9].
*
* During the course of the loop below, `c` contains the bit-packed
* coefficients of the polynomial constructed from just the values of v that
* were processed so far, mod g(x). In the above example, `c` initially
* corresponds to 1 mod (x), and after processing 2 inputs of v, it
* corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the
* starting value for `c`.
*
* @privateRemarks
* Derived from the `bitcore-lib-cash` implementation, which does not require
* BigInt: https://github.com/bitpay/bitcore
*
* @param v - Array of 5-bit integers over which the checksum is to be computed
*/
export const cashAddressPolynomialModulo = (v: readonly number[]) => {
/* eslint-disable functional/no-let, functional/no-loop-statement, functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers */
let mostSignificantByte = 0;
let lowerBytes = 1;
let c = 0;
// eslint-disable-next-line @typescript-eslint/prefer-for-of, no-plusplus
for (let j = 0; j < v.length; j++) {
c = mostSignificantByte >>> 3;
mostSignificantByte &= 0x07;
mostSignificantByte <<= 5;
mostSignificantByte |= lowerBytes >>> 27;
lowerBytes &= 0x07ffffff;
lowerBytes <<= 5;
lowerBytes ^= v[j];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < bech32GeneratorMostSignificantByte.length; ++i) {
// eslint-disable-next-line functional/no-conditional-statement
if (c & (1 << i)) {
mostSignificantByte ^= bech32GeneratorMostSignificantByte[i];
lowerBytes ^= bech32GeneratorRemainingBytes[i];
}
}
}
lowerBytes ^= 1;
// eslint-disable-next-line functional/no-conditional-statement
if (lowerBytes < 0) {
lowerBytes ^= 1 << 31;
lowerBytes += (1 << 30) * 2;
}
return mostSignificantByte * (1 << 30) * 4 + lowerBytes;
/* eslint-enable functional/no-let, functional/no-loop-statement, functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers */
};
const base32WordLength = 5;
const base256WordLength = 8;
/**
* Convert the checksum returned by `cashAddressPolynomialModulo` to an array of
* 5-bit positive integers which can be Base32 encoded.
* @param checksum - a 40 bit checksum returned by `cashAddressPolynomialModulo`
*/
export const cashAddressChecksumToUint5Array = (checksum: number) => {
const result = [];
// eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus
for (let i = 0; i < base256WordLength; ++i) {
// eslint-disable-next-line functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers, functional/immutable-data
result.push(checksum & 31);
// eslint-disable-next-line functional/no-expression-statement, @typescript-eslint/no-magic-numbers, no-param-reassign
checksum /= 32;
}
// eslint-disable-next-line functional/immutable-data
return result.reverse();
};
const payloadSeparator = 0;
/**
* Encode a hash as a CashAddress-like string using the CashAddress format.
*
* To encode a standard CashAddress, use `encodeCashAddress`.
*
* @param prefix - a valid prefix indicating the network for which to encode the
* address – must be only lowercase letters
* @param version - a single byte indicating the version of this address
* @param hash - the hash to encode
*/
export const encodeCashAddressFormat = <
Prefix extends string = CashAddressNetworkPrefix,
Version extends number = CashAddressVersionByte
>(
prefix: Prefix,
version: Version,
hash: Immutable<Uint8Array>
) => {
const checksum40BitPlaceholder = [0, 0, 0, 0, 0, 0, 0, 0];
const payloadContents = regroupBits({
bin: Uint8Array.from([version, ...hash]),
resultWordLength: base32WordLength,
sourceWordLength: base256WordLength,
}) as number[];
const checksumContents = [
...maskCashAddressPrefix(prefix),
payloadSeparator,
...payloadContents,
...checksum40BitPlaceholder,
];
const checksum = cashAddressPolynomialModulo(checksumContents);
const payload = [
...payloadContents,
...cashAddressChecksumToUint5Array(checksum),
];
return `${prefix}:${encodeBech32(payload)}`;
};
export enum CashAddressEncodingError {
unsupportedHashLength = 'CashAddress encoding error: a hash of this length can not be encoded as a valid CashAddress.',
}
const isValidBitLength = (
bitLength: number
): bitLength is CashAddressAvailableSizesInBits =>
(cashAddressSizeToBit[bitLength as CashAddressAvailableSizesInBits] as
| CashAddressAvailableSizes
| undefined) !== undefined;
/**
* Encode a hash as a CashAddress.
*
* Note, this method does not enforce error handling via the type system. The
* returned string may be a `CashAddressEncodingError.unsupportedHashLength`
* if `hash` is not a valid length. Check the result if the input is potentially
* malformed.
*
* For other address standards which closely follow the CashAddress
* specification (but have alternative version byte requirements), use
* `encodeCashAddressFormat`.
*
* @param prefix - a valid prefix indicating the network for which to encode the
* address (usually a `CashAddressNetworkPrefix`) – must be only lowercase
* letters
* @param type - the `CashAddressType` to encode in the version byte – usually a
* `CashAddressType`
* @param hash - the hash to encode (for P2PKH, the public key hash; for P2SH,
* the redeeming bytecode hash)
*/
export const encodeCashAddress = <
Prefix extends string = CashAddressNetworkPrefix,
Type extends CashAddressAvailableTypes = CashAddressType
>(
prefix: Prefix,
type: Type,
hash: Uint8Array
) => {
const bitLength = hash.length * base256WordLength;
if (!isValidBitLength(bitLength)) {
return CashAddressEncodingError.unsupportedHashLength;
}
return encodeCashAddressFormat(
prefix,
encodeCashAddressVersionByte(type, bitLength),
hash
);
};
export enum CashAddressDecodingError {
improperPadding = 'CashAddress decoding error: the payload is improperly padded.',
invalidCharacters = 'CashAddress decoding error: the payload contains non-bech32 characters.',
invalidChecksum = 'CashAddress decoding error: invalid checksum – please review the address for errors.',
invalidFormat = 'CashAddress decoding error: CashAddresses should be of the form "prefix:payload".',
mismatchedHashLength = 'CashAddress decoding error: mismatched hash length for specified address version.',
reservedByte = 'CashAddress decoding error: unknown CashAddress version, reserved byte set.',
}
/**
* Decode and validate a string using the CashAddress format. This is more
* lenient than `decodeCashAddress`, which also validates the contents of the
* version byte.
*
* Note, this method requires `address` to include a network prefix. To
* decode a string with an unknown prefix, try
* `decodeCashAddressFormatWithoutPrefix`.
*
* @param address - the CashAddress-like string to decode
*/
// eslint-disable-next-line complexity
export const decodeCashAddressFormat = (address: string) => {
const parts = address.toLowerCase().split(':');
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
if (parts.length !== 2 || parts[0] === '' || parts[1] === '') {
return CashAddressDecodingError.invalidFormat;
}
const [prefix, payload] = parts;
if (!isBech32CharacterSet(payload)) {
return CashAddressDecodingError.invalidCharacters;
}
const decodedPayload = decodeBech32(payload);
const polynomial = [
...maskCashAddressPrefix(prefix),
payloadSeparator,
...decodedPayload,
];
if (cashAddressPolynomialModulo(polynomial) !== 0) {
return CashAddressDecodingError.invalidChecksum;
}
const checksum40BitPlaceholderLength = 8;
const payloadContents = regroupBits({
allowPadding: false,
bin: decodedPayload.slice(0, -checksum40BitPlaceholderLength),
resultWordLength: base256WordLength,
sourceWordLength: base32WordLength,
});
if (typeof payloadContents === 'string') {
return CashAddressDecodingError.improperPadding;
}
const [version, ...hashContents] = payloadContents;
const hash = Uint8Array.from(hashContents);
return { hash, prefix, version };
};
/**
* Decode and validate a CashAddress, strictly checking the version byte
* according to the CashAddress specification. This is important for error
* detection in CashAddresses.
*
* For other address-like standards which closely follow the CashAddress
* specification (but have alternative version byte requirements), use
* `decodeCashAddressFormat`.
*
* Note, this method requires that CashAddresses include a network prefix. To
* decode an address with an unknown prefix, try
* `decodeCashAddressFormatWithoutPrefix`.
*
* @param address - the CashAddress to decode
*/
export const decodeCashAddress = (address: string) => {
const decoded = decodeCashAddressFormat(address);
if (typeof decoded === 'string') {
return decoded;
}
const info = decodeCashAddressVersionByte(decoded.version);
if (info === CashAddressVersionByteDecodingError.reservedBitSet) {
return CashAddressDecodingError.reservedByte;
}
if (decoded.hash.length * base256WordLength !== info.bitLength) {
return CashAddressDecodingError.mismatchedHashLength;
}
return {
hash: decoded.hash,
prefix: decoded.prefix,
type: info.type,
};
};
/**
* Attempt to decode and validate a CashAddress against a list of possible
* prefixes. If the correct prefix is known, use `decodeCashAddress`.
*
* @param address - the CashAddress to decode
* @param possiblePrefixes - the network prefixes to try
*/
// decodeCashAddressWithoutPrefix
export const decodeCashAddressFormatWithoutPrefix = (
address: string,
possiblePrefixes: readonly string[] = [
CashAddressNetworkPrefix.mainnet,
CashAddressNetworkPrefix.testnet,
CashAddressNetworkPrefix.regtest,
]
) => {
// eslint-disable-next-line functional/no-loop-statement
for (const prefix of possiblePrefixes) {
const attempt = decodeCashAddressFormat(`${prefix}:${address}`);
if (attempt !== CashAddressDecodingError.invalidChecksum) {
return attempt;
}
}
return CashAddressDecodingError.invalidChecksum;
};
const asciiLowerCaseStart = 96;
/**
* Convert a CashAddress polynomial to CashAddress string format.
*
* @remarks
* CashAddress polynomials take the form:
*
* `[lowest 5 bits of each prefix character] 0 [payload + checksum]`
*
* This method remaps the 5-bit integers in the prefix location to the matching
* ASCII lowercase characters, replaces the separator with `:`, and then Bech32
* encodes the remaining payload and checksum.
*
* @param polynomial - an array of 5-bit integers representing the terms of a
* CashAddress polynomial
*/
export const cashAddressPolynomialToCashAddress = (
polynomial: readonly number[]
) => {
const separatorPosition = polynomial.indexOf(0);
const prefix = polynomial
.slice(0, separatorPosition)
.map((integer) => String.fromCharCode(asciiLowerCaseStart + integer))
.join('');
const contents = encodeBech32(polynomial.slice(separatorPosition + 1));
return `${prefix}:${contents}`;
};
export enum CashAddressCorrectionError {
tooManyErrors = 'This address has more than 2 errors and cannot be corrected.',
}
const finiteFieldOrder = 32;
/**
* Attempt to correct up to 2 errors in a CashAddress. The CashAddress must be
* properly formed (include a prefix and only contain Bech32 characters).
*
* ## **Improper use of this method carries the risk of lost funds.**
*
* It is strongly advised that this method only be used under explicit user
* control. With enough errors, this method is likely to find a plausible
* correction for any address (but for which no private key exists). This is
* effectively equivalent to burning the funds.
*
* Only 2 substitution errors can be corrected (or a single swap) – deletions
* and insertions (errors which shift many other characters and change the
* length of the payload) can never be safely corrected and will produce an
* error.
*
* Errors can be corrected in both the prefix and the payload, but attempting to
* correct errors in the prefix prior to this method can improve results, e.g.
* for `bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x`, the string
* `bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc` can be corrected, while
* `typo:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc` can not.
*
* @privateRemarks
* Derived from: https://github.com/deadalnix/cashaddressed
*
* @param address - the CashAddress on which to attempt error correction
*/
// eslint-disable-next-line complexity
export const attemptCashAddressFormatErrorCorrection = (address: string) => {
const parts = address.toLowerCase().split(':');
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
if (parts.length !== 2 || parts[0] === '' || parts[1] === '') {
return CashAddressDecodingError.invalidFormat;
}
const [prefix, payload] = parts;
if (!isBech32CharacterSet(payload)) {
return CashAddressDecodingError.invalidCharacters;
}
const decodedPayload = decodeBech32(payload);
const polynomial = [...maskCashAddressPrefix(prefix), 0, ...decodedPayload];
const originalChecksum = cashAddressPolynomialModulo(polynomial);
if (originalChecksum === 0) {
return {
address: cashAddressPolynomialToCashAddress(polynomial),
corrections: [],
};
}
const syndromes: { [index: string]: number } = {};
// eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus
for (let term = 0; term < polynomial.length; term++) {
// eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus
for (let errorVector = 1; errorVector < finiteFieldOrder; errorVector++) {
// eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data
polynomial[term] ^= errorVector;
const correct = cashAddressPolynomialModulo(polynomial);
if (correct === 0) {
return {
address: cashAddressPolynomialToCashAddress(polynomial),
corrections: [term],
};
}
// eslint-disable-next-line no-bitwise
const s0 = (BigInt(correct) ^ BigInt(originalChecksum)).toString();
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
syndromes[s0] = term * finiteFieldOrder + errorVector;
// eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data
polynomial[term] ^= errorVector;
}
}
// eslint-disable-next-line functional/no-loop-statement
for (const [s0, pe] of Object.entries(syndromes)) {
// eslint-disable-next-line no-bitwise
const s1Location = (BigInt(s0) ^ BigInt(originalChecksum)).toString();
const s1 = syndromes[s1Location] as number | undefined;
if (s1 !== undefined) {
const correctionIndex1 = Math.trunc(pe / finiteFieldOrder);
const correctionIndex2 = Math.trunc(s1 / finiteFieldOrder);
// eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data
polynomial[correctionIndex1] ^= pe % finiteFieldOrder;
// eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data
polynomial[correctionIndex2] ^= s1 % finiteFieldOrder;
return {
address: cashAddressPolynomialToCashAddress(polynomial),
corrections: [correctionIndex1, correctionIndex2].sort((a, b) => a - b),
};
}
}
return CashAddressCorrectionError.tooManyErrors;
}; | the_stack |
import * as Redis from 'ioredis';
import { Module, RedisModuleOptions } from '../module.base';
import { RejsonCommander } from './rejson.commander';
import { ReJSONGetParameters } from './rejson.types';
export class ReJSON extends Module {
private rejsonCommander = new RejsonCommander();
/**
* Initializing the module object
* @param name The name of the module
* @param clusterNodes The nodes of the cluster
* @param moduleOptions The additional module options
* @param moduleOptions.isHandleError If to throw error on error
* @param moduleOptions.showDebugLogs If to print debug logs
* @param clusterOptions The options of the clusters
*/
constructor(clusterNodes: Redis.ClusterNode[], moduleOptions?: RedisModuleOptions, clusterOptions?: Redis.ClusterOptions)
/**
* Initializing the module object
* @param name The name of the module
* @param redisOptions The options of the redis database
* @param moduleOptions The additional module options
* @param moduleOptions.isHandleError If to throw error on error
* @param moduleOptions.showDebugLogs If to print debug logs
*/
constructor(redisOptions: Redis.RedisOptions, moduleOptions?: RedisModuleOptions)
constructor(options: Redis.RedisOptions & Redis.ClusterNode[], moduleOptions?: RedisModuleOptions, clusterOptions?: Redis.ClusterOptions) {
super(ReJSON.name, options, moduleOptions, clusterOptions)
}
/**
* Deleting a JSON key
* @param key The name of the key
* @param path The path of the key defaults to root if not provided. Non-existing keys and paths are ignored. Deleting an object's root is equivalent to deleting the key from Redis.
* @returns The number of paths deleted (0 or 1).
*/
async del(key: string, path?: string): Promise<number> {
const command = this.rejsonCommander.del(key, path);
return await this.sendCommand(command);
}
/**
* Clearing a JSON key
* @param key The name of the key
* @param path The path of the key defaults to root if not provided. Non-existing keys and paths are ignored. Deleting an object's root is equivalent to deleting the key from Redis.
* @returns The number of paths deleted (0 or 1).
*/
async clear(key: string, path?: string): Promise<number> {
const command = this.rejsonCommander.clear(key, path);
return await this.sendCommand(command);
}
/**
* Toggling a JSON key
* @param key The name of the key
* @param path The path of the key defaults to root if not provided. Non-existing keys and paths are ignored. Deleting an object's root is equivalent to deleting the key from Redis.
* @returns The value of the path after the toggle.
*/
async toggle(key: string, path?: string): Promise<boolean> {
const command = this.rejsonCommander.toggle(key, path);
return await this.sendCommand(command);
}
/**
* Setting a new JSON key
* @param key The name of the key
* @param path The path of the key
* @param json The JSON string of the key i.e. '{"x": 4}'
* @param condition Optional. The condition to set the JSON in.
* @returns Simple String OK if executed correctly, or Null Bulk if the specified NX or XX conditions were not met.
*/
async set(key: string, path: string, json: string, condition?: 'NX' | 'XX'): Promise<"OK"> {
const command = this.rejsonCommander.set(key, path, json, condition);
return await this.sendCommand(command);
}
/**
* Retrieving a JSON key
* @param key The name of the key
* @param path The path of the key
* @param parameters Additional parameters to arrange the returned values
* @returns The value at path in JSON serialized form.
*/
async get(key: string, path?: string, parameters?: ReJSONGetParameters): Promise<string>{
const command = this.rejsonCommander.get(key, path, parameters);
return await this.sendCommand(command);
}
/**
* Retrieving values from multiple keys
* @param keys A list of keys
* @param path The path of the keys
* @returns The values at path from multiple key's. Non-existing keys and non-existing paths are reported as null.
*/
async mget(keys: string[], path?: string): Promise<string[]> {
const command = this.rejsonCommander.mget(keys, path);
return await this.sendCommand(command);
}
/**
* Retrieving the type of a JSON key
* @param key The name of the key
* @param path The path of the key
* @returns Simple String, specifically the type of value.
*/
async type(key: string, path?: string): Promise<string> {
const command = this.rejsonCommander.type(key, path);
return await this.sendCommand(command);
}
/**
* Increasing JSON key value by number
* @param key The name of the key
* @param number The number to increase by
* @param path The path of the key
* @returns Bulk String, specifically the stringified new value.
*/
async numincrby(key: string, number: number, path?: string): Promise<string> {
const command = this.rejsonCommander.numincrby(key, number, path);
return await this.sendCommand(command);
}
/**
* Multiplying JSON key value by number
* @param key The name of the key
* @param number The number to multiply by
* @param path The path of the key
* @returns Bulk String, specifically the stringified new value.
*/
async nummultby(key: string, number: number, path?: string): Promise<string> {
const command = this.rejsonCommander.nummultby(key, number, path);
return await this.sendCommand(command);
}
/**
* Appending string to JSON key string value
* @param key The name of the key
* @param string The string to append to key value
* @param path The path of the key
* @returns Integer, specifically the string's new length.
*/
async strappend(key: string, string: string, path?: string): Promise<string> {
const command = this.rejsonCommander.strappend(key, string, path);
return await this.sendCommand(command);
}
/**
* Retrieving the length of a JSON key value
* @param key The name of the key
* @param path The path of the key
* @returns Integer, specifically the string's length.
*/
async strlen(key: string, path?: string): Promise<number | null> {
const command = this.rejsonCommander.strlen(key, path);
return await this.sendCommand(command);
}
/**
* Appending string to JSON key array value
* @param key The name of the key
* @param items The items to append to an existing JSON array
* @param path The path of the key
* @returns Integer, specifically the array's new size.
*/
async arrappend(key: string, items: string[], path?: string): Promise<number> {
const command = this.rejsonCommander.arrappend(key, items, path);
return await this.sendCommand(command);
}
/**
* Retrieving JSON key array item by index
* @param key The name of the key
* @param scalar The scalar to filter out a JSON key
* @param path The path of the key
* @returns Integer, specifically the position of the scalar value in the array, or -1 if unfound.
*/
async arrindex(key: string, scalar: string, path?: string): Promise<number> {
const command = this.rejsonCommander.arrindex(key, scalar, path);
return await this.sendCommand(command);
}
/**
* Inserting item into JSON key array
* @param key The name of the key
* @param index The index to insert the JSON into the array
* @param json The JSON string to insert into the array
* @param path The path of the key
* @returns Integer, specifically the array's new size.
*/
async arrinsert(key: string, index: number, json: string, path?: string): Promise<number> {
const command = this.rejsonCommander.arrinsert(key, index, json, path);
return await this.sendCommand(command);
}
/**
* Retrieving the length of a JSON key array
* @param key The name of the key
* @param path The path of the key
* @returns Integer, specifically the array's length.
*/
async arrlen(key: string, path?: string): Promise<number> {
const command = this.rejsonCommander.arrlen(key, path);
return await this.sendCommand(command);
}
/**
* Poping an array item by index
* @param key The name of the key
* @param index The index of the array item to pop
* @param path The path of the key
* @returns Bulk String, specifically the popped JSON value.
*/
async arrpop(key: string, index: number, path?: string): Promise<string> {
const command = this.rejsonCommander.arrpop(key, index, path);
return await this.sendCommand(command);
}
/**
* Triming an array by index range
* @param key The name of the key
* @param start The starting index of the trim
* @param end The ending index of the trim
* @param path The path of the key
* @returns Integer, specifically the array's new size.
*/
async arrtrim(key: string, start: number, end: number, path?: string): Promise<string> {
const command = this.rejsonCommander.arrtrim(key, start, end, path);
return await this.sendCommand(command);
}
/**
* Retrieving an array of JSON keys
* @param key The name of the key
* @param path The path of the key
* @returns Array, specifically the key names in the object as Bulk Strings.
*/
async objkeys(key: string, path?: string): Promise<string[]> {
const command = this.rejsonCommander.objkeys(key, path);
return await this.sendCommand(command);
}
/**
* Retrieving the length of a JSON
* @param key The name of the key
* @param path The path of the key
* @returns Integer, specifically the number of keys in the object.
*/
async objlen(key: string, path?: string): Promise<number> {
const command = this.rejsonCommander.objlen(key, path);
return await this.sendCommand(command);
}
/**
* Executing debug command
* @param subcommand The subcommand of the debug command
* @param key The name of the key
* @param path The path of the key
* @returns
MEMORY returns an integer, specifically the size in bytes of the value
HELP returns an array, specifically with the help message
*/
async debug(subcommand: 'MEMORY' | 'HELP', key?: string, path?: string): Promise<string[] | number> {
const command = this.rejsonCommander.debug(subcommand, key, path);
return await this.sendCommand(command);
}
/**
* An alias of delCommand
* @param key The name of the key
* @param path The path of the key
* @returns The number of paths deleted (0 or 1).
*/
async forget(key: string, path?: string): Promise<number> {
const command = this.rejsonCommander.forget(key, path);
return await this.sendCommand(command);
}
/**
* Retrieving a JSON key value in RESP protocol
* @param key The name of the key
* @param path The path of the key
* @returns Array, specifically the JSON's RESP form as detailed.
*/
async resp(key: string, path?: string): Promise<string[]> {
const command = this.rejsonCommander.resp(key, path);
return await this.sendCommand(command);
}
} | the_stack |
let cache;
export const MD5 = function(data) {
//use cache first
if(cache) {
const cache_ret = cache.get(data);
if(cache_ret) {
return cache_ret;
}
}
// convert number to (unsigned) 32 bit hex, zero filled string
function to_zerofilled_hex(n) {
var t1 = (n >>> 0).toString(16);
return "00000000".substr(0, 8 - t1.length) + t1;
}
// convert array of chars to array of bytes
function chars_to_bytes(ac) {
var retval = [];
for (var i = 0; i < ac.length; i++) {
retval = retval.concat(str_to_bytes(ac[i]));
}
return retval;
}
// convert a 64 bit unsigned number to array of bytes. Little endian
function int64_to_bytes(num) {
var retval = [];
for (var i = 0; i < 8; i++) {
retval.push(num & 0xFF);
num = num >>> 8;
}
return retval;
}
// 32 bit left-rotation
function rol(num, places) {
return ((num << places) & 0xFFFFFFFF) | (num >>> (32 - places));
}
// The 4 MD5 functions
function fF(b, c, d) {
return (b & c) | (~b & d);
}
function fG(b, c, d) {
return (d & b) | (~d & c);
}
function fH(b, c, d) {
return b ^ c ^ d;
}
function fI(b, c, d) {
return c ^ (b | ~d);
}
// pick 4 bytes at specified offset. Little-endian is assumed
function bytes_to_int32(arr, off) {
return (arr[off + 3] << 24) | (arr[off + 2] << 16) | (arr[off + 1] << 8) | (arr[off]);
}
/*
Conver string to array of bytes in UTF-8 encoding
See:
http://www.dangrossman.info/2007/05/25/handling-utf-8-in-javascript-php-and-non-utf8-databases/
http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string
How about a String.getBytes(<ENCODING>) for Javascript!? Isn't it time to add it?
*/
function str_to_bytes(str) {
var retval = [ ];
for (var i = 0; i < str.length; i++)
if (str.charCodeAt(i) <= 0x7F) {
retval.push(str.charCodeAt(i));
} else {
var tmp = encodeURIComponent(str.charAt(i)).substr(1).split('%')
for (var j = 0; j < tmp.length; j++) {
retval.push(parseInt(tmp[j], 0x10));
}
}
return retval;
}
// convert the 4 32-bit buffers to a 128 bit hex string. (Little-endian is assumed)
function int128le_to_hex(a, b, c, d) {
var ra = "";
var t = 0;
var ta = 0;
for (var i = 3; i >= 0; i--) {
ta = arguments[i];
t = (ta & 0xFF);
ta = ta >>> 8;
t = t << 8;
t = t | (ta & 0xFF);
ta = ta >>> 8;
t = t << 8;
t = t | (ta & 0xFF);
ta = ta >>> 8;
t = t << 8;
t = t | ta;
ra = ra + to_zerofilled_hex(t);
}
return ra;
}
// conversion from typed byte array to plain javascript array
function typed_to_plain(tarr) {
var retval = new Array(tarr.length);
for (var i = 0; i < tarr.length; i++) {
retval[i] = tarr[i];
}
return retval;
}
// check input data type and perform conversions if needed
var databytes = null;
function cloneArray(inpArr) {
return inpArr.slice();
}
// String
var type_mismatch = null;
if (typeof data == 'string') {
// convert string to array bytes
databytes = str_to_bytes(data);
} else if (data.constructor == Array) {
if (data.length === 0) {
// if it's empty, just assume array of bytes
databytes = cloneArray(data);
} else if (typeof data[0] == 'string') {
databytes = chars_to_bytes(data);
} else if (typeof data[0] == 'number') {
databytes = cloneArray(data);
} else {
type_mismatch = typeof data[0];
}
} else if (typeof ArrayBuffer != 'undefined') {
if (data instanceof ArrayBuffer) {
databytes = typed_to_plain(new Uint8Array(data));
} else if ((data instanceof Uint8Array) || (data instanceof Int8Array)) {
databytes = typed_to_plain(data);
} else if ((data instanceof Uint32Array) || (data instanceof Int32Array) ||
(data instanceof Uint16Array) || (data instanceof Int16Array) ||
(data instanceof Float32Array) || (data instanceof Float64Array)
) {
databytes = typed_to_plain(new Uint8Array(data.buffer));
} else {
type_mismatch = typeof data;
}
} else {
type_mismatch = typeof data;
}
if (type_mismatch) {
alert('MD5 type mismatch, cannot process ' + type_mismatch);
}
function _add(n1, n2) {
return 0x0FFFFFFFF & (n1 + n2);
}
const ret = do_digest();
cache = cache || new Map();
cache.set(data, ret);
return ret;
function do_digest() {
// function update partial state for each run
function updateRun(nf, sin32, dw32, b32) {
var temp = d;
d = c;
c = b;
//b = b + rol(a + (nf + (sin32 + dw32)), b32)
b = _add(b,
rol(
_add(a,
_add(nf, _add(sin32, dw32))
), b32
)
);
a = temp;
}
// save original length
var org_len = databytes.length;
// first append the "1" + 7x "0"
databytes.push(0x80);
// determine required amount of padding
var tail = databytes.length % 64
// no room for msg length?
if (tail > 56) {
// pad to next 512 bit block
for (var i = 0; i < (64 - tail); i++) {
databytes.push(0x0);
}
tail = databytes.length % 64;
}
for (i = 0; i < (56 - tail); i++) {
databytes.push(0x0);
}
// message length in bits mod 512 should now be 448
// append 64 bit, little-endian original msg length (in *bits*!)
databytes = databytes.concat(int64_to_bytes(org_len * 8));
// initialize 4x32 bit state
var h0 = 0x67452301;
var h1 = 0xEFCDAB89;
var h2 = 0x98BADCFE;
var h3 = 0x10325476;
// temp buffers
var a = 0, b = 0, c = 0, d = 0;
// Digest message
for (i = 0; i < databytes.length / 64; i++) {
// initialize run
a = h0;
b = h1;
c = h2;
d = h3;
var ptr = i * 64;
// do 64 runs
updateRun(fF(b, c, d), 0xd76aa478, bytes_to_int32(databytes, ptr), 7);
updateRun(fF(b, c, d), 0xe8c7b756, bytes_to_int32(databytes, ptr + 4), 12);
updateRun(fF(b, c, d), 0x242070db, bytes_to_int32(databytes, ptr + 8), 17);
updateRun(fF(b, c, d), 0xc1bdceee, bytes_to_int32(databytes, ptr + 12), 22);
updateRun(fF(b, c, d), 0xf57c0faf, bytes_to_int32(databytes, ptr + 16), 7);
updateRun(fF(b, c, d), 0x4787c62a, bytes_to_int32(databytes, ptr + 20), 12);
updateRun(fF(b, c, d), 0xa8304613, bytes_to_int32(databytes, ptr + 24), 17);
updateRun(fF(b, c, d), 0xfd469501, bytes_to_int32(databytes, ptr + 28), 22);
updateRun(fF(b, c, d), 0x698098d8, bytes_to_int32(databytes, ptr + 32), 7);
updateRun(fF(b, c, d), 0x8b44f7af, bytes_to_int32(databytes, ptr + 36), 12);
updateRun(fF(b, c, d), 0xffff5bb1, bytes_to_int32(databytes, ptr + 40), 17);
updateRun(fF(b, c, d), 0x895cd7be, bytes_to_int32(databytes, ptr + 44), 22);
updateRun(fF(b, c, d), 0x6b901122, bytes_to_int32(databytes, ptr + 48), 7);
updateRun(fF(b, c, d), 0xfd987193, bytes_to_int32(databytes, ptr + 52), 12);
updateRun(fF(b, c, d), 0xa679438e, bytes_to_int32(databytes, ptr + 56), 17);
updateRun(fF(b, c, d), 0x49b40821, bytes_to_int32(databytes, ptr + 60), 22);
updateRun(fG(b, c, d), 0xf61e2562, bytes_to_int32(databytes, ptr + 4), 5);
updateRun(fG(b, c, d), 0xc040b340, bytes_to_int32(databytes, ptr + 24), 9);
updateRun(fG(b, c, d), 0x265e5a51, bytes_to_int32(databytes, ptr + 44), 14);
updateRun(fG(b, c, d), 0xe9b6c7aa, bytes_to_int32(databytes, ptr), 20);
updateRun(fG(b, c, d), 0xd62f105d, bytes_to_int32(databytes, ptr + 20), 5);
updateRun(fG(b, c, d), 0x2441453, bytes_to_int32(databytes, ptr + 40), 9);
updateRun(fG(b, c, d), 0xd8a1e681, bytes_to_int32(databytes, ptr + 60), 14);
updateRun(fG(b, c, d), 0xe7d3fbc8, bytes_to_int32(databytes, ptr + 16), 20);
updateRun(fG(b, c, d), 0x21e1cde6, bytes_to_int32(databytes, ptr + 36), 5);
updateRun(fG(b, c, d), 0xc33707d6, bytes_to_int32(databytes, ptr + 56), 9);
updateRun(fG(b, c, d), 0xf4d50d87, bytes_to_int32(databytes, ptr + 12), 14);
updateRun(fG(b, c, d), 0x455a14ed, bytes_to_int32(databytes, ptr + 32), 20);
updateRun(fG(b, c, d), 0xa9e3e905, bytes_to_int32(databytes, ptr + 52), 5);
updateRun(fG(b, c, d), 0xfcefa3f8, bytes_to_int32(databytes, ptr + 8), 9);
updateRun(fG(b, c, d), 0x676f02d9, bytes_to_int32(databytes, ptr + 28), 14);
updateRun(fG(b, c, d), 0x8d2a4c8a, bytes_to_int32(databytes, ptr + 48), 20);
updateRun(fH(b, c, d), 0xfffa3942, bytes_to_int32(databytes, ptr + 20), 4);
updateRun(fH(b, c, d), 0x8771f681, bytes_to_int32(databytes, ptr + 32), 11);
updateRun(fH(b, c, d), 0x6d9d6122, bytes_to_int32(databytes, ptr + 44), 16);
updateRun(fH(b, c, d), 0xfde5380c, bytes_to_int32(databytes, ptr + 56), 23);
updateRun(fH(b, c, d), 0xa4beea44, bytes_to_int32(databytes, ptr + 4), 4);
updateRun(fH(b, c, d), 0x4bdecfa9, bytes_to_int32(databytes, ptr + 16), 11);
updateRun(fH(b, c, d), 0xf6bb4b60, bytes_to_int32(databytes, ptr + 28), 16);
updateRun(fH(b, c, d), 0xbebfbc70, bytes_to_int32(databytes, ptr + 40), 23);
updateRun(fH(b, c, d), 0x289b7ec6, bytes_to_int32(databytes, ptr + 52), 4);
updateRun(fH(b, c, d), 0xeaa127fa, bytes_to_int32(databytes, ptr), 11);
updateRun(fH(b, c, d), 0xd4ef3085, bytes_to_int32(databytes, ptr + 12), 16);
updateRun(fH(b, c, d), 0x4881d05, bytes_to_int32(databytes, ptr + 24), 23);
updateRun(fH(b, c, d), 0xd9d4d039, bytes_to_int32(databytes, ptr + 36), 4);
updateRun(fH(b, c, d), 0xe6db99e5, bytes_to_int32(databytes, ptr + 48), 11);
updateRun(fH(b, c, d), 0x1fa27cf8, bytes_to_int32(databytes, ptr + 60), 16);
updateRun(fH(b, c, d), 0xc4ac5665, bytes_to_int32(databytes, ptr + 8), 23);
updateRun(fI(b, c, d), 0xf4292244, bytes_to_int32(databytes, ptr), 6);
updateRun(fI(b, c, d), 0x432aff97, bytes_to_int32(databytes, ptr + 28), 10);
updateRun(fI(b, c, d), 0xab9423a7, bytes_to_int32(databytes, ptr + 56), 15);
updateRun(fI(b, c, d), 0xfc93a039, bytes_to_int32(databytes, ptr + 20), 21);
updateRun(fI(b, c, d), 0x655b59c3, bytes_to_int32(databytes, ptr + 48), 6);
updateRun(fI(b, c, d), 0x8f0ccc92, bytes_to_int32(databytes, ptr + 12), 10);
updateRun(fI(b, c, d), 0xffeff47d, bytes_to_int32(databytes, ptr + 40), 15);
updateRun(fI(b, c, d), 0x85845dd1, bytes_to_int32(databytes, ptr + 4), 21);
updateRun(fI(b, c, d), 0x6fa87e4f, bytes_to_int32(databytes, ptr + 32), 6);
updateRun(fI(b, c, d), 0xfe2ce6e0, bytes_to_int32(databytes, ptr + 60), 10);
updateRun(fI(b, c, d), 0xa3014314, bytes_to_int32(databytes, ptr + 24), 15);
updateRun(fI(b, c, d), 0x4e0811a1, bytes_to_int32(databytes, ptr + 52), 21);
updateRun(fI(b, c, d), 0xf7537e82, bytes_to_int32(databytes, ptr + 16), 6);
updateRun(fI(b, c, d), 0xbd3af235, bytes_to_int32(databytes, ptr + 44), 10);
updateRun(fI(b, c, d), 0x2ad7d2bb, bytes_to_int32(databytes, ptr + 8), 15);
updateRun(fI(b, c, d), 0xeb86d391, bytes_to_int32(databytes, ptr + 36), 21);
// update buffers
h0 = _add(h0, a);
h1 = _add(h1, b);
h2 = _add(h2, c);
h3 = _add(h3, d);
}
// Done! Convert buffers to 128 bit (LE)
return int128le_to_hex(h3, h2, h1, h0);
}
}
// module.exports = MD5; | the_stack |
/////*1*/var a;var c , b;var $d
/////*2*/var $e
/////*3*/var f
/////*4*/a++;b++;
////
/////*5*/function f ( ) {
/////*6*/ for (i = 0; i < 10; i++) {
/////*7*/ k = abc + 123 ^ d;
/////*8*/ a = XYZ[m (a[b[c][d]])];
/////*9*/ break;
////
/////*10*/ switch ( variable){
/////*11*/ case 1: abc += 425;
/////*12*/break;
/////*13*/case 404 : a [x--/2]%=3 ;
/////*14*/ break ;
/////*15*/ case vari : v[--x ] *=++y*( m + n / k[z]);
/////*16*/ for (a in b){
/////*17*/ for (a = 0; a < 10; ++a) {
/////*18*/ a++;--a;
/////*19*/ if (a == b) {
/////*20*/ a++;b--;
/////*21*/ }
/////*22*/else
/////*23*/if (a == c){
/////*24*/++a;
/////*25*/(--c)+=d;
/////*26*/$c = $a + --$b;
/////*27*/}
/////*28*/if (a == b)
/////*29*/if (a != b) {
/////*30*/ if (a !== b)
/////*31*/ if (a === b)
/////*32*/ --a;
/////*33*/ else
/////*34*/ --a;
/////*35*/ else {
/////*36*/ a--;++b;
/////*37*/a++
/////*38*/ }
/////*39*/ }
/////*40*/ }
/////*41*/ for (x in y) {
/////*42*/m-=m;
/////*43*/k=1+2+3+4;
/////*44*/}
/////*45*/}
/////*46*/ break;
////
/////*47*/ }
/////*48*/ }
/////*49*/ var a ={b:function(){}};
/////*50*/ return {a:1,b:2}
/////*51*/}
////
/////*52*/var z = 1;
/////*53*/ for (i = 0; i < 10; i++)
/////*54*/ for (j = 0; j < 10; j++)
/////*55*/for (k = 0; k < 10; ++k) {
/////*56*/z++;
/////*57*/}
////
/////*58*/for (k = 0; k < 10; k += 2) {
/////*59*/z++;
/////*60*/}
////
/////*61*/ $(document).ready ();
////
////
/////*62*/ function pageLoad() {
/////*63*/ $('#TextBox1' ) . unbind ( ) ;
/////*64*/$('#TextBox1' ) . datepicker ( ) ;
/////*65*/}
////
/////*66*/ function pageLoad ( ) {
/////*67*/ var webclass=[
/////*68*/ { 'student' :/*69*/
/////*70*/ { 'id': '1', 'name': 'Linda Jones', 'legacySkill': 'Access, VB 5.0' }
/////*71*/ } ,
/////*72*/{ 'student':/*73*/
/////*74*/{'id':'2','name':'Adam Davidson','legacySkill':'Cobol,MainFrame'}
/////*75*/} ,
/////*76*/ { 'student':/*77*/
/////*78*/{ 'id':'3','name':'Charles Boyer' ,'legacySkill':'HTML, XML'}
/////*79*/}
/////*80*/ ];
////
/////*81*/$create(Sys.UI.DataView,{data:webclass},null,null,$get('SList'));
////
/////*82*/}
////
/////*83*/$( document ).ready(function(){
/////*84*/alert('hello');
/////*85*/ } ) ;
format.document();
goTo.marker("1");
verify.currentLineContentIs("var a; var c, b; var $d");
goTo.marker("2");
verify.currentLineContentIs("var $e");
goTo.marker("3");
verify.currentLineContentIs("var f");
goTo.marker("4");
verify.currentLineContentIs("a++; b++;");
goTo.marker("5");
verify.currentLineContentIs("function f() {");
goTo.marker("6");
verify.currentLineContentIs(" for (i = 0; i < 10; i++) {");
goTo.marker("7");
verify.currentLineContentIs(" k = abc + 123 ^ d;");
goTo.marker("8");
verify.currentLineContentIs(" a = XYZ[m(a[b[c][d]])];");
goTo.marker("9");
verify.currentLineContentIs(" break;");
goTo.marker("10");
verify.currentLineContentIs(" switch (variable) {");
goTo.marker("11");
verify.currentLineContentIs(" case 1: abc += 425;");
goTo.marker("12");
verify.currentLineContentIs(" break;");
goTo.marker("13");
verify.currentLineContentIs(" case 404: a[x-- / 2] %= 3;");
goTo.marker("14");
verify.currentLineContentIs(" break;");
goTo.marker("15");
verify.currentLineContentIs(" case vari: v[--x] *= ++y * (m + n / k[z]);");
goTo.marker("16");
verify.currentLineContentIs(" for (a in b) {");
goTo.marker("17");
verify.currentLineContentIs(" for (a = 0; a < 10; ++a) {");
goTo.marker("18");
verify.currentLineContentIs(" a++; --a;");
goTo.marker("19");
verify.currentLineContentIs(" if (a == b) {");
goTo.marker("20");
verify.currentLineContentIs(" a++; b--;");
goTo.marker("21");
verify.currentLineContentIs(" }");
goTo.marker("22");
verify.currentLineContentIs(" else");
goTo.marker("23");
verify.currentLineContentIs(" if (a == c) {");
goTo.marker("24");
verify.currentLineContentIs(" ++a;");
goTo.marker("25");
verify.currentLineContentIs(" (--c) += d;");
goTo.marker("26");
verify.currentLineContentIs(" $c = $a + --$b;");
goTo.marker("27");
verify.currentLineContentIs(" }");
goTo.marker("28");
verify.currentLineContentIs(" if (a == b)");
goTo.marker("29");
verify.currentLineContentIs(" if (a != b) {");
goTo.marker("30");
verify.currentLineContentIs(" if (a !== b)");
goTo.marker("31");
verify.currentLineContentIs(" if (a === b)");
goTo.marker("32");
verify.currentLineContentIs(" --a;");
goTo.marker("33");
verify.currentLineContentIs(" else");
goTo.marker("34");
verify.currentLineContentIs(" --a;");
goTo.marker("35");
verify.currentLineContentIs(" else {");
goTo.marker("36");
verify.currentLineContentIs(" a--; ++b;");
goTo.marker("37");
verify.currentLineContentIs(" a++");
goTo.marker("38");
//bug 697788 expect result : " }", actual result : " }"
//verify.currentLineContentIs(" }");
verify.currentLineContentIs(" }");
goTo.marker("39");
verify.currentLineContentIs(" }");
goTo.marker("40");
verify.currentLineContentIs(" }");
goTo.marker("41");
verify.currentLineContentIs(" for (x in y) {");
goTo.marker("42");
verify.currentLineContentIs(" m -= m;");
goTo.marker("43");
verify.currentLineContentIs(" k = 1 + 2 + 3 + 4;");
goTo.marker("44");
verify.currentLineContentIs(" }");
goTo.marker("45");
verify.currentLineContentIs(" }");
goTo.marker("46");
verify.currentLineContentIs(" break;");
goTo.marker("47");
verify.currentLineContentIs(" }");
goTo.marker("48");
verify.currentLineContentIs(" }");
goTo.marker("49");
//bug 704204 expect result : " var a = { b: function () { } };", actual result : " var a = { b: function() { } };"
//verify.currentLineContentIs(" var a = { b: function () { } };");
verify.currentLineContentIs(" var a = { b: function() { } };");
goTo.marker("50");
verify.currentLineContentIs(" return { a: 1, b: 2 }");
goTo.marker("51");
verify.currentLineContentIs("}");
goTo.marker("52");
verify.currentLineContentIs("var z = 1;");
goTo.marker("53");
verify.currentLineContentIs("for (i = 0; i < 10; i++)");
goTo.marker("54");
verify.currentLineContentIs(" for (j = 0; j < 10; j++)");
goTo.marker("55");
verify.currentLineContentIs(" for (k = 0; k < 10; ++k) {");
goTo.marker("56");
verify.currentLineContentIs(" z++;");
goTo.marker("57");
verify.currentLineContentIs(" }");
goTo.marker("58");
verify.currentLineContentIs("for (k = 0; k < 10; k += 2) {");
goTo.marker("59");
verify.currentLineContentIs(" z++;");
goTo.marker("60");
verify.currentLineContentIs("}");
goTo.marker("61");
verify.currentLineContentIs("$(document).ready();");
goTo.marker("62");
verify.currentLineContentIs("function pageLoad() {");
goTo.marker("63");
verify.currentLineContentIs(" $('#TextBox1').unbind();");
goTo.marker("64");
verify.currentLineContentIs(" $('#TextBox1').datepicker();");
goTo.marker("65");
verify.currentLineContentIs("}");
goTo.marker("66");
verify.currentLineContentIs("function pageLoad() {");
goTo.marker("67");
verify.currentLineContentIs(" var webclass = [");
goTo.marker("68");
verify.currentLineContentIs(" {");
goTo.marker("69");
verify.currentLineContentIs(" 'student':");
goTo.marker("70");
verify.currentLineContentIs(" { 'id': '1', 'name': 'Linda Jones', 'legacySkill': 'Access, VB 5.0' }");
goTo.marker("71");
verify.currentLineContentIs(" },");
goTo.marker("72");
verify.currentLineContentIs(" {");
goTo.marker("73");
verify.currentLineContentIs(" 'student':");
goTo.marker("74");
verify.currentLineContentIs(" { 'id': '2', 'name': 'Adam Davidson', 'legacySkill': 'Cobol,MainFrame' }");
goTo.marker("75");
verify.currentLineContentIs(" },");
goTo.marker("76");
verify.currentLineContentIs(" {");
goTo.marker("77");
verify.currentLineContentIs(" 'student':");
goTo.marker("78");
verify.currentLineContentIs(" { 'id': '3', 'name': 'Charles Boyer', 'legacySkill': 'HTML, XML' }");
goTo.marker("79");
verify.currentLineContentIs(" }");
goTo.marker("80");
verify.currentLineContentIs(" ];");
goTo.marker("81");
verify.currentLineContentIs(" $create(Sys.UI.DataView, { data: webclass }, null, null, $get('SList'));");
goTo.marker("82");
verify.currentLineContentIs("}");
goTo.marker("83");
//bug 704204 expect result : "$(document).ready(function () {", actual result : "$(document).ready(function() "
//verify.currentLineContentIs("$(document).ready(function () {");
verify.currentLineContentIs("$(document).ready(function() {");
goTo.marker("84");
verify.currentLineContentIs(" alert('hello');");
goTo.marker("85");
verify.currentLineContentIs("});"); | the_stack |
import LineChart from "./Components/LineChart/LineChart";
import AvailabilityChart from "./Components/AvailabilityChart/AvailabilityChart";
import PieChart from "./Components/PieChart/PieChart";
import ScatterPlot from "./Components/ScatterPlot/ScatterPlot";
import GroupedBarChart from "./Components/GroupedBarChart/GroupedBarChart";
import Grid from "./Components/Grid/Grid";
import Slider from "./Components/Slider/Slider";
import Hierarchy from "./Components/Hierarchy/Hierarchy";
import AggregateExpression from "./Models/AggregateExpression";
import Heatmap from "./Components/Heatmap/Heatmap";
import EventsTable from "./Components/EventsTable/EventsTable";
import ModelSearch from "./Components/ModelSearch/ModelSearch";
import DateTimePicker from "./Components/DateTimePicker/DateTimePicker";
import TimezonePicker from "./Components/TimezonePicker/TimezonePicker";
import Utils from "./Utils";
import './styles.scss'
import EllipsisMenu from "./Components/EllipsisMenu/EllipsisMenu";
import TsqExpression from "./Models/TsqExpression";
import ModelAutocomplete from "./Components/ModelAutocomplete/ModelAutocomplete";
import HierarchyNavigation from "./Components/HierarchyNavigation/HierarchyNavigation";
import SingleDateTimePicker from "./Components/SingleDateTimePicker/SingleDateTimePicker";
import DateTimeButtonSingle from "./Components/DateTimeButtonSingle/DateTimeButtonSingle";
import DateTimeButtonRange from "./Components/DateTimeButtonRange/DateTimeButtonRange";
import ProcessGraphic from './Components/ProcessGraphic/ProcessGraphic';
import PlaybackControls from './Components/PlaybackControls/PlaybackControls';
import ColorPicker from "./Components/ColorPicker/ColorPicker";
import GeoProcessGraphic from "./Components/GeoProcessGraphic/GeoProcessGraphic";
import { transformTsqResultsForVisualization } from "./Utils/Transformers";
class UXClient {
UXClient () {
}
// Public facing components have class constructors exposed as public UXClient members.
// This allows for typings to be bundled while maintaining 'new Component()' syntax
public DateTimePicker: typeof DateTimePicker = DateTimePicker;
public PieChart: typeof PieChart = PieChart;
public ScatterPlot: typeof ScatterPlot = ScatterPlot;
public BarChart: typeof GroupedBarChart = GroupedBarChart;
public LineChart: typeof LineChart = LineChart;
public AvailabilityChart: typeof AvailabilityChart = AvailabilityChart;
public Grid: typeof Grid = Grid;
public Slider: typeof Slider = Slider;
public Hierarchy: typeof Hierarchy = Hierarchy;
public AggregateExpression: typeof AggregateExpression = AggregateExpression;
public TsqExpression: typeof TsqExpression = TsqExpression;
public Heatmap: typeof Heatmap = Heatmap;
public EventsTable: typeof EventsTable = EventsTable;
public ModelSearch: typeof ModelSearch = ModelSearch;
public ModelAutocomplete: typeof ModelAutocomplete = ModelAutocomplete;
public HierarchyNavigation: typeof HierarchyNavigation = HierarchyNavigation;
public TimezonePicker: typeof TimezonePicker = TimezonePicker;
public EllipsisMenu: typeof EllipsisMenu = EllipsisMenu;
public SingleDateTimePicker: typeof SingleDateTimePicker = SingleDateTimePicker;
public DateTimeButtonSingle: typeof DateTimeButtonSingle = DateTimeButtonSingle;
public DateTimeButtonRange: typeof DateTimeButtonRange = DateTimeButtonRange;
public ProcessGraphic: typeof ProcessGraphic = ProcessGraphic;
public PlaybackControls: typeof PlaybackControls = PlaybackControls;
public ColorPicker: typeof ColorPicker = ColorPicker;
public GeoProcessGraphic: typeof GeoProcessGraphic = GeoProcessGraphic;
public transformTsqResultsForVisualization: typeof transformTsqResultsForVisualization = transformTsqResultsForVisualization;
public transformTsxToEventsArray (events, options) {
var timezoneOffset = options.timezoneOffset ? options.timezoneOffset : 0;
var rows = [];
var eventSourceProperties = {};
var nameToStrippedPropName = {};
var valueToStrippedValueMap = {};
for (var eventIdx in events) {
var eventSourceId;
if (events[eventIdx].hasOwnProperty('schema')) {
eventSourceProperties[events[eventIdx].schema.rid] = {};
eventSourceProperties[events[eventIdx].schema.rid].propertyNames = events[eventIdx].schema.properties.reduce(function(prev, curr) {
prev.push({ name: curr.name, type: curr.type });
return prev;
}, []);
eventSourceProperties[events[eventIdx].schema.rid].eventSourceName = events[eventIdx].schema['$esn'];
eventSourceId = events[eventIdx].schema.rid;
} else {
eventSourceId = events[eventIdx].schemaRid;
}
var timeStamp = (new Date((new Date(events[eventIdx]['$ts'])).valueOf() - timezoneOffset)).toISOString().slice(0,-1).replace('T', ' ');
var event = { 'timestamp ($ts)': timeStamp };
// lts logic
var lts = events[eventIdx]['$lts'] ? events[eventIdx]['$lts'] : null;
if (lts) {
event['LocalTimestamp_DateTime'] = {
value: lts.replace('T', ' '),
name: 'LocalTimestamp',
type: 'DateTime'
}
}
event["EventSourceName_String"] = {
value: eventSourceProperties[eventSourceId].eventSourceName,
name: 'EventSourceName',
type: 'String'
};
for (var propIdx in eventSourceProperties[eventSourceId].propertyNames) {
var name = eventSourceProperties[eventSourceId].propertyNames[propIdx].name;
if (!nameToStrippedPropName.hasOwnProperty(name))
nameToStrippedPropName[name] = Utils.stripForConcat(name);
var strippedName = nameToStrippedPropName[name];
var type = eventSourceProperties[eventSourceId].propertyNames[propIdx].type;
var columnNameAndType = strippedName + "_" + type;
if (!valueToStrippedValueMap.hasOwnProperty(String(events[eventIdx].values[propIdx])))
valueToStrippedValueMap[String(events[eventIdx].values[propIdx])] = Utils.stripForConcat(String(events[eventIdx].values[propIdx]));
var eventObject = {
value: valueToStrippedValueMap[String(events[eventIdx].values[propIdx])],
name: strippedName,
type: type
}
event[columnNameAndType] = eventObject;
}
if (events[eventIdx].hasOwnProperty('$op')) {
let defaultType = 'String';
let otherProps = JSON.parse(events[eventIdx]['$op']);
Object.keys(otherProps).forEach((propNameRaw) => {
let strippedNameOP = Utils.stripForConcat(propNameRaw);
let columnNameAndTypeOP = strippedNameOP + '_String';
event[columnNameAndTypeOP] = {
value: otherProps[propNameRaw],
name: strippedNameOP,
type: defaultType
}
});
}
rows.push(event);
}
return rows;
}
private toISONoMillis (dateTime) {
return dateTime.toISOString().slice(0,-5)+"Z";
}
//specifiedRange gives the subset of availability buckets to be returned. If not included, will return all buckets
public transformAvailabilityForVisualization(availabilityTsx: any): Array<any> {
var from = new Date(availabilityTsx.range.from);
var to = new Date(availabilityTsx.range.to);
var rawBucketSize = Utils.parseTimeInput(availabilityTsx.intervalSize);
var buckets = {};
var startBucket = Math.round(Math.floor(from.valueOf() / rawBucketSize) * rawBucketSize);
var firstKey = this.toISONoMillis(new Date(startBucket));
var firstCount = availabilityTsx.distribution[firstKey] ? availabilityTsx.distribution[firstKey] : 0;
// reset first key if greater than the availability range from
if (startBucket < (new Date(availabilityTsx.range.from)).valueOf())
firstKey = this.toISONoMillis(new Date(availabilityTsx.range.from));
buckets[firstKey] = {count: firstCount }
Object.keys(availabilityTsx.distribution).forEach(key => {
var formattedISO = this.toISONoMillis(new Date(key));
buckets[formattedISO] = {count: availabilityTsx.distribution[key]};
});
//set end time value
var lastBucket = Math.round(Math.floor(to.valueOf() / rawBucketSize) * rawBucketSize);
// pad out if range is less than one bucket;
if (startBucket == lastBucket) {
for(var i = startBucket; i <= startBucket + rawBucketSize; i += (rawBucketSize / 60)) {
if (buckets[this.toISONoMillis(new Date(i))] == undefined)
buckets[this.toISONoMillis(new Date(i))] = {count : 0};
}
//reset startBucket to count 0 if not the start time
if (startBucket != from.valueOf()) {
buckets[this.toISONoMillis(new Date(startBucket))] = {count : 0}
}
}
return [{"availabilityCount" : {"" : buckets}}];
}
public transformAggregatesForVisualization(aggregates: Array<any>, options): Array<any> {
var result = [];
aggregates.forEach((agg, i) => {
var transformedAggregate = {};
var aggregatesObject = {};
transformedAggregate[options[i].alias] = aggregatesObject;
if(agg.hasOwnProperty('__tsiError__'))
transformedAggregate[''] = {};
else if(agg.hasOwnProperty('aggregate')){
agg.dimension.forEach((d, j) => {
var dateTimeToValueObject = {};
aggregatesObject[d] = dateTimeToValueObject;
agg.aggregate.dimension.forEach((dt, k) => {
var measuresObject = {};
dateTimeToValueObject[dt] = measuresObject;
options[i].measureTypes.forEach((t,l) => {
if (agg.aggregate.measures[j][k] != null && agg.aggregate.measures[j][k] != undefined &&
agg.aggregate.measures[j][k][l] != null && agg.aggregate.measures[j][k][l] != undefined)
measuresObject[t] = agg.aggregate.measures[j][k][l];
else
measuresObject[t] = null;
})
})
})
}
else{
var dateTimeToValueObject = {};
aggregatesObject[''] = dateTimeToValueObject;
agg.dimension.forEach((dt,j) => {
var measuresObject = {};
dateTimeToValueObject[dt] = measuresObject;
options[i].measureTypes.forEach((t,l) => {
measuresObject[t] = agg.measures[j][l];
})
})
}
result.push(transformedAggregate);
});
return result;
}
// exposed publicly to use for highlighting elements in the well on hover/focus
public createEntityKey (aggName: string, aggIndex: number = 0) {
return Utils.createEntityKey(aggName, aggIndex);
}
public transformTsqResultsToEventsArray (results) {
let flattenedResults = [];
results.forEach(tsqr => {
tsqr.timestamps.forEach((ts, idx) => {
let event = {};
event['timestamp ($ts)'] = ts;
tsqr.properties.forEach(p => {
event[`${p.name}_${p.type}`] = {name: p.name, type: p.type, value: p.values[idx]};
});
flattenedResults.push(event);
});
});
return flattenedResults.sort((a,b) => (new Date(a['timestamp ($ts)'])).valueOf() < (new Date(b['timestamp ($ts)'])).valueOf() ? -1 : 1);
}
}
export default UXClient | the_stack |
import { ResolvedLayoutConfig, ResolvedPopoutLayoutConfig } from '../config/resolved-config';
import { PopoutBlockedError } from '../errors/external-error';
import { UnexpectedNullError, UnexpectedUndefinedError } from '../errors/internal-error';
import { ContentItem } from '../items/content-item';
import { LayoutManager } from '../layout-manager';
import { EventEmitter } from '../utils/event-emitter';
import { Rect } from '../utils/types';
import { deepExtend, getUniqueId } from '../utils/utils';
/**
* Pops a content item out into a new browser window.
* This is achieved by
*
* - Creating a new configuration with the content item as root element
* - Serializing and minifying the configuration
* - Opening the current window's URL with the configuration as a GET parameter
* - GoldenLayout when opened in the new window will look for the GET parameter
* and use it instead of the provided configuration
* @public
*/
export class BrowserPopout extends EventEmitter {
/** @internal */
private _popoutWindow: Window | null;
/** @internal */
private _isInitialised;
/** @internal */
private _checkReadyInterval: ReturnType<typeof setTimeout> | undefined;
/**
* @param _config - GoldenLayout item config
* @param _initialWindowSize - A map with width, height, top and left
* @internal
*/
constructor(
/** @internal */
private _config: ResolvedPopoutLayoutConfig,
/** @internal */
private _initialWindowSize: Rect,
/** @internal */
private _layoutManager: LayoutManager,
) {
super();
this._isInitialised = false;
this._popoutWindow = null;
this.createWindow();
}
toConfig(): ResolvedPopoutLayoutConfig {
if (this._isInitialised === false) {
throw new Error('Can\'t create config, layout not yet initialised');
}
const glInstance = this.getGlInstance();
const glInstanceConfig = glInstance.saveLayout();
let left: number | null;
let top: number | null;
if (this._popoutWindow === null) {
left = null;
top = null;
} else {
left = this._popoutWindow.screenX ?? this._popoutWindow.screenLeft;
top = this._popoutWindow.screenY ?? this._popoutWindow.screenTop;
}
const window: ResolvedPopoutLayoutConfig.Window = {
width: this.getGlInstance().width,
height: this.getGlInstance().height,
left,
top,
};
const config: ResolvedPopoutLayoutConfig = {
root: glInstanceConfig.root,
openPopouts: glInstanceConfig.openPopouts,
settings: glInstanceConfig.settings,
dimensions: glInstanceConfig.dimensions,
header: glInstanceConfig.header,
window,
parentId: this._config.parentId,
indexInParent: this._config.indexInParent,
resolved: true,
};
return config;
}
getGlInstance(): LayoutManager {
if (this._popoutWindow === null) {
throw new UnexpectedNullError('BPGGI24693');
}
return this._popoutWindow.__glInstance;
}
/**
* Retrieves the native BrowserWindow backing this popout.
* Might throw an UnexpectedNullError exception when the window is not initialized yet.
* @public
*/
getWindow(): Window {
if (this._popoutWindow === null) {
throw new UnexpectedNullError('BPGW087215');
}
return this._popoutWindow;
}
close(): void {
if (this.getGlInstance()) {
this.getGlInstance().closeWindow();
} else {
try {
this.getWindow().close();
} catch (e) {
//
}
}
}
/**
* Returns the popped out item to its original position. If the original
* parent isn't available anymore it falls back to the layout's topmost element
*/
popIn(): void {
let parentItem: ContentItem;
let index = this._config.indexInParent;
if (!this._config.parentId) {
return;
}
/*
* The deepExtend call seems a bit pointless, but it's crucial to
* copy the config returned by this.getGlInstance().toConfig()
* onto a new object. Internet Explorer keeps the references
* to objects on the child window, resulting in the following error
* once the child window is closed:
*
* The callee (server [not server application]) is not available and disappeared
*/
const glInstanceLayoutConfig = this.getGlInstance().saveLayout();
const copiedGlInstanceLayoutConfig = deepExtend({}, glInstanceLayoutConfig) as ResolvedLayoutConfig;
const copiedRoot = copiedGlInstanceLayoutConfig.root;
if (copiedRoot === undefined) {
throw new UnexpectedUndefinedError('BPPIR19998');
}
const groundItem = this._layoutManager.groundItem;
if (groundItem === undefined) {
throw new UnexpectedUndefinedError('BPPIG34972');
}
parentItem = groundItem.getItemsByPopInParentId(this._config.parentId)[0];
/*
* Fallback if parentItem is not available. Either add it to the topmost
* item or make it the topmost item if the layout is empty
*/
if (!parentItem) {
if (groundItem.contentItems.length > 0) {
parentItem = groundItem.contentItems[0];
} else {
parentItem = groundItem;
}
index = 0;
}
const newContentItem = this._layoutManager.createAndInitContentItem(copiedRoot, parentItem);
parentItem.addChild(newContentItem, index);
if (this._layoutManager.layoutConfig.settings.popInOnClose) {
this._onClose();
} else {
this.close();
}
}
/**
* Creates the URL and window parameter
* and opens a new window
* @internal
*/
private createWindow(): void {
const url = this.createUrl();
/**
* Bogus title to prevent re-usage of existing window with the
* same title. The actual title will be set by the new window's
* GoldenLayout instance if it detects that it is in subWindowMode
*/
const target = Math.floor(Math.random() * 1000000).toString(36);
/**
* The options as used in the window.open string
*/
const features = this.serializeWindowFeatures({
width: this._initialWindowSize.width,
height: this._initialWindowSize.height,
innerWidth: this._initialWindowSize.width,
innerHeight: this._initialWindowSize.height,
menubar: 'no',
toolbar: 'no',
location: 'no',
personalbar: 'no',
resizable: 'yes',
scrollbars: 'no',
status: 'no'
});
this._popoutWindow = globalThis.open(url, target, features);
if (!this._popoutWindow) {
if (this._layoutManager.layoutConfig.settings.blockedPopoutsThrowError === true) {
const error = new PopoutBlockedError('Popout blocked');
throw error;
} else {
return;
}
}
this._popoutWindow.addEventListener('load', () => this.positionWindow(), { passive: true })
this._popoutWindow.addEventListener('beforeunload', () => {
if (this._layoutManager.layoutConfig.settings.popInOnClose) {
this.popIn();
} else {
this._onClose();
}
}, { passive: true })
/**
* Polling the childwindow to find out if GoldenLayout has been initialised
* doesn't seem optimal, but the alternatives - adding a callback to the parent
* window or raising an event on the window object - both would introduce knowledge
* about the parent to the child window which we'd rather avoid
*/
this._checkReadyInterval = setInterval(() => this.checkReady(), 10);
}
/** @internal */
private checkReady() {
if (this._popoutWindow === null) {
throw new UnexpectedNullError('BPCR01844');
} else {
if (this._popoutWindow.__glInstance && this._popoutWindow.__glInstance.isInitialised) {
this.onInitialised();
if (this._checkReadyInterval !== undefined) {
clearInterval(this._checkReadyInterval);
this._checkReadyInterval = undefined;
}
}
}
}
/**
* Serialises a map of key:values to a window options string
*
* @param windowOptions -
*
* @returns serialised window options
* @internal
*/
private serializeWindowFeatures(windowOptions: Record<string, string | number>): string {
const windowOptionsString: string[] = [];
for (const key in windowOptions) {
windowOptionsString.push(key + '=' + windowOptions[key].toString());
}
return windowOptionsString.join(',');
}
/**
* Creates the URL for the new window, including the
* config GET parameter
*
* @returns URL
* @internal
*/
private createUrl(): string {
const storageKey = 'gl-window-config-' + getUniqueId();
const config = ResolvedLayoutConfig.minifyConfig(this._config);
try {
localStorage.setItem(storageKey, JSON.stringify(config));
} catch (e) {
throw new Error('Error while writing to localStorage ' + e.toString());
}
const url = new URL(location.href);
url.searchParams.set('gl-window', storageKey);
return url.toString();
}
/**
* Move the newly created window roughly to
* where the component used to be.
* @internal
*/
private positionWindow() {
if (this._popoutWindow === null) {
throw new Error('BrowserPopout.positionWindow: null popoutWindow');
} else {
this._popoutWindow.moveTo(this._initialWindowSize.left, this._initialWindowSize.top);
this._popoutWindow.focus();
}
}
/**
* Callback when the new window is opened and the GoldenLayout instance
* within it is initialised
* @internal
*/
private onInitialised(): void {
this._isInitialised = true;
this.getGlInstance().on('popIn', () => this.popIn());
this.emit('initialised');
}
/**
* Invoked 50ms after the window unload event
* @internal
*/
private _onClose() {
setTimeout(() => this.emit('closed'), 50);
}
} | the_stack |
import { Component, Input, Output, Pipe, PipeTransform, ViewChild, EventEmitter } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { Validators, FormGroup, FormControl, FormArray, FormBuilder } from '@angular/forms';
import { ExportServiceCfg } from './export.service'
import { TreeView} from './treeview';
import { IMultiSelectOption, IMultiSelectSettings, IMultiSelectTexts } from '../multiselect-dropdown';
//Services
import { InfluxServerService } from '../../influxserver/influxservercfg.service';
import { SnmpDeviceService } from '../../snmpdevice/snmpdevicecfg.service';
import { MeasurementService } from '../../measurement/measurementcfg.service';
import { OidConditionService } from '../../oidcondition/oidconditioncfg.service';
import { SnmpMetricService } from '../../snmpmetric/snmpmetriccfg.service';
import { MeasGroupService } from '../../measgroup/measgroupcfg.service';
import { MeasFilterService } from '../../measfilter/measfiltercfg.service';
import { CustomFilterService } from '../../customfilter/customfilter.service';
import { VarCatalogService } from '../../varcatalog/varcatalogcfg.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'export-file-modal',
template: `
<div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog" style="width:90%">
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" (click)="childModal.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" *ngIf="exportObject != null">{{titleName}} <b>{{ exportObject.ID }}</b> - <label [ngClass]="['label label-'+colorsObject[exportType]]">{{exportType}}</label></h4>
<h4 class="modal-title" *ngIf="exportObject == null">Export</h4>
</div>
<div class="modal-body">
<div *ngIf="prepareExport === false">
<div class="row">
<div class="col-md-2">
<div class="panel-heading">
1.Select type:
</div>
<div class="panel panel-default" *ngFor="let items of objectTypes; let i = index" style="margin-bottom: 0px" >
<div class="panel-heading" (click)="loadSelection(i, items.Type)" role="button">
<i [ngClass]="selectedType ? (selectedType.Type === items.Type ? ['glyphicon glyphicon-eye-open'] : ['glyphicon glyphicon-eye-close'] ) : ['glyphicon glyphicon-eye-close']" style="padding-right: 10px"></i>
<label [ngClass]="['label label-'+items.Class]"> {{items.Type}} </label>
</div>
</div>
</div>
<div class="col-md-5">
<div *ngIf="selectedType">
<div class="panel-heading">
<div>
2. Select Items of type <label [ngClass]="['label label-'+selectedType.Class]"> {{selectedType.Type}}</label> <span class="badge" style="margin-left: 10px">{{resultArray.length}} Results</span>
</div>
<div dropdown class="text-left" style="margin-top: 10px">
<span class="dropdown-toggle-split">Filter by</span>
<ss-multiselect-dropdown style="border: none" class="text-primary" [options]="listFilterProp" [texts]="myTexts" [settings]="propSettings" [(ngModel)]="selectedFilterProp" (ngModelChange)="onChange(filter)"></ss-multiselect-dropdown>
<input type=text [(ngModel)]="filter" placeholder="Filter items..." (ngModelChange)="onChange($event)">
<label [tooltip]="'Clear Filter'" container="body" (click)="filter=''; onChange(filter)"><i class="glyphicon glyphicon-trash text-primary"></i></label>
</div>
<div class="text-right">
<label class="label label-success" (click)=selectAllItems(true)>Select All</label>
<label class="label label-danger" (click)=selectAllItems(false)>Deselect All</label>
</div>
</div>
<div style="max-height: 400px; overflow-y:auto">
<div *ngFor="let res of resultArray; let i = index" style="margin-bottom: 0px" >
<treeview [keyProperty]="selectedFilterProp" [showType]="false" [visible]="false" [title]="res.ID" [object]="res" [alreadySelected]="checkItems(res.ID, selectedType.Type)" [type]="selectedType.Type" [visibleToogleEnable]="true" [addClickEnable]="true" (addClicked)="selectItem($event,index)" style="margin-bottom:0px !important">{{res}}</treeview>
</div>
</div>
</div>
</div>
<div class="col-md-5">
<div *ngIf="finalArray.length !== 0">
<div class="panel-heading"> 3. Items ready to export: <span class="badge">{{finalArray.length}}</span>
<div class="text-right">
<label class="label label-danger" (click)="finalArray = []">Clear All</label>
</div>
</div>
<div style="max-height: 400px; overflow-y:auto">
<div *ngFor="let res of finalArray; let i = index" class="col-md-12">
<i class="text-danger glyphicon glyphicon-remove-sign col-md-1" role="button" style="margin-top: 15px;" (click)="removeItem(i)"> </i>
<treeview [visible]="false" [title]="res.ObjectID" [object]="res" [type]="res.ObjectTypeID" [recursiveToogle]="true" [index] = "i" (recursiveClicked)="toogleRecursive($event)" class="col-md-11">{{res}}</treeview>
</div>
</div>
</div>
</div>
</div>
</div>
<div *ngIf="prepareExport === true">
<div *ngIf="exportResult === true" style="overflow-y: scroll; max-height: 350px">
<h4 class="text-success"> <i class="glyphicon glyphicon-ok-circle" style="padding-right:10px"></i>Succesfully exported {{exportedItem.Objects.length}} items </h4>
<div *ngFor="let object of exportedItem.Objects; let i=index">
<treeview [visible]="false" [visibleToogleEnable]="true" [title]="object.ObjectID" [type]="object.ObjectTypeID" [object]="object.ObjectCfg"> </treeview>
</div>
</div>
<div *ngIf="exportForm && exportResult === false">
<form class="form-horizontal" *ngIf="bulkExport === false">
<div class="form-group">
<label class="col-sm-2 col-offset-sm-2" for="Recursive">Recursive</label>
<i placement="top" style="float: left" class="info control-label glyphicon glyphicon-info-sign" tooltipAnimation="true" tooltip="Select if the export request will include all related componentes"></i>
<div class="col-sm-9">
<select name="recursiveObject" class="form-control" id="recursiveObject" [(ngModel)]="recursiveObject">
<option value="true">True</option>
<option value="false">False</option>
</select>
</div>
</div>
</form>
<form [formGroup]="exportForm" class="form-horizontal" >
<div class="form-group">
<label for="FileName" class="col-sm-2 col-offset-sm-2 control-FileName">FileName</label>
<i placement="top" style="float: left" class="info control-label glyphicon glyphicon-info-sign" tooltipAnimation="true" tooltip="Desired file name"></i>
<div class="col-sm-9">
<input type="text" class="form-control" placeholder="file.json" formControlName="FileName" id="FileName">
</div>
</div>
<div class="form-group">
<label for="Author" class="col-sm-2 control-Author">Author</label>
<i placement="top" style="float: left" class="info control-label glyphicon glyphicon-info-sign" tooltipAnimation="true" tooltip="Author of the export"></i>
<div class="col-sm-9">
<input type="text" class="form-control" placeholder="snmpcollector" formControlName="Author" id="Author">
</div>
</div>
<div class="form-group">
<label for="Tags" class="col-sm-2 control-Tags">Tags</label>
<i placement="top" style="float: left" class="info control-label glyphicon glyphicon-info-sign" tooltipAnimation="true" tooltip="Related tags to identify exported data"></i>
<div class="col-sm-9">
<input type="text" class="form-control" placeholder="cisco,catalyst,..." formControlName="Tags" id="Tags">
</div>
</div>
<div class="form-group">
<label for="FileName" class="col-sm-2 control-FileName">Description</label>
<i placement="top" style="float: left" class="info control-label glyphicon glyphicon-info-sign" tooltipAnimation="true" tooltip="Description of the exported file"></i>
<div class="col-sm-9">
<textarea class="form-control" style="width: 100%" rows="2" formControlName="Description" id="Description"> </textarea>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer" *ngIf="showValidation === true">
<button type="button" class="btn btn-default" (click)="childModal.hide()">Close</button>
<button *ngIf="exportResult === false && prepareExport === true" type="button" class="btn btn-primary" (click)="exportBulkItem()">{{textValidation ? textValidation : Save}}</button>
<button *ngIf="prepareExport === false" type="button" class="btn btn-primary" [disabled]="finalArray.length === 0" (click)="showExportForm()">Continue</button>
</div>
</div>
</div>
</div>`,
styleUrls: ['./import-modal-styles.css'],
providers: [ExportServiceCfg, InfluxServerService, SnmpDeviceService, SnmpMetricService, MeasurementService, OidConditionService,MeasGroupService, MeasFilterService, CustomFilterService, VarCatalogService, TreeView]
})
export class ExportFileModal {
@ViewChild('childModal') public childModal: ModalDirective;
@Input() titleName: any;
@Input() customMessage: string;
@Input() showValidation: boolean;
@Input() textValidation: string;
@Input() prepareExport : boolean = true;
@Input() bulkExport: boolean = false;
@Input() exportType: any = null;
@Output() public validationClicked: EventEmitter<any> = new EventEmitter();
public validationClick(myId: string): void {
this.validationClicked.emit(myId);
}
public builder: any;
public exportForm: any;
public mySubscriber: Subscription;
constructor(builder: FormBuilder, public exportServiceCfg : ExportServiceCfg,
public influxServerService: InfluxServerService, public metricMeasService: SnmpMetricService,
public measurementService: MeasurementService, public oidConditionService : OidConditionService,
public snmpDeviceService: SnmpDeviceService, public measGroupService: MeasGroupService,
public measFilterService: MeasFilterService, public customFilterService: CustomFilterService,
public varCatalogService: VarCatalogService) {
this.builder = builder;
}
//COMMON
createStaticForm() {
this.exportForm = this.builder.group({
FileName: [this.prepareExport ? this.exportObject.ID+'_'+this.exportType+'_'+this.nowDate+'.json' : 'bulkexport_'+this.nowDate+'.json' , Validators.required],
Author: ['snmpcollector', Validators.required],
Tags: [''],
Recursive: [true, Validators.required],
Description: ['Autogenerated', Validators.required]
});
}
//Single Object Export:
exportObject: any = null;
//Single Object
public colorsObject : Object = {
"snmpdevicecfg" : 'danger',
"influxcfg" : 'info',
"measfiltercfg": 'warning',
"oidconditioncfg" : 'success',
"customfiltercfg" : 'default',
"measurementcfg" : 'primary',
"snmpmetriccfg" : 'warning',
"measgroupcfg" : 'success',
"varcatalogcfg" : 'default'
};
//Control to load exported result
exportResult : boolean = false;
exportedItem : any;
//Others
nowDate : any;
recursiveObject : boolean = true;
//Bulk Export - Result Array from Loading data:
resultArray : any = [];
dataArray : any = [];
selectedFilterProp : any = "ID";
listFilterProp: IMultiSelectOption[] = [];
private propSettings: IMultiSelectSettings = {
singleSelect: true,
};
//Bulk Export - SelectedType
selectedType : any = null;
finalArray : any = [];
filter : any = "";
//Bulk Objects
public objectTypes : any = [
{'Type':"snmpdevicecfg", 'Class' : 'danger', 'Visible': false},
{'Type':"influxcfg" ,'Class' : 'info', 'Visible': false},
{'Type':"measfiltercfg", 'Class' : 'warning','Visible': false},
{'Type':"oidconditioncfg", 'Class' : 'success', 'Visible': false},
{'Type':"customfiltercfg", 'Class' : 'default', 'Visible': false},
{'Type':"measurementcfg", 'Class' : 'primary', 'Visible': false},
{'Type':"snmpmetriccfg", 'Class' : 'warning', 'Visible': false},
{'Type':"measgroupcfg", 'Class' : 'success', 'Visible': false},
{'Type':"varcatalogcfg", 'Class' : 'default', 'Visible': false}
]
//Reset Vars on Init
clearVars() {
this.finalArray = [];
this.resultArray = [];
this.selectedType = null;
this.exportResult = false;
this.exportedItem = [];
this.exportType = this.exportType || null;
this.exportObject = null;
}
//Init Modal, depending from where is called
initExportModal(exportObject: any, prepareExport? : boolean) {
this.clearVars();
if (prepareExport === false) {
this.prepareExport = false;
} else {
this.prepareExport = true;
};
//Single export
if (this.prepareExport === true) {
console.log(exportObject);
this.exportObject = exportObject.row || exportObject;
this.exportType = exportObject.exportType || this.exportType;
//Sets the FinalArray to export the items, in this case only be 1
this.finalArray = [{
'ObjectID' : this.exportObject.ID,
'ObjectTypeID' : this.exportType,
'Options' : {
Recursive: this.recursiveObject
}
}]
//Bulk export
} else {
this.exportObject = exportObject;
this.exportType = null;
}
this.nowDate = this.getCustomTimeString()
this.createStaticForm();
this.childModal.show();
}
getCustomTimeString(){
let date = new Date();
let day = ('0' + date.getDate()).slice(-2);
let year = date.getFullYear().toString();
let month = ('0' + (date.getMonth()+1)).slice(-2);
let ymd =year+month+day;
let hm = date.getHours().toString()+date.getMinutes().toString();
return ymd + '_' + hm;
}
onChange(event){
let tmpArray = this.dataArray.filter((item: any) => {
if (item[this.selectedFilterProp]) return item[this.selectedFilterProp].toString().match(event);
else if (event === "" && !item[this.selectedFilterProp]) return item;
});
this.resultArray = tmpArray;
}
changeFilterProp(prop){
this.selectedFilterProp = prop;
}
//Load items from selection type
loadSelection(i, type) {
for (let a of this.objectTypes) {
if(type !== this.objectTypes[i].Type) {
this.objectTypes[i].Visible = false;
}
}
this.objectTypes[i].Visible = true;
this.selectedType = this.objectTypes[i];
this.filter = "";
this.loadItems(type,null);
}
checkItems(checkItem: any,type) : boolean {
//Extract the ID from finalArray and loaded Items:
let exist = true;
for (let a of this.finalArray) {
if (checkItem === a.ObjectID) {
exist = false;
}
}
return exist;
}
//Common function to find given object property inside an array
findIndexItem(checkArray, checkItem: any) : any {
for (let a in checkArray) {
if (checkItem === checkArray[a].ObjectID) {
return a;
}
}
}
selectAllItems(selectAll) {
//Creates the form array
if (selectAll === true) {
for (let a of this.resultArray) {
if (this.checkItems(a.ID, this.selectedType)) {
this.finalArray.push({ "ObjectID" : a.ID, ObjectTypeID: this.selectedType.Type, "Options" : {'Recursive': false }});
}
}
} else {
for (let a of this.resultArray) {
let index = this.findIndexItem(this.finalArray, a.ID);
if (index) this.removeItem(index);
}
}
}
//Select item to add it to the FinalArray or delete it if its alreay selected
selectItem(event) {
if (this.checkItems(event.ObjectID, event.ObjectTypeID)) {
this.finalArray.push(event);
}
else {
let index = this.findIndexItem(this.finalArray, event.ObjectID);
this.removeItem(index);
}
}
//Remove item from Array
removeItem(index) {
this.finalArray.splice(index,1);
}
//Change Recursive option on the FinalArray objects
toogleRecursive(event) {
this.finalArray[event.Index].Options.Recursive = event.Recursive;
}
showExportForm() {
this.prepareExport = true;
}
exportBulkItem(){
if (this.bulkExport === false) this.finalArray[0].Options.Recursive = this.recursiveObject;
let finalValues = {"Info": this.exportForm.value, "Objects" : this.finalArray}
this.exportServiceCfg.bulkExport(finalValues)
.subscribe(
data => {
this.exportedItem = data[1];
saveAs(data[0],data[1].Info.FileName);
this.exportResult = true;
},
err => console.error(err),
() => console.log("DONE"),
);
}
//SINGLE EXPORT
/* exportItem(){
this.exportServiceCfg.bulkExport(this.finalArray[0])
.subscribe(
data => {
this.exportedItem = data[1];
saveAs(data[0],data[1].Info.FileName);
this.exportResult = true;
},
err => console.error(err),
() => console.log("DONE"),
);
}
*/
//Load items functions from services depending on items selected Type
loadItems(type, filter?) {
this.resultArray = [];
this.selectedFilterProp = "ID";
this.listFilterProp = [];
if (this.mySubscriber) this.mySubscriber.unsubscribe();
switch (type) {
case 'snmpdevicecfg':
this.mySubscriber = this.snmpDeviceService.getDevices(filter)
.subscribe(
data => {
//Load items on selection
this.dataArray = data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'influxcfg':
this.mySubscriber = this.influxServerService.getInfluxServer(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'oidconditioncfg':
this.mySubscriber = this.oidConditionService.getConditions(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'measfiltercfg':
this.mySubscriber = this.measFilterService.getMeasFilter(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'customfiltercfg':
this.mySubscriber = this.customFilterService.getCustomFilter(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'measurementcfg':
this.mySubscriber = this.measurementService.getMeas(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'snmpmetriccfg':
this.mySubscriber = this.metricMeasService.getMetrics(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'measgroupcfg':
this.mySubscriber = this.measGroupService.getMeasGroup(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
case 'varcatalogcfg':
this.mySubscriber = this.varCatalogService.getVarCatalog(filter)
.subscribe(
data => {
this.dataArray=data;
this.resultArray = this.dataArray;
for (let i in this.dataArray[0]) {
this.listFilterProp.push({ 'id': i, 'name': i });
}
},
err => {console.log(err)},
() => {console.log("DONE")}
);
break;
default:
break;
}
}
//Common Functions
isArray(myObject) {
return myObject instanceof Array;
}
isObject(myObject) {
return typeof myObject === 'object'
}
hide() {
if (this.mySubscriber) this.mySubscriber.unsubscribe();
this.childModal.hide();
}
} | the_stack |
* Original code taken from https://github.com/kvz/locutus
*/
function initCache () {
const store: any[] = []
// cache only first element, second is length to jump ahead for the parser
const cache = function cache (value) {
store.push(value[0])
return value
}
cache.get = (index) => {
if (index >= store.length) {
throw RangeError(`Can't resolve reference ${index + 1}`)
}
return store[index]
}
return cache
}
function expectType (str, cache) {
const types = /^(?:N(?=;)|[bidsSaOCrR](?=:)|[^:]+(?=:))/g
const type = (types.exec(str) || [])[0]
if (!type) {
throw SyntaxError('Invalid input: ' + str)
}
switch (type) {
case 'N':
return cache([ null, 2 ])
case 'b':
return cache(expectBool(str))
case 'i':
return cache(expectInt(str))
case 'd':
return cache(expectFloat(str))
case 's':
return cache(expectString(str))
case 'S':
return cache(expectEscapedString(str))
case 'a':
return expectArray(str, cache)
case 'O':
return expectObject(str, cache)
case 'C':
return expectClass(str, cache)
case 'r':
case 'R':
return expectReference(str, cache)
default:
throw SyntaxError(`Invalid or unsupported data type: ${type}`)
}
}
function expectBool (str) {
const reBool = /^b:([01]);/
const [ match, boolMatch ] = reBool.exec(str) || []
if (!boolMatch) {
throw SyntaxError('Invalid bool value, expected 0 or 1')
}
return [ boolMatch === '1', match.length ]
}
function expectInt (str) {
const reInt = /^i:([+-]?\d+);/
const [ match, intMatch ] = reInt.exec(str) || []
if (!intMatch) {
throw SyntaxError('Expected an integer value')
}
return [ parseInt(intMatch, 10), match.length ]
}
function expectFloat (str) {
const reFloat = /^d:(NAN|-?INF|(?:\d+\.\d*|\d*\.\d+|\d+)(?:[eE][+-]\d+)?);/
const [ match, floatMatch ] = reFloat.exec(str) || []
if (!floatMatch) {
throw SyntaxError('Expected a float value')
}
let floatValue
switch (floatMatch) {
case 'NAN':
floatValue = Number.NaN
break
case '-INF':
floatValue = Number.NEGATIVE_INFINITY
break
case 'INF':
floatValue = Number.POSITIVE_INFINITY
break
default:
floatValue = parseFloat(floatMatch)
break
}
return [ floatValue, match.length ]
}
function readBytes (str, len, escapedString = false) {
let bytes = 0
let out = ''
let c = 0
const strLen = str.length
let wasHighSurrogate = false
let escapedChars = 0
while (bytes < len && c < strLen) {
let chr = str.charAt(c)
const code = chr.charCodeAt(0)
const isHighSurrogate = code >= 0xd800 && code <= 0xdbff
const isLowSurrogate = code >= 0xdc00 && code <= 0xdfff
if (escapedString && chr === '\\') {
chr = String.fromCharCode(parseInt(str.substring(c + 1, c + 3), 16))
escapedChars++
// each escaped sequence is 3 characters. Go 2 chars ahead.
// third character will be jumped over a few lines later
c += 2
}
c++
bytes += isHighSurrogate || (isLowSurrogate && wasHighSurrogate)
// if high surrogate, count 2 bytes, as expectation is to be followed by low surrogate
// if low surrogate preceded by high surrogate, add 2 bytes
? 2
: code > 0x7ff
// otherwise low surrogate falls into this part
? 3
: code > 0x7f
? 2
: 1
// if high surrogate is not followed by low surrogate, add 1 more byte
bytes += wasHighSurrogate && !isLowSurrogate ? 1 : 0
out += chr
wasHighSurrogate = isHighSurrogate
}
return [ out, bytes, escapedChars ]
}
function expectString (str) {
// PHP strings consist of one-byte characters.
// JS uses 2 bytes with possible surrogate pairs.
// Serialized length of 2 is still 1 JS string character
const reStrLength = /^s:(\d+):"/g // also match the opening " char
const [ match, byteLenMatch ] = reStrLength.exec(str) || []
if (!match) {
throw SyntaxError('Expected a string value')
}
const len = parseInt(byteLenMatch, 10)
str = str.substring(match.length)
let [ strMatch, bytes ] = readBytes(str, len)
if (bytes !== len) {
throw SyntaxError(`Expected string of ${len} bytes, but got ${bytes}`)
}
str = str.substring((strMatch as string).length)
// strict parsing, match closing "; chars
if (!str.startsWith('";')) {
throw SyntaxError('Expected ";')
}
return [ strMatch, match.length + (strMatch as string).length + 2 ] // skip last ";
}
function expectEscapedString (str) {
const reStrLength = /^S:(\d+):"/g // also match the opening " char
const [ match, strLenMatch ] = reStrLength.exec(str) || []
if (!match) {
throw SyntaxError('Expected an escaped string value')
}
const len = parseInt(strLenMatch, 10)
str = str.substring(match.length)
let [ strMatch, bytes, escapedChars ] = readBytes(str, len, true)
if (bytes !== len) {
throw SyntaxError(`Expected escaped string of ${len} bytes, but got ${bytes}`)
}
str = str.substring((strMatch as string).length + (escapedChars as number) * 2)
// strict parsing, match closing "; chars
if (!str.startsWith('";')) {
throw SyntaxError('Expected ";')
}
return [ strMatch, match.length + (strMatch as string).length + 2 ] // skip last ";
}
function expectKeyOrIndex (str) {
try {
return expectString(str)
} catch (err) {}
try {
return expectEscapedString(str)
} catch (err) {}
try {
return expectInt(str)
} catch (err) {
throw SyntaxError('Expected key or index')
}
}
function expectObject (str, cache) {
// O:<class name length>:"class name":<prop count>:{<props and values>}
// O:8:"stdClass":2:{s:3:"foo";s:3:"bar";s:3:"bar";s:3:"baz";}
const reObjectLiteral = /^O:(\d+):"([^"]+)":(\d+):\{/
const [ objectLiteralBeginMatch, /* classNameLengthMatch */, className, propCountMatch ] = reObjectLiteral.exec(str) || []
if (!objectLiteralBeginMatch) {
throw SyntaxError('Invalid input')
}
if (className !== 'stdClass') {
throw SyntaxError(`Unsupported object type: ${className}`)
}
let totalOffset = objectLiteralBeginMatch.length
const propCount = parseInt(propCountMatch, 10)
const obj = {}
cache([obj])
str = str.substring(totalOffset)
for (let i = 0; i < propCount; i++) {
const prop = expectKeyOrIndex(str)
str = str.substring(prop[1])
totalOffset += prop[1] as number
const value = expectType(str, cache)
str = str.substring(value[1])
totalOffset += value[1]
obj[prop[0]] = value[0]
}
// strict parsing, expect } after object literal
if (str.charAt(0) !== '}') {
throw SyntaxError('Expected }')
}
return [ obj, totalOffset + 1 ] // skip final }
}
function expectClass (str, cache) {
// can't be well supported, because requires calling eval (or similar)
// in order to call serialized constructor name
// which is unsafe
// or assume that constructor is defined in global scope
// but this is too much limiting
throw Error('Not yet implemented')
}
function expectReference (str, cache) {
const reRef = /^[rR]:([1-9]\d*);/
const [ match, refIndex ] = reRef.exec(str) || []
if (!match) {
throw SyntaxError('Expected reference value')
}
return [ cache.get(parseInt(refIndex, 10) - 1), match.length ]
}
function expectArray (str, cache) {
const reArrayLength = /^a:(\d+):{/
const [ arrayLiteralBeginMatch, arrayLengthMatch ] = reArrayLength.exec(str) || []
if (!arrayLengthMatch) {
throw SyntaxError('Expected array length annotation')
}
str = str.substring(arrayLiteralBeginMatch.length)
const array = expectArrayItems(str, parseInt(arrayLengthMatch, 10), cache)
// strict parsing, expect closing } brace after array literal
if (str.charAt(array[1]) !== '}') {
throw SyntaxError('Expected }')
}
return [ array[0], arrayLiteralBeginMatch.length + (array[1] as number) + 1 ] // jump over }
}
function expectArrayItems (str, expectedItems = 0, cache) {
let key
let hasStringKeys = false
let item
let totalOffset = 0
let items: any[] = []
cache([items])
for (let i = 0; i < expectedItems; i++) {
key = expectKeyOrIndex(str)
// this is for backward compatibility with previous implementation
if (!hasStringKeys) {
hasStringKeys = (typeof key[0] === 'string')
}
str = str.substring(key[1])
totalOffset += key[1]
// references are resolved immediately, so if duplicate key overwrites previous array index
// the old value is anyway resolved
// fixme: but next time the same reference should point to the new value
item = expectType(str, cache)
str = str.substring(item[1])
totalOffset += item[1]
items[key[0]] = item[0]
}
// this is for backward compatibility with previous implementation
if (hasStringKeys) {
items = Object.assign({}, items)
}
return [ items, totalOffset ]
}
function unserialize (str) {
// discuss at: https://locutus.io/php/unserialize/
// original by: Arpad Ray (mailto:arpad@php.net)
// improved by: Pedro Tainha (https://www.pedrotainha.com)
// improved by: Kevin van Zonneveld (https://kvz.io)
// improved by: Kevin van Zonneveld (https://kvz.io)
// improved by: Chris
// improved by: James
// improved by: Le Torbi
// improved by: Eli Skeggs
// bugfixed by: dptr1988
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: philippsimon (https://github.com/philippsimon/)
// revised by: d3x
// input by: Brett Zamir (https://brett-zamir.me)
// input by: Martin (https://www.erlenwiese.de/)
// input by: kilops
// input by: Jaroslaw Czarniak
// input by: lovasoa (https://github.com/lovasoa/)
// improved by: Rafał Kukawski
// reimplemented by: Rafał Kukawski
// note 1: We feel the main purpose of this function should be
// note 1: to ease the transport of data between php & js
// note 1: Aiming for PHP-compatibility, we have to translate objects to arrays
// example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}')
// returns 1: ['Kevin', 'van', 'Zonneveld']
// example 2: unserialize('a:2:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";}')
// returns 2: {firstName: 'Kevin', midName: 'van'}
// example 3: unserialize('a:3:{s:2:"ü";s:2:"ü";s:3:"四";s:3:"四";s:4:"𠜎";s:4:"𠜎";}')
// returns 3: {'ü': 'ü', '四': '四', '𠜎': '𠜎'}
// example 4: unserialize(undefined)
// returns 4: false
// example 5: unserialize('O:8:"stdClass":1:{s:3:"foo";b:1;}')
// returns 5: { foo: true }
// example 6: unserialize('a:2:{i:0;N;i:1;s:0:"";}')
// returns 6: [null, ""]
// example 7: unserialize('S:7:"\\65\\73\\63\\61\\70\\65\\64";')
// returns 7: 'escaped'
try {
if (typeof str !== 'string') {
return false
}
return expectType(str, initCache())[0]
} catch (err) {
console.error(err)
return false
}
}
function substr_replace (str, replace, start, length) {
// discuss at: https://locutus.io/php/substr_replace/
// original by: Brett Zamir (https://brett-zamir.me)
// example 1: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0)
// returns 1: 'bob'
// example 2: var $var = 'ABCDEFGH:/MNRPQR/'
// example 2: substr_replace($var, 'bob', 0, $var.length)
// returns 2: 'bob'
// example 3: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0, 0)
// returns 3: 'bobABCDEFGH:/MNRPQR/'
// example 4: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 10, -1)
// returns 4: 'ABCDEFGH:/bob/'
// example 5: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', -7, -1)
// returns 5: 'ABCDEFGH:/bob/'
// example 6: substr_replace('ABCDEFGH:/MNRPQR/', '', 10, -1)
// returns 6: 'ABCDEFGH://'
if (start < 0) {
// start position in str
start = start + str.length
}
length = length !== undefined ? length : str.length
if (length < 0) {
length = length + str.length - start
}
return [
str.slice(0, start),
replace.substring(0, length),
replace.slice(length),
str.slice(start + length)
].join('')
}
export class Locutus {
static unserialize<T = unknown>(data: string): T {
return unserialize(data);
}
static substrReplace(str: string, replace: string, start: number, length?: number): string {
return substr_replace(str, replace, start, length);
}
}; | the_stack |
import {
SPDestinationNode,
SPNode,
NodePlaybackDescription
} from '../nodes/SPNodeFactory';
import { TimeInstant } from '../time';
import { Mutation, MutationNames, CommandsMutation } from '../Mutations';
import { ContentCache } from '../ContentCache';
import { Score } from 'nf-grapher';
import { DirectedScore } from '../DirectedScore';
import { RendererInfo, XAudioBufferFromInfo } from './RendererInfo';
import { XAudioBuffer } from '../XAudioBuffer';
import { applyFadeIn, applyFadeOut, mixdown } from '../AudioBufferUtils';
import { debug as Debug } from 'debug';
const DBG_STR = 'nf:base-renderer';
const dbg = Debug(DBG_STR);
// Enqueuing a Score means adding a new Destination Node to the renderer.
type QueuedEffect<T> = {
reject: (err: Error) => void;
resolve: (value?: any) => void;
effect: T;
};
export const enum PlayingState {
STOPPED,
STARTING,
PLAYING,
STOPPING
}
export class BaseRenderer {
// Minimum is 0 for ScriptProcessorNode!
static DEFAULT_QUANTUM_SIZE = 8192;
protected samplesElapsed: number = 0;
protected contentCache: ContentCache = new ContentCache();
protected effects: Array<QueuedEffect<Mutation>> = [];
protected enqueuedScores: Array<{
destination: SPDestinationNode;
rolloff: boolean;
}> = [];
protected dequeuedScores: Array<{
id: string;
rolloff: boolean;
}> = [];
protected dnodes: SPDestinationNode[] = [];
protected playingState = PlayingState.STOPPED;
constructor(
public readonly info: RendererInfo,
protected readonly autoRolloff: boolean = true
) {}
// TODO: does this need a destroy method?
// destroy () {
// if (this.processor) {
// this.processor.disconnect(this.ctx.destination);
// this.processor.onaudioprocess = null;
// this.processor = undefined;
// }
// }
/**
* It is only "safe" to call this method if no audio is being rendered.
*/
async unsafelyReplaceContentCache(nextCache: ContentCache) {
if (this.playingState !== PlayingState.STOPPED) {
throw new Error('Cannot replace ContentCache while rendering.');
}
this.contentCache = nextCache;
}
protected renderQuantum(): XAudioBuffer | undefined {
if (!this.playing) return;
this.processEffects();
const finalDequeuedBuffers = this.processDequeuedScores();
const buffers: XAudioBuffer[] = [];
const output = XAudioBufferFromInfo(this.info, this.info.quantumSize);
const renderTime = TimeInstant.fromSamples(
this.samplesElapsed,
this.info.sampleRate
);
for (let i = 0; i < this.dnodes.length; i++) {
const destination = this.dnodes[i];
destination.feed(renderTime, buffers, this.info.quantumSize);
}
const firstEnqueuedBuffers = this.processEnqueuedScores();
if (finalDequeuedBuffers) buffers.push(...finalDequeuedBuffers);
if (firstEnqueuedBuffers) buffers.push(...firstEnqueuedBuffers);
mixdown(output, buffers);
if (this.playingState === PlayingState.STARTING) {
if (this.autoRolloff) {
applyFadeIn(output);
}
this.playingState = PlayingState.PLAYING;
}
if (this.playingState === PlayingState.STOPPING) {
if (this.autoRolloff) {
applyFadeOut(output);
}
this.playingState = PlayingState.STOPPED;
}
// Even if we stopped this step, we still got this far and therefore still
// rendered some samples.
this.samplesElapsed += this.info.quantumSize;
return output;
}
async enqueueScore(score: Score, rolloff = this.autoRolloff): Promise<void> {
dbg('loading newly enqueued score with id %s', score.graph.id);
// TODO: need to check if graph id is unique and throw if Not!
const dscore = new DirectedScore(score);
const node = new SPDestinationNode(this.info, dscore);
await node.timeChange(
this.renderedTime(),
this.contentCache,
this.info.quantumSize
);
await this.contentCache.scoreContentLoaded(dscore.graphId());
// We don't want a double rolloff to be performed if we just started
// playing and enqueued this score immediately.
const ee = { destination: node, rolloff: this.playing ? rolloff : false };
this.enqueuedScores.push(ee);
dbg('enqueued score with id %s', score.graph.id);
// Immediately process since the audio is irrelevant.
if (!this.playing) {
dbg('immediately processing enqueued scores');
this.processEnqueuedScores();
}
}
async dequeueScore(
graphId: string,
rolloff = this.autoRolloff
): Promise<void> {
const ee = { id: graphId, rolloff: this.playing ? rolloff : false };
this.dequeuedScores.push(ee);
dbg('dequeued score with id %s', graphId);
// Immediately process since the render loop won't handle it.
if (!this.playing) {
dbg('immediately processing dequeued scores');
this.processDequeuedScores();
}
}
protected processEnqueuedScores(): XAudioBuffer[] | undefined {
if (!this.enqueuedScores.length) return;
let buffers: XAudioBuffer[] = [];
let renderTime = TimeInstant.fromSamples(
this.samplesElapsed,
this.info.sampleRate
);
while (this.enqueuedScores.length > 0) {
const ee = this.enqueuedScores.shift();
if (!ee) continue;
if (ee.rolloff) {
ee.destination.feed(renderTime, buffers, this.info.quantumSize);
for (let i = 0; i < buffers.length; i++) {
applyFadeIn(buffers[i]);
}
}
this.dnodes.push(ee.destination);
dbg('promoted enqueued score with id %s', ee.destination.graphId());
}
return buffers;
}
// TODO: this should do some sort of lifecycle, recursively. Nothing really uses
// the lifecycles today, and it would be nice to avoid them all together...
protected processDequeuedScores(): XAudioBuffer[] | undefined {
if (!this.dequeuedScores.length) return;
let buffers: XAudioBuffer[] = [];
let renderTime = TimeInstant.fromSamples(
this.samplesElapsed,
this.info.sampleRate
);
while (this.dequeuedScores.length > 0) {
const ee = this.dequeuedScores.shift();
if (!ee) continue;
const graphId = ee.id;
const idx = this.dnodes.findIndex(node => node.graphId() === graphId);
if (idx === -1) continue;
const nodes = this.dnodes.splice(idx, 1);
if (!nodes.length) continue;
const node = nodes[0];
if (ee.rolloff) {
node.feed(renderTime, buffers, this.info.quantumSize);
for (let i = 0; i < buffers.length; i++) {
applyFadeOut(buffers[i]);
}
}
// This is async, but we fire and forget it because processDequeuedScores
// has to be sync and speedy as part of the render loop.
node.unmountAncestors();
dbg('removed dequeued score with id %s', graphId);
}
return buffers;
}
// TODO: lifecycle!?!?!
dequeueScores() {
dbg('dequeuing all scores');
return Promise.all(
this.dnodes.map(dnode => this.dequeueScore(dnode.graphId()))
);
}
getScore(graphId: string) {
const node = this.dnodes.find(node => node.graphId() === graphId);
if (!node) return;
return node.dscore;
}
getScores() {
return this.dnodes.map(node => node.dscore);
}
renderedTime() {
return TimeInstant.fromSamples(this.samplesElapsed, this.info.sampleRate);
}
public getPlaybackDescription(
renderTime: TimeInstant
): NodePlaybackDescription[] {
const all: NodePlaybackDescription[] = [];
this.dnodes.forEach(node => {
const descs: NodePlaybackDescription[] = [];
node.getPlaybackDescription(renderTime, descs);
// Remove the destination node, it shouldn't be exposed.
descs.shift();
all.push.apply(all, descs);
});
return all;
}
async timeChange(renderTime: TimeInstant) {
this.samplesElapsed = renderTime.asSamples(this.info.sampleRate);
dbg('timeChange to %d samples requested', this.samplesElapsed);
const tasks = [];
for (let i = 0; i < this.dnodes.length; i++) {
const node = this.dnodes[i];
const tc = node.timeChange(
renderTime,
this.contentCache,
this.info.quantumSize
);
const cc = this.contentCache.scoreContentLoaded(node.graphId());
// We want both node processing and content loading to happen as quickly
// as possible.
tasks.push(tc, cc);
}
await Promise.all(tasks);
dbg('timeChange to %d samples completed', this.samplesElapsed);
}
async enqueueEffect(effect: Mutation) {
const p = new Promise((resolve, reject) => {
const ee = {
resolve,
reject,
effect
};
this.effects.push(ee);
});
if (!this.playing) {
this.processEffects();
}
await p;
}
protected ancestorsWithId(nodeId: string) {
const results: SPNode[] = [];
this.dnodes.forEach(node => {
results.push(...node.ancestorsWithId(nodeId));
});
return results;
}
protected commandsEffectTargets(payload: CommandsMutation) {
const { graphId, nodeId } = payload;
const candidates: SPDestinationNode[] = [];
const enqueued = this.enqueuedScores.find(
es => es.destination.graphId() === graphId
);
const running = this.dnodes.find(node => node.graphId() === graphId);
if (enqueued) candidates.push(enqueued.destination);
if (running) candidates.push(running);
// If graph id is not specified, attempt to apply the mutation to all.
if (!graphId) {
if (this.enqueuedScores.length) {
candidates.push(...this.enqueuedScores.map(es => es.destination));
}
if (this.dnodes.length) {
candidates.push(...this.dnodes);
}
}
if (candidates.length === 0) {
throw new Error(`Graph not found for id ${graphId}`);
}
const targets = [];
for (let i = 0; i < candidates.length; i++) {
const candidate = candidates[i];
targets.push(...candidate.ancestorsWithId(nodeId));
}
return targets;
}
protected processEffects() {
while (this.effects.length > 0) {
const ee = this.effects.shift();
if (!ee) continue;
this.processEffect(ee);
}
}
protected processEffect(ee: QueuedEffect<Mutation>) {
const effect = ee.effect;
try {
switch (effect.name) {
case MutationNames.PushCommands:
case MutationNames.ClearCommands: {
// Type appropriately due to lack of string-enum-to-type-mappings.
const commandEffect = effect as CommandsMutation;
const targets = this.commandsEffectTargets(commandEffect);
dbg('effect %o found targets %o', commandEffect, targets);
targets.map(target => target.acceptCommandsEffect(commandEffect));
ee.resolve();
break;
}
default: {
// The value of the switch condition must be used here for the
// exhaustive check to work.
const exhaustive: never = effect.name;
console.warn(`Unknown Effect: ${effect.name}`);
ee.reject(new Error('Unknown Effect!'));
}
}
} catch (err) {
ee.reject(err);
}
}
get playing() {
return this.playingState !== PlayingState.STOPPED;
}
set playing(state: boolean) {
const prev = this.playingState;
if (prev === PlayingState.PLAYING && state === false) {
this.playingState = PlayingState.STOPPING;
} else if (prev === PlayingState.STOPPED && state === true) {
this.playingState = PlayingState.STARTING;
} else if (prev === PlayingState.STARTING && state === false) {
this.playingState = PlayingState.STOPPED;
} else if (prev === PlayingState.STOPPING && state === true) {
this.playingState = PlayingState.STARTING;
}
}
} | the_stack |
/**
* @license Copyright © 2013 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview A jQueryUI plugin that can manage the detail panel for an aircraft.
*/
namespace VRS
{
/*
* Global options
*/
export var globalOptions: GlobalOptions = VRS.globalOptions || {};
VRS.globalOptions.detailPanelDefaultShowUnits = VRS.globalOptions.detailPanelDefaultShowUnits !== undefined ? VRS.globalOptions.detailPanelDefaultShowUnits : true; // True if the aircraft details panel should default to showing distance / speed / height units.
if(VRS.globalOptions.isMobile) {
VRS.globalOptions.detailPanelDefaultItems = VRS.globalOptions.detailPanelDefaultItems || [ // The default set of items to display on the detail panel.
VRS.RenderProperty.Altitude,
VRS.RenderProperty.VerticalSpeed,
VRS.RenderProperty.Speed,
VRS.RenderProperty.Heading,
VRS.RenderProperty.Distance,
VRS.RenderProperty.Squawk,
VRS.RenderProperty.Engines,
VRS.RenderProperty.Species,
VRS.RenderProperty.Wtc,
VRS.RenderProperty.RouteFull,
VRS.RenderProperty.PictureOrThumbnails,
VRS.RenderProperty.PositionOnMap
];
} else {
VRS.globalOptions.detailPanelDefaultItems = VRS.globalOptions.detailPanelDefaultItems || [ // The default set of items to display on the detail panel.
VRS.RenderProperty.Altitude,
VRS.RenderProperty.VerticalSpeed,
VRS.RenderProperty.Speed,
VRS.RenderProperty.Heading,
VRS.RenderProperty.Distance,
VRS.RenderProperty.Squawk,
VRS.RenderProperty.Engines,
VRS.RenderProperty.Species,
VRS.RenderProperty.Wtc,
VRS.RenderProperty.RouteFull,
VRS.RenderProperty.PictureOrThumbnails
];
}
VRS.globalOptions.detailPanelUserCanConfigureItems = VRS.globalOptions.detailPanelUserCanConfigureItems !== undefined ? VRS.globalOptions.detailPanelUserCanConfigureItems : true; // True if the user can change the items shown for an aircraft in the details panel.
VRS.globalOptions.detailPanelShowSeparateRouteLink = VRS.globalOptions.detailPanelShowSeparateRouteLink !== undefined ? VRS.globalOptions.detailPanelShowSeparateRouteLink : true; // Show a separate link to add or correct routes if the detail panel is showing routes.
VRS.globalOptions.detailPanelShowAircraftLinks = VRS.globalOptions.detailPanelShowAircraftLinks !== undefined ? VRS.globalOptions.detailPanelShowAircraftLinks : true; // True to show the links for an aircraft, false to suppress them.
VRS.globalOptions.detailPanelShowEnableAutoSelect = VRS.globalOptions.detailPanelShowEnableAutoSelect !== undefined ? VRS.globalOptions.detailPanelShowEnableAutoSelect : true; // True to show a link to enable and disable auto-select, false to suppress the link.
VRS.globalOptions.detailPanelShowCentreOnAircraft = VRS.globalOptions.detailPanelShowCentreOnAircraft !== undefined ? VRS.globalOptions.detailPanelShowCentreOnAircraft : true; // True to show a link to centre the map on the selected aircraft.
VRS.globalOptions.detailPanelFlagUncertainCallsigns = VRS.globalOptions.detailPanelFlagUncertainCallsigns !== undefined ? VRS.globalOptions.detailPanelFlagUncertainCallsigns : true; // True if uncertain callsigns are to be flagged up on the detail panel.
VRS.globalOptions.detailPanelDistinguishOnGround = VRS.globalOptions.detailPanelDistinguishOnGround !== undefined ? VRS.globalOptions.detailPanelDistinguishOnGround : true; // True if altitudes should show 'GND' when the aircraft is on the ground.
VRS.globalOptions.detailPanelAirportDataThumbnails = VRS.globalOptions.detailPanelAirportDataThumbnails || 2; // The number of thumbnails to fetch from www.airport-data.com.
VRS.globalOptions.detailPanelUseShortLabels = VRS.globalOptions.detailPanelUseShortLabels !== undefined ? VRS.globalOptions.detailPanelUseShortLabels : false; // Use list labels instead of full labels.
/**
* The options that AircraftDetailPlugin honours.
*/
export interface AircraftDetailPlugin_Options
{
/**
* The name to use when saving and loading state.
*/
name?: string;
/**
* The VRS.AircraftList to display aircraft details from.
*/
aircraftList?: AircraftList;
/**
* The VRS.UnitDisplayPreferences that dictates how values are to be displayed.
*/
unitDisplayPreferences: UnitDisplayPreferences;
/**
* The VRS.AircraftAutoSelect that, if supplied, can be configured via controls in the detail panel.
*/
aircraftAutoSelect?: AircraftAutoSelect;
/**
* The map to centre when the 'Centre selected aircraft on map' link is clicked. If it isn't supplied then the option isn't shown.
*/
mapPlugin?: IMap;
/**
* True if the state last saved by the user against name should be loaded and applied immediately when creating the control.
*/
useSavedState?: boolean;
/**
* True if heights, distances and speeds should indicate their units.
*/
showUnits?: boolean;
/**
* The items to show to the user aside from those that are always shown in the detail header.
*/
items?: RenderPropertyEnum[];
/**
* True if a separate link to add or correct links is to be shown if the user is displaying routes. Always hidden if there are no routes on display.
*/
showSeparateRouteLink?: boolean;
/**
* True if uncertain callsigns are to show be flagged up as such on display.
*/
flagUncertainCallsigns?: boolean;
/**
* True if aircraft on the ground should be shown with altitudes of 'GND'.
*/
distinguishOnGround?: boolean;
/**
* The map to pass to property renderers that display mirrored maps.
*/
mirrorMapJQ?: JQuery;
/**
* The plotter options to pass to property renderers that employ aircraft plotters.
*/
plotterOptions?: AircraftPlotterOptions;
/**
* The number of thumbnails to fetch from www.airport-data.com.
*/
airportDataThumbnails?: number;
/**
* True to show short labels, null or false to show long labels.
*/
useShortLabels?: boolean;
}
/**
* Carries the state for the VRS.AircraftDetail plugin.
*/
class AircraftDetailPlugin_State
{
/**
* Indicates whether the detail panel responds to updates or not.
*/
suspended = false;
/**
* A jQuery element for the container for the panel when an aircraft is selected.
*/
container: JQuery = undefined;
/**
* A jQuery element for the container for the panel when no aircraft is selected.
*/
noAircraftContainer: JQuery = undefined;
/**
* A jQuery element for the header's container.
*/
headerContainer: JQuery = undefined;
/**
* A jQuery element for the body's container.
*/
bodyContainer: JQuery = undefined;
/**
* A jQuery element for the links.
*/
linksContainer: JQuery = undefined;
/**
* A direct reference to the plugin for standard aircraft links.
*/
aircraftLinksPlugin: AircraftLinksPlugin = null;
/**
* A direct reference to the plugin for links to the routes submission site.
*/
routeLinksPlugin: AircraftLinksPlugin = null;
/**
* A direct reference to the plugin for links that are shown when no aircraft is selected.
*/
noAircraftLinksPlugin: AircraftLinksPlugin = null;
/**
* An instance of a link render helper that can manage a link to enable and disable auto-select.
*/
autoSelectLinkRenderHelper: AutoSelectLinkRenderHelper = null;
/**
* An instance of a link render helper that can centre the map on the selected aircraft.
*/
centreOnSelectedAircraftLinkRenderHandler: CentreOnSelectedAircraftLinkRenderHandler = null;
/**
* The hook result for the VRS.AircraftList.updated event.
*/
aircraftListUpdatedHook: IEventHandle = undefined;
/**
* The hook result for the VRS.AircraftList.selectedAircraftChanged event.
*/
selectedAircraftChangedHook: IEventHandle = undefined;
/**
* The hook result for the VRS.Localise.localeChanged event.
*/
localeChangedHook: IEventHandle = undefined;
/**
* The hook result for the VRS.UnitDisplayPreferences.unitChanged event.
*/
unitChangedHook: IEventHandle = undefined;
/**
* An array of VRS.AircraftDetailProperty objects that have been rendered into the detail panel's header.
*/
headerProperties: AircraftDetailProperty[] = [];
/**
* An array of VRS.AircraftDetailProperty objects that have been rendered into the detail panel's body.
*/
bodyProperties: AircraftDetailProperty[] = [];
/**
* The aircraft last rendered.
*/
aircraftLastRendered: Aircraft = undefined;
}
/**
* Describes a property that has been rendered into the aircraft detail panel.
*/
class AircraftDetailProperty
{
handler: RenderPropertyHandler;
contentElement: JQuery;
constructor(property: RenderPropertyEnum, isHeader: boolean, public element: JQuery, options: AircraftRenderOptions)
{
if(!property) throw 'You must supply a RenderProperty';
var handler = VRS.renderPropertyHandlers[property];
if(!handler) throw 'The render property ' + property + ' has no handler declared for it';
if(!handler.isSurfaceSupported(isHeader ? VRS.RenderSurface.DetailHead : VRS.RenderSurface.DetailBody)) throw 'The render property ' + property + ' does not support rendering on detail ' + (isHeader ? 'headers' : 'bodies');
if(!element) throw 'You must supply a jQuery element';
this.handler = handler;
this.contentElement = isHeader ? element : element.children().first();
handler.createWidgetInJQuery(this.contentElement, isHeader ? VRS.RenderSurface.DetailHead : VRS.RenderSurface.DetailBody, options);
}
}
/**
* The settings saved by AircraftDetailPlugin objects.
*/
export interface AircraftDetailPlugin_SaveState
{
showUnits: boolean;
items: RenderPropertyEnum[];
useShortLabels: boolean;
}
/*
* jQueryUIHelper methods
*/
export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {};
VRS.jQueryUIHelper.getAircraftDetailPlugin = function(jQueryElement: JQuery) : AircraftDetailPlugin
{
return <AircraftDetailPlugin>jQueryElement.data('vrsVrsAircraftDetail');
}
VRS.jQueryUIHelper.getAircraftDetailOptions = function(overrides?: AircraftDetailPlugin_Options) : AircraftDetailPlugin_Options
{
return $.extend(<AircraftDetailPlugin_Options>{
name: 'default',
useSavedState: true,
showUnits: VRS.globalOptions.detailPanelDefaultShowUnits,
items: VRS.globalOptions.detailPanelDefaultItems.slice(),
showSeparateRouteLink: VRS.globalOptions.detailPanelShowSeparateRouteLink,
flagUncertainCallsigns: VRS.globalOptions.detailPanelFlagUncertainCallsigns,
distinguishOnGround: VRS.globalOptions.detailPanelDistinguishOnGround,
airportDataThumbnails: VRS.globalOptions.detailPanelAirportDataThumbnails,
useShortLabels: VRS.globalOptions.detailPanelUseShortLabels,
unitDisplayPreferences: undefined
}, overrides);
}
/**
* A plugin that can show the user some details about the currently selected aircraft.
*/
export class AircraftDetailPlugin extends JQueryUICustomWidget implements ISelfPersist<AircraftDetailPlugin_SaveState>
{
options: AircraftDetailPlugin_Options;
constructor()
{
super();
this.options = VRS.jQueryUIHelper.getAircraftDetailOptions();
}
private _getState() : AircraftDetailPlugin_State
{
var result = this.element.data('aircraftDetailPluginState');
if(result === undefined) {
result = new AircraftDetailPlugin_State();
this.element.data('aircraftDetailPluginState', result);
}
return result;
}
_create()
{
var options = this.options;
if(!options.aircraftList) throw 'An aircraft list must be supplied';
if(!options.unitDisplayPreferences) throw 'A unit display preferences object must be supplied';
if(options.useSavedState) {
this.loadAndApplyState();
}
var state = this._getState();
state.container =
$('<div/>')
.addClass('vrsAircraftDetail aircraft')
.appendTo(this.element);
state.headerContainer =
$('<div/>')
.addClass('header')
.appendTo(state.container);
state.bodyContainer =
$('<div/>')
.addClass('body')
.appendTo(state.container);
state.linksContainer =
$('<div/>')
.addClass('links')
.appendTo(state.container);
state.noAircraftContainer =
$('<div/>')
.addClass('vrsAircraftDetail noAircraft')
.appendTo(this.element);
this._buildContent(state);
state.aircraftListUpdatedHook = options.aircraftList.hookUpdated(this._aircraftListUpdated, this);
state.selectedAircraftChangedHook = options.aircraftList.hookSelectedAircraftChanged(this._selectedAircraftChanged, this);
state.localeChangedHook = VRS.globalisation.hookLocaleChanged(this._localeChanged, this);
state.unitChangedHook = options.unitDisplayPreferences.hookUnitChanged(this._displayUnitChanged, this);
this._renderContent(state, options.aircraftList.getSelectedAircraft(), true);
}
_destroy()
{
var state = this._getState();
var options = this.options;
state.headerProperties = this._destroyProperties(VRS.RenderSurface.DetailHead, state.headerProperties);
state.bodyProperties = this._destroyProperties(VRS.RenderSurface.DetailBody, state.bodyProperties);
if(state.container) {
this.element.empty();
state.container = undefined;
}
if(state.aircraftLinksPlugin) {
state.aircraftLinksPlugin.destroy();
state.aircraftLinksPlugin = null;
}
if(state.routeLinksPlugin) {
state.routeLinksPlugin.destroy();
state.routeLinksPlugin = null;
}
if(state.autoSelectLinkRenderHelper) {
state.autoSelectLinkRenderHelper.dispose();
state.autoSelectLinkRenderHelper = null;
}
if(state.aircraftListUpdatedHook) {
if(options && options.aircraftList) options.aircraftList.unhook(state.aircraftListUpdatedHook);
state.aircraftListUpdatedHook = undefined;
}
if(state.selectedAircraftChangedHook) {
if(options && options.aircraftList) options.aircraftList.unhook(state.selectedAircraftChangedHook);
state.selectedAircraftChangedHook = undefined;
}
if(state.localeChangedHook) {
if(VRS.globalisation) VRS.globalisation.unhook(state.localeChangedHook);
state.localeChangedHook = undefined;
}
if(state.unitChangedHook) {
if(options && options.unitDisplayPreferences) options.unitDisplayPreferences.unhook(state.unitChangedHook);
state.unitChangedHook = undefined;
}
}
/**
* Destroys the elements and releases any resources held by a collection of properties.
*/
private _destroyProperties(surface: RenderSurfaceBitFlags, properties: AircraftDetailProperty[])
{
var length = properties.length;
for(var i = 0;i < length;++i) {
var property = properties[i];
if(property.element) {
property.handler.destroyWidgetInJQuery(property.contentElement, surface);
property.element.remove();
}
}
return [];
}
/**
* Suspends or resumes updates.
*/
suspend(onOff: boolean)
{
onOff = !!onOff;
var state = this._getState();
if(state.suspended !== onOff) {
state.suspended = onOff;
this._suspendWidgets(state, onOff);
if(!state.suspended) {
var selectedAircraft = this.options.aircraftList.getSelectedAircraft();
this._renderContent(state, selectedAircraft, true);
}
}
}
/**
* Suspends or resumes widgets that have been used to render items.
*/
private _suspendWidgets(state: AircraftDetailPlugin_State, onOff: boolean)
{
this._suspendWidgetProperties(state, onOff, state.headerProperties, VRS.RenderSurface.DetailHead);
this._suspendWidgetProperties(state, onOff, state.bodyProperties, VRS.RenderSurface.DetailBody);
}
/**
* Suspends or resumes widgets used to render an array of properties.
*/
private _suspendWidgetProperties(state: AircraftDetailPlugin_State, onOff: boolean, properties: AircraftDetailProperty[], surface: RenderSurfaceBitFlags)
{
var length = properties.length;
for(var i = 0;i < length;++i) {
var property = properties[i];
property.handler.suspendWidget(property.contentElement, surface, onOff);
}
}
/**
* Saves the current state.
*/
saveState()
{
VRS.configStorage.save(this._persistenceKey(), this._createSettings());
}
/**
* Returns the saved state or, if there is no saved state, the current state.
*/
loadState() : AircraftDetailPlugin_SaveState
{
var savedSettings = VRS.configStorage.load(this._persistenceKey(), {});
var result = $.extend(this._createSettings(), savedSettings);
result.items = VRS.renderPropertyHelper.buildValidRenderPropertiesList(result.items, [ VRS.RenderSurface.DetailBody ]);
return result;
}
/**
* Applies the saved state to the object.
*/
applyState(settings: AircraftDetailPlugin_SaveState)
{
this.options.showUnits = settings.showUnits;
this.options.items = settings.items;
this.options.useShortLabels = !!settings.useShortLabels;
}
/**
* Loads and then applies the saved state.
*/
loadAndApplyState()
{
this.applyState(this.loadState());
}
/**
* Returns the key against which the state is saved.
*/
private _persistenceKey() : string
{
return 'vrsAircraftDetailPlugin-' + this.options.name;
}
/**
* Returns the current state.
*/
private _createSettings() : AircraftDetailPlugin_SaveState
{
return {
showUnits: this.options.showUnits,
items: this.options.items,
useShortLabels: this.options.useShortLabels
};
}
/**
* Returns the option panes that can be used to configure the panel.
*/
createOptionPane(displayOrder: number) : OptionPane[]
{
var result: OptionPane[] = [];
var state = this._getState();
var options = this.options;
var settingsPane = new VRS.OptionPane({
name: 'vrsAircraftDetailPlugin_' + options.name + '_Settings',
titleKey: 'PaneDetailSettings',
displayOrder: displayOrder,
fields: [
new VRS.OptionFieldCheckBox({
name: 'showUnits',
labelKey: 'ShowUnits',
getValue: () => options.showUnits,
setValue: (value) => {
options.showUnits = value;
this._buildContent(this._getState());
this._reRenderAircraft(this._getState())
},
saveState: () => this.saveState()
}),
new VRS.OptionFieldCheckBox({
name: 'useShortLabels',
labelKey: 'UseShortLabels',
getValue: () => options.useShortLabels,
setValue: (value) => {
options.useShortLabels = value;
this._buildContent(this._getState());
this._reRenderAircraft(this._getState());
},
saveState: () => this.saveState()
})
]
});
result.push(settingsPane);
if(VRS.globalOptions.detailPanelUserCanConfigureItems) {
VRS.renderPropertyHelper.addRenderPropertiesListOptionsToPane({
pane: settingsPane,
fieldLabel: 'DetailItems',
surface: VRS.RenderSurface.DetailBody,
getList: () => options.items,
setList: (items) => {
options.items = items;
this._buildBody(state);
this._reRenderAircraft(state);
},
saveState: () => this.saveState()
});
}
return result;
}
/**
* Fills both the header and body with content.
*/
private _buildContent(state: AircraftDetailPlugin_State)
{
this._buildHeader(state);
this._buildBody(state);
this._buildLinks(state);
}
/**
* Empties the header and then prepares it with elements to render into.
*/
private _buildHeader(state: AircraftDetailPlugin_State)
{
var options = this.options;
state.headerProperties = this._destroyProperties(VRS.RenderSurface.DetailHead, state.headerProperties);
state.headerContainer.empty();
var table = $('<table/>')
.appendTo(state.headerContainer),
row1 = $('<tr/>')
.appendTo(table),
regElement = $('<td/>')
.addClass('reg')
.appendTo(row1),
icaoElement = $('<td/>')
.addClass('icao')
.appendTo(row1),
bearingElement = $('<td/>')
.addClass('bearing')
.appendTo(row1),
opFlagElement = $('<td/>')
.addClass('flag')
.appendTo(row1),
row2 = $('<tr/>')
.appendTo(table),
operatorElement = $('<td/>')
.addClass('op')
.attr('colspan', '3')
.appendTo(row2),
callsignElement = $('<td/>')
.addClass('callsign')
.appendTo(row2),
row3 = $('<tr/>')
.appendTo(table),
countryElement = $('<td/>')
.addClass('country')
.attr('colspan', '3')
.appendTo(row3),
militaryElement = $('<td/>')
.addClass('military')
.appendTo(row3),
row4 = $('<tr/>')
.appendTo(table),
modelElement = $('<td/>')
.addClass('model')
.attr('colspan', '3')
.appendTo(row4),
modelTypeElement = $('<td/>')
.addClass('modelType')
.appendTo(row4);
state.headerProperties = [
new AircraftDetailProperty(VRS.RenderProperty.Registration, true, regElement, options),
new AircraftDetailProperty(VRS.RenderProperty.Icao, true, icaoElement, options),
new AircraftDetailProperty(VRS.RenderProperty.Bearing, true, bearingElement, options),
new AircraftDetailProperty(VRS.RenderProperty.OperatorFlag, true, opFlagElement, options),
new AircraftDetailProperty(VRS.RenderProperty.Operator, true, operatorElement, options),
new AircraftDetailProperty(VRS.RenderProperty.Callsign, true, callsignElement, options),
new AircraftDetailProperty(VRS.RenderProperty.Country, true, countryElement, options),
new AircraftDetailProperty(VRS.RenderProperty.CivOrMil, true, militaryElement, options),
new AircraftDetailProperty(VRS.RenderProperty.Model, true, modelElement, options),
new AircraftDetailProperty(VRS.RenderProperty.ModelIcao, true, modelTypeElement, options)
];
}
/**
* Empties the body and then prepares it with elements to render into.
*/
private _buildBody(state: AircraftDetailPlugin_State)
{
state.bodyProperties = this._destroyProperties(VRS.RenderSurface.DetailBody, state.bodyProperties);
state.bodyContainer.empty();
var options = this.options;
var list =
$('<ul/>')
.appendTo(state.bodyContainer);
state.bodyProperties = [];
var countProperties = options.items.length;
for(var i = 0;i < countProperties;++i) {
var property = options.items[i];
var handler = VRS.renderPropertyHandlers[property];
var suppressLabel = handler.suppressLabelCallback(VRS.RenderSurface.DetailBody);
var listItem =
$('<li/>')
.appendTo(list);
if(!suppressLabel) {
$('<div/>')
.addClass('label')
.append($('<span/>')
.text(VRS.globalisation.getText(options.useShortLabels ? handler.headingKey : handler.labelKey) + ':')
)
.appendTo(listItem);
}
var content =
$('<div/>')
.addClass('content')
.append($('<span/>'))
.appendTo(listItem);
if(suppressLabel) {
listItem.addClass('wide');
content.addClass('wide');
}
if(handler.isMultiLine) {
listItem.addClass('multiline');
content.addClass('multiline');
}
state.bodyProperties.push(new AircraftDetailProperty(property, false, content, options));
}
}
/**
* Adds the UI for the aircraft links.
*/
private _buildLinks(state: AircraftDetailPlugin_State)
{
var options = this.options;
if(state.aircraftLinksPlugin) {
state.aircraftLinksPlugin.destroy();
}
if(state.noAircraftLinksPlugin) {
state.noAircraftLinksPlugin.destroy();
}
state.linksContainer.empty();
state.noAircraftContainer.empty();
var aircraftLinksElement = $('<div/>')
.appendTo(state.linksContainer)
.vrsAircraftLinks();
state.aircraftLinksPlugin = VRS.jQueryUIHelper.getAircraftLinksPlugin(aircraftLinksElement);
var routeLinks: (LinkSiteEnum | LinkRenderHandler)[] = [];
if(options.mapPlugin && options.aircraftList && VRS.globalOptions.detailPanelShowCentreOnAircraft) {
state.centreOnSelectedAircraftLinkRenderHandler = new VRS.CentreOnSelectedAircraftLinkRenderHandler(options.aircraftList, options.mapPlugin);
routeLinks.push(state.centreOnSelectedAircraftLinkRenderHandler);
}
if(options.aircraftAutoSelect && VRS.globalOptions.detailPanelShowEnableAutoSelect) {
state.autoSelectLinkRenderHelper = new VRS.AutoSelectLinkRenderHelper(options.aircraftAutoSelect);
routeLinks.push(state.autoSelectLinkRenderHelper);
}
if(VRS.globalOptions.detailPanelShowSeparateRouteLink) {
routeLinks.push(VRS.LinkSite.StandingDataMaintenance);
}
if(routeLinks.length > 0) {
var routeLinksElement = $('<div/>')
.appendTo(state.linksContainer)
.vrsAircraftLinks({
linkSites: routeLinks
});
state.routeLinksPlugin = VRS.jQueryUIHelper.getAircraftLinksPlugin(routeLinksElement);
if(state.autoSelectLinkRenderHelper) state.autoSelectLinkRenderHelper.addLinksRendererPlugin(state.routeLinksPlugin);
}
if(options.aircraftAutoSelect && VRS.globalOptions.detailPanelShowEnableAutoSelect) {
var noAircraftLinksElement = $('<div/>')
.appendTo(state.noAircraftContainer)
.vrsAircraftLinks({
linkSites: [ state.autoSelectLinkRenderHelper ]
});
state.noAircraftLinksPlugin = VRS.jQueryUIHelper.getAircraftLinksPlugin(noAircraftLinksElement);
state.autoSelectLinkRenderHelper.addLinksRendererPlugin(state.noAircraftLinksPlugin);
}
}
/**
* Updates the header and body with any values on the aircraft that have changed. If displayUnit is provided then only properties that
* depend on the unit are refreshed.
*/
private _renderContent(state: AircraftDetailPlugin_State, aircraft: Aircraft, refreshAll: boolean, displayUnit?: DisplayUnitDependencyEnum)
{
state.aircraftLastRendered = aircraft;
if(!aircraft) {
$(state.container, ':visible').hide();
$(state.noAircraftContainer, ':hidden').show();
this._renderLinks(state, null, refreshAll);
} else {
$(state.container, ':hidden').show();
$(state.noAircraftContainer, ':visible').hide();
this._renderProperties(state, aircraft, refreshAll, state.headerProperties, VRS.RenderSurface.DetailHead, displayUnit);
this._renderProperties(state, aircraft, refreshAll, state.bodyProperties, VRS.RenderSurface.DetailBody, displayUnit);
this._renderLinks(state, aircraft, refreshAll);
}
}
/**
* Renders the values into a set of existing elements on a surface. If displayUnit is provided then only properties that
* depend on the unit are refreshed.
*/
private _renderProperties(state: AircraftDetailPlugin_State, aircraft: Aircraft, refreshAll: boolean, properties: AircraftDetailProperty[], surface: RenderSurfaceBitFlags, displayUnit?: DisplayUnitDependencyEnum)
{
var options = this.options;
var countProperties = properties.length;
var refreshedContent = false;
for(var i = 0;i < countProperties;++i) {
var property = properties[i];
var handler = property.handler;
var element = property.contentElement;
var forceRefresh = refreshAll;
if(!forceRefresh) forceRefresh = displayUnit && handler.usesDisplayUnit(displayUnit);
if(forceRefresh || handler.hasChangedCallback(aircraft)) {
handler.renderToJQuery(element, surface, aircraft, options);
refreshedContent = true;
}
if(forceRefresh || handler.tooltipChangedCallback(aircraft)) {
handler.renderTooltipToJQuery(element, surface, aircraft, options);
}
}
}
/**
* Renders the links for the aircraft.
*/
private _renderLinks(state: AircraftDetailPlugin_State, aircraft: Aircraft, refreshAll: boolean)
{
if(aircraft === null) {
if(state.noAircraftLinksPlugin) {
state.noAircraftLinksPlugin.renderForAircraft(null, refreshAll);
}
} else {
if(VRS.globalOptions.detailPanelShowAircraftLinks) {
state.aircraftLinksPlugin.renderForAircraft(aircraft, refreshAll);
}
if(state.routeLinksPlugin) {
state.routeLinksPlugin.renderForAircraft(aircraft, refreshAll);
}
}
}
/**
* Forces the drawing of every item in both the header and body.
*/
private _reRenderAircraft(state: AircraftDetailPlugin_State)
{
this._renderContent(state, state.aircraftLastRendered, true);
}
/**
* Called when the aircraft list has been updated.
*/
private _aircraftListUpdated()
{
var state = this._getState();
if(!state.suspended) {
var options = this.options;
var selectedAircraft = options.aircraftList.getSelectedAircraft();
if(selectedAircraft) this._renderContent(state, selectedAircraft, false);
}
}
/**
* Called when the user changes the display units.
*/
private _displayUnitChanged(displayUnit: DisplayUnitDependencyEnum)
{
var state = this._getState();
if(!state.suspended) {
var selectedAircraft = this.options.aircraftList.getSelectedAircraft();
if(selectedAircraft) this._renderContent(state, selectedAircraft, false, displayUnit);
}
}
/**
* Called when the selected aircraft has changed.
*/
private _selectedAircraftChanged()
{
var state = this._getState();
if(!state.suspended) {
var selectedAircraft = this.options.aircraftList.getSelectedAircraft();
this._renderContent(state, selectedAircraft, true);
}
}
/**
* Called when the language has changed.
*/
private _localeChanged()
{
var state = this._getState();
this._buildContent(state);
if(!state.suspended) this._reRenderAircraft(state);
}
}
$.widget('vrs.vrsAircraftDetail', new AircraftDetailPlugin());
}
declare interface JQuery
{
vrsAircraftDetail();
vrsAircraftDetail(options: VRS.AircraftDetailPlugin_Options);
vrsAircraftDetail(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any);
} | the_stack |
import { Injectable, Inject } from "@angular/core";
import { RegistrationUser } from "../../../app/components/auth/register/registration.component";
import { environment } from "../../../environments/environment";
/**
* Created by Vladimir Budilov
*/
declare var AWSCognito: any;
declare var AWS: any;
export interface CognitoCallback {
cognitoCallback(message: string, result: any): void;
}
export interface LoggedInCallback {
isLoggedIn(message: string, loggedIn: boolean): void;
}
export interface Callback {
callback(): void;
callbackWithParam(result: any): void;
}
@Injectable()
export class CognitoUtil {
public static _REGION = environment.region;
public static _IDENTITY_POOL_ID = environment.identityPoolId;
public static _USER_POOL_ID = environment.userPoolId;
public static _CLIENT_ID = environment.clientId;
public static _POOL_DATA = {
UserPoolId: CognitoUtil._USER_POOL_ID,
ClientId: CognitoUtil._CLIENT_ID
};
public static getAwsCognito(): any {
return AWSCognito
}
getUserPool() {
return new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(CognitoUtil._POOL_DATA);
}
getCurrentUser() {
return this.getUserPool().getCurrentUser();
}
getCognitoIdentity(): string {
return AWS.config.credentials.identityId;
}
getAccessToken(): Promise<any> {
return new Promise((resolve, reject) => {
if (this.getCurrentUser() != null)
this.getCurrentUser().getSession(function (err, session) {
if (err) {
console.log("CognitoUtil: Can't set the credentials:" + err);
reject(err);
}
else {
if (session.isValid()) {
resolve(session.getAccessToken().getJwtToken());
} else {
reject({ message: "CognitoUtil: Got the id token, but the session isn't valid" });
}
}
});
else
reject({ message: "No current user." });
});
}
getIdToken(): Promise<any> {
return new Promise((resolve, reject) => {
if (this.getCurrentUser() != null)
this.getCurrentUser().getSession(function (err, session) {
if (err) {
console.log("CognitoUtil: Can't set the credentials:" + err);
reject(err);
}
else {
if (session.isValid()) {
resolve(session.getIdToken().getJwtToken());
} else {
reject({ message: "CognitoUtil: Got the id token, but the session isn't valid" });
}
}
});
else
reject({ message: "No current user." });
});
}
getRefreshToken(callback: Callback): void {
if (callback == null) {
throw ("CognitoUtil: callback in getRefreshToken is null...returning");
}
if (this.getCurrentUser() != null)
this.getCurrentUser().getSession(function (err, session) {
if (err) {
console.log("CognitoUtil: Can't set the credentials:" + err);
callback.callbackWithParam(null);
}
else {
if (session.isValid()) {
callback.callbackWithParam(session.getRefreshToken());
}
}
});
else
callback.callbackWithParam(null);
}
refresh(): void {
this.getCurrentUser().getSession(function (err, session) {
if (err) {
console.log("CognitoUtil: Can't set the credentials:" + err);
}
else {
if (session.isValid()) {
console.log("CognitoUtil: refreshed successfully");
} else {
console.log("CognitoUtil: refreshed but session is still not valid");
}
}
});
}
}
@Injectable()
export class UserRegistrationService {
constructor( @Inject(CognitoUtil) public cognitoUtil: CognitoUtil) {
}
register(user: RegistrationUser, callback: CognitoCallback): void {
console.log("UserRegistrationService: user is " + user);
let attributeList = [];
let dataEmail = {
Name: 'email',
Value: user.email
};
let dataNickname = {
Name: 'nickname',
Value: user.name
};
attributeList.push(new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail));
attributeList.push(new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataNickname));
this.cognitoUtil.getUserPool().signUp(user.email, user.password, attributeList, null, function (err, result) {
if (err) {
callback.cognitoCallback(err.message, null);
} else {
console.log("UserRegistrationService: registered user is " + result);
callback.cognitoCallback(null, result);
}
});
}
confirmRegistration(username: string, confirmationCode: string, callback: CognitoCallback): void {
let userData = {
Username: username,
Pool: this.cognitoUtil.getUserPool()
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.confirmRegistration(confirmationCode, true, function (err, result) {
if (err) {
callback.cognitoCallback(err.message, null);
} else {
callback.cognitoCallback(null, result);
}
});
}
resendCode(username: string, callback: CognitoCallback): void {
let userData = {
Username: username,
Pool: this.cognitoUtil.getUserPool()
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.resendConfirmationCode(function (err, result) {
if (err) {
callback.cognitoCallback(err.message, null);
} else {
callback.cognitoCallback(null, result);
}
});
}
}
@Injectable()
export class UserLoginService {
constructor(public cognitoUtil: CognitoUtil) {
}
authenticate(username: string, password: string, callback: CognitoCallback) {
console.log("UserLoginService: starting the authentication")
// Need to provide placeholder keys unless unauthorised user access is enabled for user pool
AWSCognito.config.update({ accessKeyId: 'anything', secretAccessKey: 'anything' })
let authenticationData = {
Username: username,
Password: password,
};
let authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
let userData = {
Username: username,
Pool: this.cognitoUtil.getUserPool()
};
console.log("UserLoginService: Params set...Authenticating the user");
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
console.log("UserLoginService: config is " + AWS.config);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var logins = {}
logins['cognito-idp.' + CognitoUtil._REGION + '.amazonaws.com/' + CognitoUtil._USER_POOL_ID] = result.getIdToken().getJwtToken();
// Add the User's Id Token to the Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: CognitoUtil._IDENTITY_POOL_ID,
Logins: logins
});
console.log("UserLoginService: set the AWS credentials - " + JSON.stringify(AWS.config.credentials));
console.log("UserLoginService: set the AWSCognito credentials - " + JSON.stringify(AWSCognito.config.credentials));
callback.cognitoCallback(null, result);
},
onFailure: function (err) {
callback.cognitoCallback(err.message, null);
},
});
}
forgotPassword(username: string, callback: CognitoCallback) {
let userData = {
Username: username,
Pool: this.cognitoUtil.getUserPool()
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.forgotPassword({
onSuccess: function (result) {
},
onFailure: function (err) {
callback.cognitoCallback(err.message, null);
},
inputVerificationCode() {
callback.cognitoCallback(null, null);
}
});
}
confirmNewPassword(email: string, verificationCode: string, password: string, callback: CognitoCallback) {
let userData = {
Username: email,
Pool: this.cognitoUtil.getUserPool()
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.confirmPassword(verificationCode, password, {
onSuccess: function (result) {
callback.cognitoCallback(null, result);
},
onFailure: function (err) {
callback.cognitoCallback(err.message, null);
}
});
}
logout() {
console.log("UserLoginService: Logging out");
this.cognitoUtil.getCurrentUser().signOut();
}
isAuthenticated(callback: LoggedInCallback) {
if (callback == null)
throw ("UserLoginService: Callback in isAuthenticated() cannot be null");
let cognitoUser = this.cognitoUtil.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function (err, session) {
if (err) {
console.log("UserLoginService: Couldn't get the session: " + err, err.stack);
callback.isLoggedIn(err, false);
}
else {
console.log("UserLoginService: Session is " + session.isValid());
callback.isLoggedIn(err, session.isValid());
}
});
} else {
console.log("UserLoginService: can't retrieve the current user");
callback.isLoggedIn("Can't retrieve the CurrentUser", false);
}
}
}
@Injectable()
export class UserParametersService {
constructor(public cognitoUtil: CognitoUtil) {
}
getParameters(callback: Callback) {
let cognitoUser = this.cognitoUtil.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function (err, session) {
if (err)
console.log("UserParametersService: Couldn't retrieve the user");
else {
cognitoUser.getUserAttributes(function (err, result) {
if (err) {
console.log("UserParametersService: in getParameters: " + err);
} else {
callback.callbackWithParam(result);
}
});
}
});
} else {
callback.callbackWithParam(null);
}
}
} | the_stack |
import { DID, SchemaManager } from 'identity_ts';
import { v4 as uuid } from 'uuid';
import zmq from 'zeromq';
import { maxDistance, operations, security } from '../config.json';
import { processReceivedCredentialForUser, VERIFICATION_LEVEL } from '../utils/credentialHelper';
import { readData, writeData } from '../utils/databaseHelper';
import { convertOperationsList, extractMessageType } from '../utils/eclassHelper';
import { decryptWithReceiversPrivateKey } from '../utils/encryptionHelper';
import { getPayload } from '../utils/iotaHelper';
import { calculateDistance, getLocationFromMessage } from '../utils/locationHelper';
import { publish } from '../utils/mamHelper';
import { processPayment } from '../utils/walletHelper';
/**
* Class to handle ZMQ service.
*/
export class ZmqService {
/**
* Bundle hashes that were already send to not send twice
*
*/
public sentBundles = [];
/**
* The interval to frequently delete sentBundle array.
*/
public _bundleInterval;
/**
* The interval to frequently delete sentBundle array.
*/
public _paymentInterval;
/**
* The configuration for the service.
*/
private readonly _config;
/**
* The connected socket.
*/
private _socket;
/**
* The callback for different events.
*/
private readonly _subscriptions;
/**
*
*/
private listenAddress: string | undefined;
/**
* Create a new instance of ZmqService.
* @param config The gateway for the zmq service.
*/
constructor(config) {
this._config = config;
this._subscriptions = {};
this._bundleInterval = setInterval(this.emptyBundleArray.bind(this), 10000);
this._paymentInterval = setInterval(this.processPayments.bind(this), 5 * 60 * 1000);
this.listenAddress = null;
// Add trusted identities (Initially, the DID of the IOTA Foundation)
const schema = SchemaManager.GetInstance().GetSchema('WhiteListedCredential');
for (let i = 0; i < this._config.trustedIdentities.length; i++) {
schema.AddTrustedDID(new DID(this._config.trustedIdentities[i]));
}
}
/**
* Clear sentBundles array
*/
public emptyBundleArray() {
this.sentBundles = [];
}
public processPayments() {
processPayment();
}
public setAddressToListenTo(address: string | undefined) {
this.listenAddress = address;
console.log('Set listen address: ', address);
}
/**
* Subscribe to named event.
* @param event The event to subscribe to.
* @param callback The callback to call with data for the event.
* @returns An id to use for unsubscribe.
*/
public subscribe(event, callback) {
return this.internalAddEventCallback(event, callback);
}
/**
* Subscribe to a specific event.
* @param event The event to subscribe to.
* @param callback The callback to call with data for the event.
* @returns An id to use for unsubscribe.
*/
public subscribeEvent(event, callback) {
return this.internalAddEventCallback(event, callback);
}
/**
* Unsubscribe from an event.
* @param subscriptionId The id to unsubscribe.
*/
public unsubscribe(subscriptionId) {
const keys = Object.keys(this._subscriptions);
for (let i = 0; i < keys.length; i++) {
const eventKey = keys[i];
for (let j = 0; j < this._subscriptions[eventKey].length; j++) {
if (this._subscriptions[eventKey][j].id === subscriptionId) {
this._subscriptions[eventKey].splice(j, 1);
if (this._subscriptions[eventKey].length === 0) {
this._socket.unsubscribe(eventKey);
delete this._subscriptions[eventKey];
if (Object.keys(this._subscriptions).length === 0) {
this.disconnect();
}
}
return;
}
}
}
}
/**
* Connect the ZMQ service.
*/
private connect() {
try {
if (!this._socket) {
this._socket = zmq.socket('sub');
this._socket.connect(this._config.endpoint);
this._socket.on('message', (msg) => this.handleMessage(msg));
const keys = Object.keys(this._subscriptions);
for (let i = 0; i < keys.length; i++) {
this._socket.subscribe(keys[i]);
}
}
} catch (err) {
throw new Error(`Unable to connect to ZMQ.\n${err}`);
}
}
/**
* Disconnect the ZQM service.
*/
private disconnect() {
if (this._socket) {
this._socket.close();
this._socket = undefined;
}
}
/**
* Add a callback for the event.
* @param event The event to add the callback for.
* @param callback The callback to store for the event.
* @returns The id of the subscription.
*/
private internalAddEventCallback(event, callback) {
if (!this._subscriptions[event]) {
this._subscriptions[event] = [];
if (this._socket) {
this._socket.subscribe(event);
}
}
const id = uuid();
this._subscriptions[event].push({ id, callback });
this.connect();
return id;
}
/**
* Build payload for the socket packet
*/
private buildPayload(data, messageType, messageParams, trustLevel) {
return {
data,
messageType,
tag: messageParams[12],
hash: messageParams[1],
address: messageParams[2],
timestamp: parseInt(messageParams[5], 10),
trustLevel
};
}
/**
* Send out an event
*/
private async sendEvent(data, messageType, messageParams, trustLevel: VERIFICATION_LEVEL = VERIFICATION_LEVEL.DID_TRUSTED) {
const event = messageParams[0];
const payload = this.buildPayload(data, messageType, messageParams, trustLevel);
console.log(`Sending ${messageType}`);
for (let i = 0; i < this._subscriptions[event].length; i++) {
this._subscriptions[event][i].callback(event, payload);
}
}
/**
* Handle a message and send to any callbacks.
* @param message The message to handle.
*/
private async handleMessage(message) {
const messageContent = message.toString();
const messageParams = messageContent.split(' ');
const event = messageParams[0];
const address = messageParams[2];
const tag = messageParams[12];
const operationList = await convertOperationsList(operations);
if (event === 'tx' && this._subscriptions[event]) {
const messageType = extractMessageType(tag);
// tslint:disable-next-line:no-unused-expression
messageType && console.log('handleMessage', messageType, tag);
if (tag.startsWith(this._config.prefix) && messageType && operationList.includes(tag.slice(9, 15))) {
const bundle = messageParams[8];
if (!this.sentBundles.includes(bundle)) {
this.sentBundles.push(bundle);
interface IUser {
id?: string;
name?: string;
role?: string;
location?: string;
address?: string;
}
const { id, role, location }: IUser = await readData('user');
// 1. Check user role (SR, SP, YP)
switch (role) {
case 'SR':
// 2. For SR only react on message types B, E ('proposal' and 'informConfirm')
if (['proposal', 'informConfirm'].includes(messageType)) {
// 2.1 Decode every such message and retrieve receiver ID
const data = await getPayload(bundle);
const receiverID = data.frame.receiver.identification.id;
// 2.2 Compare receiver ID with user ID. Only if match, send message to UI
if (id === receiverID) {
await this.sendEvent(data, messageType, messageParams);
if (messageType !== 'proposal') {
const channelId = data.frame.conversationId;
await publish(channelId, data);
}
}
}
break;
case 'SP':
// 3. For SP only react on message types A, C, D, F ('callForProposal', 'acceptProposal', 'rejectProposal', and 'informPayment')
if (['callForProposal', 'acceptProposal', 'rejectProposal', 'informPayment'].includes(messageType)) {
const data = await getPayload(bundle);
console.log('handleMessage 3', data);
// 3.1 Decode every message of type A, retrieve location.
if (messageType === 'callForProposal') {
const senderLocation = await getLocationFromMessage(data);
if (!location || !maxDistance) {
await this.sendEvent(data, messageType, messageParams);
}
// 3.3 If own location and accepted range are set, calculate distance between own location and location of the request.
if (location && maxDistance) {
try {
const distance = await calculateDistance(location, senderLocation);
// 3.3.1 If distance within accepted range, send message to UI
if (distance <= maxDistance) {
await this.sendEvent(data, messageType, messageParams);
}
} catch (error) {
console.error(error);
}
}
} else {
// 3.4 Decode every message of type C, D, F and retrieve receiver ID
const receiverID = data.frame.receiver.identification.id;
// 3.5 Compare receiver ID with user ID. Only if match, send message to UI
if (id === receiverID) {
if (messageType === 'acceptProposal') {
const channelId = data.frame.conversationId;
// Check if the correct challenge is used and if the signatures are correct
const secretKey = await decryptWithReceiversPrivateKey(data.mam);
await writeData('mam', {
id: channelId,
root: data.mam.root,
seed: '',
nextRoot: '',
sideKey: secretKey,
start: 0,
mode: '',
security,
count: 1,
nextCount: 1,
index: 0
});
}
await this.sendEvent(data, messageType, messageParams);
}
}
}
break;
default:
// 4. For YP only react on message types A, B, C ('callForProposal', 'proposal' and 'acceptProposal')
if (['callForProposal', 'proposal', 'acceptProposal'].includes(messageType)) {
const data = await getPayload(bundle);
// 4.1 Send every such message to UI
this.sendEvent(data, messageType, messageParams);
}
}
}
} else if (this.listenAddress && address === this.listenAddress) {
const bundle = messageParams[8];
if (!this.sentBundles.includes(bundle)) {
this.sentBundles.push(bundle);
// A message has been received through the ServiceEndpoint of the DID
const unstructuredData = await getPayload(bundle);
processReceivedCredentialForUser(unstructuredData);
}
}
}
}
} | the_stack |
import React from "react";
import {BrowserRouter as Router} from "react-router-dom";
import {fireEvent, render, wait, waitForElement} from "@testing-library/react";
import CustomCard from "./custom-card";
import axiosMock from "axios";
import data from "../../../assets/mock-data/curation/flows.data";
import {act} from "react-dom/test-utils";
import {AuthoritiesService, AuthoritiesContext} from "../../../util/authorities";
import mocks from "../../../api/__mocks__/mocks.data";
import {CustomStepTooltips} from "../../../config/tooltips.config";
jest.mock("axios");
const mockHistoryPush = jest.fn();
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
describe("Custom Card component", () => {
beforeEach(() => {
mocks.curateAPI(axiosMock);
});
afterEach(() => {
jest.clearAllMocks();
});
test("Custom card does not allow edit without writeCustom", async () => {
let customData = data.customSteps.data.stepsWithEntity[0].artifacts;
let getByRole, queryAllByRole, getByText, getByTestId;
await act(async () => {
const renderResults = render(
<Router><CustomCard data={customData} canReadOnly={true} canReadWrite={false} entityModel={{entityTypeId: "Customer"}}/></Router>
);
getByRole = renderResults.getByRole;
queryAllByRole = renderResults.queryAllByRole;
getByText=renderResults.getByText;
getByTestId=renderResults.getByTestId;
});
expect(getByRole("edit-custom")).toBeInTheDocument();
expect(queryAllByRole("delete-custom")).toHaveLength(0);
let tipIconView = getByTestId("customJSON-edit");
fireEvent.mouseOver(tipIconView);
await waitForElement(() => getByText(CustomStepTooltips.viewCustom));
});
test("Can add step to flow", async () => {
const authorityService = new AuthoritiesService();
authorityService.setAuthorities(["readCustom"]);
let customData = data.customSteps.data.stepsWithEntity[0].artifacts;
let flows = data.flows.data;
const {getByText, getByLabelText, getByTestId} = render(
<Router><AuthoritiesContext.Provider value={authorityService}>
<CustomCard
data={customData}
flows={flows}
canReadOnly={true}
canReadWrite={false}
canWriteFlow={true}
entityModel={{entityTypeId: "Customer"}}
addStepToFlow={() => {}}
getArtifactProps={() => { return customData[0]; }}
/>
</AuthoritiesContext.Provider></Router>);
expect(getByText("customJSON")).toBeInTheDocument();
// hover over card to see options
fireEvent.mouseOver(getByText("customJSON"));
expect(getByTestId("customJSON-toNewFlow")).toBeInTheDocument(); // 'Add to a new Flow'
expect(getByTestId("customJSON-toExistingFlow")).toBeInTheDocument(); // 'Add to an existing Flow'
// Open menu, choose flow
fireEvent.click(getByTestId("customJSON-flowsList"));
fireEvent.click(getByLabelText("testFlow-option"));
// Dialog appears, click 'Yes' button
expect(getByLabelText("step-not-in-flow")).toBeInTheDocument();
fireEvent.click(getByTestId("customJSON-to-testFlow-Confirm"));
// Check if the /tiles/run/add route has been called
wait(() => { expect(mockHistoryPush).toHaveBeenCalledWith("/tiles/run/add"); });
});
test("Open settings in read-only mode", async () => {
const authorityService = new AuthoritiesService();
authorityService.setAuthorities(["readCustom"]);
let customData = data.customSteps.data.stepsWithEntity[0].artifacts;
const {getByText, queryByText, getByLabelText, getByPlaceholderText, getByTestId} = render(
<Router><AuthoritiesContext.Provider value={authorityService}>
<CustomCard
data={customData}
canReadOnly={true}
canReadWrite={false}
entityModel={{entityTypeId: "Customer"}}
getArtifactProps={() => { return customData[0]; }}
/>
</AuthoritiesContext.Provider></Router>);
await wait(() => {
fireEvent.click(getByTestId("customJSON-edit"));
});
expect(getByText("Custom Step Settings")).toBeInTheDocument();
expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).not.toHaveClass("ant-tabs-tab-active");
// Basic settings values
expect(getByPlaceholderText("Enter name")).toHaveValue("customJSON");
expect(getByPlaceholderText("Enter name")).toBeDisabled();
expect(getByPlaceholderText("Enter description")).toBeDisabled();
expect(getByLabelText("Collection")).toBeInTheDocument();
expect(getByLabelText("Query")).toBeChecked();
expect(getByPlaceholderText("Enter source query")).toHaveTextContent("cts.collectionQuery(['loadCustomerJSON'])");
// Switch to Advanced settings
await wait(() => {
fireEvent.click(getByText("Advanced"));
});
expect(getByText("Basic").closest("div")).not.toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-active");
// Advanced settings values
expect(getByText("Source Database")).toBeInTheDocument();
expect(getByText("db1")).toBeInTheDocument();
expect(getByText("Target Database")).toBeInTheDocument();
expect(getByText("db2")).toBeInTheDocument();
expect(getByText("Batch Size")).toBeInTheDocument();
expect(getByPlaceholderText("Please enter batch size")).toHaveValue("50");
expect(getByPlaceholderText("Please enter batch size")).toBeDisabled();
expect(getByText("Target Collections")).toBeInTheDocument();
expect(getByText("Default Collections")).toBeInTheDocument();
expect(getByTestId("defaultCollections-Customer")).toBeInTheDocument();
expect(getByTestId("defaultCollections-mapCustomerJSON")).toBeInTheDocument();
expect(getByText("Target Permissions")).toBeInTheDocument();
expect(getByPlaceholderText("Please enter target permissions")).toHaveValue("role1,read,role2,update");
expect(getByPlaceholderText("Please enter target permissions")).toBeDisabled();
expect(getByText("Provenance Granularity")).toBeInTheDocument();
expect(getByText("Interceptors")).toBeInTheDocument();
expect(getByText("Custom Hook")).toBeInTheDocument();
expect(getByText("Additional Settings")).toBeInTheDocument();
fireEvent.click(getByLabelText("Close"));
await wait(() => {
expect(queryByText("Custom Step Settings")).not.toBeInTheDocument();
});
});
test("Open settings in read-write mode", async () => {
const authorityService = new AuthoritiesService();
authorityService.setAuthorities(["readCustom", "writeCustom"]);
let customData = data.customSteps.data.stepsWithEntity[0].artifacts;
const {getByText, queryByText, getByLabelText, getByPlaceholderText, getByTestId} = render(
<Router><AuthoritiesContext.Provider value={authorityService}>
<CustomCard
data={customData}
canReadOnly={true}
canReadWrite={true}
entityModel={{entityTypeId: "Customer"}}
getArtifactProps={() => { return customData[0]; }}
/>
</AuthoritiesContext.Provider></Router>);
await wait(() => {
fireEvent.click(getByTestId("customJSON-edit"));
});
expect(getByText("Custom Step Settings")).toBeInTheDocument();
expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).not.toHaveClass("ant-tabs-tab-active");
// Basic settings values
expect(getByPlaceholderText("Enter name")).toHaveValue("customJSON");
expect(getByPlaceholderText("Enter name")).toBeDisabled();
expect(getByPlaceholderText("Enter description")).toBeEnabled();
expect(getByLabelText("Collection")).toBeInTheDocument();
expect(getByLabelText("Query")).toBeChecked();
expect(getByPlaceholderText("Enter source query")).toHaveTextContent("cts.collectionQuery(['loadCustomerJSON'])");
// Switch to Advanced settings
await wait(() => {
fireEvent.click(getByText("Advanced"));
});
expect(getByText("Basic").closest("div")).not.toHaveClass("ant-tabs-tab-active");
expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-active");
// Advanced settings values
expect(getByText("Source Database")).toBeInTheDocument();
expect(getByLabelText("sourceDatabase-select")).toBeEnabled();
expect(getByText("db1")).toBeInTheDocument();
expect(getByText("Target Database")).toBeInTheDocument();
expect(getByText("db2")).toBeInTheDocument();
expect(getByLabelText("targetDatabase-select")).toBeEnabled();
expect(getByText("Batch Size")).toBeInTheDocument();
expect(getByPlaceholderText("Please enter batch size")).toHaveValue("50");
expect(getByPlaceholderText("Please enter batch size")).toBeEnabled();
expect(getByText("Target Collections")).toBeInTheDocument();
expect(getByLabelText("additionalColl-select")).toBeEnabled();
expect(getByText("Default Collections")).toBeInTheDocument();
expect(getByTestId("defaultCollections-Customer")).toBeInTheDocument();
expect(getByTestId("defaultCollections-mapCustomerJSON")).toBeInTheDocument();
expect(getByText("Target Permissions")).toBeInTheDocument();
expect(getByPlaceholderText("Please enter target permissions")).toHaveValue("role1,read,role2,update");
expect(getByPlaceholderText("Please enter target permissions")).toBeEnabled();
expect(getByText("Provenance Granularity")).toBeInTheDocument();
expect(getByLabelText("provGranularity-select")).toBeEnabled();
expect(getByText("Interceptors")).toBeInTheDocument();
expect(getByText("Custom Hook")).toBeInTheDocument();
expect(getByText("Additional Settings")).toBeInTheDocument();
fireEvent.click(getByLabelText("Close"));
await wait(() => {
expect(queryByText("Custom Step Settings")).not.toBeInTheDocument();
});
});
}); | the_stack |
import EthVal from 'ethval'
import Table from 'cli-table'
import colors from 'colors'
import moment from 'moment'
import terminalLink from 'terminal-link'
import { PrefixedHexString } from 'ethereumjs-util'
import * as asciichart from 'asciichart'
import { GSNContractsDeployment } from '@opengsn/common/dist/GSNContractsDeployment'
import { IntString, ObjectMap, SemVerString } from '@opengsn/common/dist/types/Aliases'
import { CommandLineStatisticsPresenterConfig } from './CommandLineStatisticsPresenterConfig'
import {
EventTransactionInfo,
GSNStatistics,
PaymasterInfo,
RelayHubConstructorParams,
RelayHubEvents,
RelayServerInfo,
RelayServerRegistrationInfo,
RelayServerStakeStatus
} from '@opengsn/common/dist/types/GSNStatistics'
import {
RelayRegisteredEventInfo,
TransactionRejectedByPaymasterEventInfo,
TransactionRelayedEventInfo
} from '@opengsn/common/dist/types/GSNContractsDataTypes'
export class CommandLineStatisticsPresenter {
config: CommandLineStatisticsPresenterConfig
constructor (config: CommandLineStatisticsPresenterConfig) {
this.config = config
}
getStatisticsStringPresentation (statistics: GSNStatistics): string {
let message: string = `GSN status for version ${statistics.runtimeVersion} on ChainID ${statistics.chainId} at block height ${statistics.blockNumber}\n\n`
message += this.createContractsDeploymentTable(statistics.contractsDeployment, statistics.deploymentBalances, statistics.deploymentVersions)
message += '\n\nRelay Hub constructor parameters:\n'
message += this.printRelayHubConstructorParams(statistics.relayHubConstructorParams)
message += '\n\nTransactions:\n'
message += this.printTransactionsPlot(statistics.blockNumber, statistics.relayHubEvents)
message += '\n\nActive Relays:\n'
message += this.printActiveServersInfo(statistics.blockNumber, statistics.relayServers)
message += '\n\nNon-active Relays:\n'
message += this.printNonActiveServersInfo(statistics.blockNumber, statistics.relayServers)
message += '\n\nPaymasters:\n'
message += this.printPaymastersInfo(statistics.blockNumber, statistics.paymasters)
return message
}
createContractsDeploymentTable (deployment: GSNContractsDeployment, balances: ObjectMap<IntString>, versions: ObjectMap<SemVerString>): string {
const table = new Table({ head: ['', 'Address', 'Balance', 'Version'] })
table.push({ 'Stake Manager': [this.toBlockExplorerLink(deployment.stakeManagerAddress, true), this.ethValueStr(balances[deployment.stakeManagerAddress ?? '']), versions[deployment.stakeManagerAddress ?? '']] })
table.push({ 'Penalizer ': [this.toBlockExplorerLink(deployment.penalizerAddress, true), this.ethValueStr(balances[deployment.penalizerAddress ?? '']), versions[deployment.penalizerAddress ?? '']] })
table.push({ 'Relay Hub': [this.toBlockExplorerLink(deployment.relayHubAddress, true), this.ethValueStr(balances[deployment.relayHubAddress ?? '']), versions[deployment.relayHubAddress ?? '']] })
return table.toString()
}
toBlockExplorerLink (value: PrefixedHexString = '', isAddress: boolean = true): string {
let truncatedAddress = value.slice(0, this.config.urlTruncateToLength + 2)
if (this.config.urlTruncateToLength < value.length) {
truncatedAddress += '…'
}
if (this.config.blockExplorerUrl == null) {
return truncatedAddress
}
const type = isAddress ? 'address/' : 'tx/'
const url = this.config.blockExplorerUrl + type + value
if (!terminalLink.isSupported) {
return url
}
return terminalLink(truncatedAddress, url)
}
/**
* Converts amount in wei to a human-readable string
* @param value - amount in wei
* @param units - units to convert to; only full 1e18 unit ('eth') will be replaced with ticker symbol
*/
ethValueStr (value: IntString = '0', units: string = 'eth'): string {
const valueStr: string = new EthVal(value).to(units).toFixed(this.config.valuesTruncateToLength)
const unitString = units === 'eth' ? this.config.nativeTokenTickerSymbol : units
return `${valueStr} ${unitString}`
}
printTransactionsPlot (
currentBlock: number,
relayHubEvents: RelayHubEvents): string {
return this.createRecentTransactionsChart(currentBlock, relayHubEvents.transactionRelayedEvents, relayHubEvents.transactionRejectedEvents)
}
printActiveServersInfo (currentBlock: number, relayServerInfos: RelayServerInfo[]): string {
const activeRelays = relayServerInfos.filter(it => it.isRegistered)
if (activeRelays.length === 0) {
return 'no active relays found'
}
const table = new Table({ head: ['Host', 'Ping status', 'Addresses & balances', 'Fee', 'Authorized Hubs', 'Transactions', 'Registration renewals'] })
for (const relayServerInfo of activeRelays) {
if (relayServerInfo.registrationInfo == null) {
throw new Error('registrationInfo not initialized for a registered relay')
}
const host = new URL(relayServerInfo.registrationInfo.lastRegisteredUrl).host
// TODO: process errors into human-readable status
const pingStatus =
relayServerInfo.registrationInfo.pingResult.pingResponse != null
? relayServerInfo.registrationInfo.pingResult.pingResponse.ready.toString().substr(0, 20)
: relayServerInfo.registrationInfo.pingResult.error?.toString().substr(0, 20) ??
'unknown'
const addressesAndBalances = this.createAddressesAndBalancesSubTable(relayServerInfo)
const fee = this.createFeeSubTable(relayServerInfo.registrationInfo)
const authorizedHubs = this.createAuthorizedHubsSubTable(relayServerInfo)
const recentChart = this.createRecentTransactionsChart(currentBlock, relayServerInfo.relayHubEvents.transactionRelayedEvents, relayServerInfo.relayHubEvents.transactionRejectedEvents)
const registrationRenewals = this.createRegistrationRenewalsSubTable(currentBlock, relayServerInfo.relayHubEvents.relayRegisteredEvents)
table.push([host, pingStatus, addressesAndBalances, fee, authorizedHubs, recentChart, registrationRenewals])
}
return table.toString()
}
printNonActiveServersInfo (currentBlock: number, relayServerInfos: RelayServerInfo[]): string {
const nonActiveRelays = relayServerInfos.filter(it => !it.isRegistered)
if (nonActiveRelays.length === 0) {
return 'no non-active relays found'
}
const table = new Table({ head: ['Manager address', 'Status', 'First Seen', 'Last Seen', 'Total Relayed'] })
for (const relay of nonActiveRelays) {
const status = this.stringServerStatus(relay.stakeStatus)
const managerAddressLink = this.toBlockExplorerLink(relay.managerAddress, true)
const firstSeen = 'TODO'
const lastSeen = 'TODO'
const totalTx = relay.relayHubEvents.transactionRelayedEvents.length
table.push([managerAddressLink, status, firstSeen, lastSeen, totalTx])
}
return table.toString()
}
createAddressesAndBalancesSubTable (relayServerInfo: RelayServerInfo): string {
const table = new Table({ head: ['Role', 'Address', 'Balance'] })
table.push(['OWN', this.toBlockExplorerLink(relayServerInfo.stakeInfo.owner, true), this.ethValueStr(relayServerInfo.ownerBalance)])
table.push(['MGR', this.toBlockExplorerLink(relayServerInfo.managerAddress, true), this.ethValueStr(relayServerInfo.managerBalance)])
for (const workerAddress of relayServerInfo.registrationInfo?.registeredWorkers ?? []) {
const workerBalance = this.ethValueStr(relayServerInfo.registrationInfo?.workerBalances[workerAddress])
table.push(['W#1', this.toBlockExplorerLink(workerAddress, true), workerBalance])
}
const table2 = new Table()
const relayHubEarningsBalance = this.ethValueStr(relayServerInfo.relayHubEarningsBalance)
const totalDepositedStake = this.ethValueStr(relayServerInfo.stakeInfo.stake.toString())
table2.push(['RelayHub earnings ', relayHubEarningsBalance])
table2.push(['Deposited Stake', totalDepositedStake])
return table.toString() + '\n' + table2.toString()
}
createFeeSubTable (registrationInfo: RelayServerRegistrationInfo): string {
const table = new Table({ head: ['Base', 'Percent'] })
table.push([this.ethValueStr(registrationInfo.lastRegisteredBaseFee, 'gwei'), `${registrationInfo.lastRegisteredPctFee}%`])
return table.toString()
}
createAuthorizedHubsSubTable (relayServerInfo: RelayServerInfo): string {
const table = new Table({ head: ['Address', 'Version'] })
for (const hub of Object.keys(relayServerInfo.authorizedHubs)) {
table.push([this.toBlockExplorerLink(hub, true), relayServerInfo.authorizedHubs[hub]])
}
return table.toString()
}
createRecentTransactionsChart (
currentBlock: number,
transactionRelayedEvents: Array<EventTransactionInfo<TransactionRelayedEventInfo>>,
transactionRejectedEvents: Array<EventTransactionInfo<TransactionRejectedByPaymasterEventInfo>>
): string {
if (transactionRelayedEvents.length === 0 && transactionRejectedEvents.length === 0) {
return 'no transactions'
}
const config = {
colors: [
asciichart.green,
asciichart.red
],
format: function (x: number) {
return `${x.toString().padStart(3, '0')} `
}
}
// this code is ugly af but does work with negative 'beginning block'
const weekBeginningBlockApprox = currentBlock - this.config.averageBlocksPerDay * this.config.daysToPlotTransactions
const relayedByDay = this.getEventsByDayCount(transactionRelayedEvents, weekBeginningBlockApprox)
const rejectedByDay = this.getEventsByDayCount(transactionRejectedEvents, weekBeginningBlockApprox)
// @ts-ignore
let plot = asciichart.plot([relayedByDay, rejectedByDay], config)
plot += `\n${colors.green('accepted')} ${colors.red('rejected')}`
return plot
}
getEventsByDayCount (transactionRelayedEvents: Array<EventTransactionInfo<TransactionRelayedEventInfo | TransactionRejectedByPaymasterEventInfo>>, weekBeginningBlockApprox: number): number[] {
const eventsByDay: number[] = new Array(this.config.daysToPlotTransactions).fill(0)
for (const event of transactionRelayedEvents) {
if (event.eventData.blockNumber <= weekBeginningBlockApprox) {
continue
}
// If the event is in the CURRENT block, it will 'floor' to 7 while last index is 6
const index = Math.floor((event.eventData.blockNumber - weekBeginningBlockApprox - 1) / this.config.averageBlocksPerDay)
eventsByDay[index]++
}
return eventsByDay
}
stringServerStatus (status: RelayServerStakeStatus): string {
switch (status) {
case RelayServerStakeStatus.STAKE_LOCKED:
return 'stake locked'
case RelayServerStakeStatus.STAKE_WITHDRAWN:
return 'withdrawn'
case RelayServerStakeStatus.STAKE_UNLOCKED:
return 'unlocked'
case RelayServerStakeStatus.STAKE_PENALIZED:
return 'penalized'
}
}
createRegistrationRenewalsSubTable (
currentBlock: number,
relayRegisteredEvents: Array<EventTransactionInfo<RelayRegisteredEventInfo>>): string {
const table = new Table({ head: ['Link', 'Block number', 'Time estimate'] })
for (const event of relayRegisteredEvents) {
const eventBlock = event.eventData.blockNumber
const estimateDays = (currentBlock - eventBlock) / this.config.averageBlocksPerDay
const blockMoment = moment().subtract(estimateDays, 'days')
const link = this.toBlockExplorerLink(event.eventData.transactionHash, false)
table.push([link, eventBlock, blockMoment.fromNow()])
}
return table.toString()
}
printPaymastersInfo (blockNumber: number, paymasters: PaymasterInfo[]): string {
if (paymasters.length === 0) {
return 'no paymasters found'
}
const table = new Table({ head: ['Address', 'Hub balance', 'Transactions accepted', 'Transaction rejected'] })
const paymastersSortedSliced = paymasters.sort((a, b) => b.acceptedTransactionsCount - a.acceptedTransactionsCount)
.slice(0, 10)
for (const paymaster of paymastersSortedSliced) {
const address = this.toBlockExplorerLink(paymaster.address, true)
const balance = this.ethValueStr(paymaster.relayHubBalance)
table.push([address, balance, paymaster.acceptedTransactionsCount, paymaster.rejectedTransactionsCount])
}
let string = table.toString()
if (paymasters.length > 10) {
string += `\n and ${paymasters.length - 10} more...`
}
return string
}
printRelayHubConstructorParams (params: RelayHubConstructorParams): string {
const table = new Table()
table.push(
['Max worker count', params.maxWorkerCount],
['Minimum unstake delay', `${params.minimumUnstakeDelay} blocks`],
['Gas Reserve', params.gasReserve],
['Post Overhead', params.postOverhead],
['Gas Overhead', params.gasOverhead]
)
return table.toString()
}
} | the_stack |
import { CSharpRenderer } from '../CSharpRenderer';
import { CSharpPreset } from '../CSharpPreset';
import { getUniquePropertyName, DefaultPropertyNames, FormatHelpers, TypeHelpers, ModelKind } from '../../../helpers';
import { CommonInputModel, CommonModel } from '../../../models';
function renderSerializeProperty(modelInstanceVariable: string, model: CommonModel, inputModel: CommonInputModel) {
let value = modelInstanceVariable;
if (model.$ref) {
const resolvedModel = inputModel.models[model.$ref];
const propertyModelKind = TypeHelpers.extractKind(resolvedModel);
//Referenced enums is the only one who need custom serialization
if (propertyModelKind === ModelKind.ENUM) {
value = `${value}.GetValue()`;
}
}
return `JsonSerializer.Serialize(writer, ${value});`;
}
function renderSerializeAdditionalProperties(model: CommonModel, renderer: CSharpRenderer, inputModel: CommonInputModel) {
const serializeAdditionalProperties = '';
if (model.additionalProperties !== undefined) {
let additionalPropertyName = getUniquePropertyName(model, DefaultPropertyNames.additionalProperties);
additionalPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(additionalPropertyName, model.additionalProperties));
return `// Unwrap additional properties in object
if (value.AdditionalProperties != null) {
foreach (var additionalProperty in value.${additionalPropertyName})
{
//Ignore any additional properties which might already be part of the core properties
if (properties.Any(prop => prop.Name == additionalProperty.Key))
{
continue;
}
// write property name and let the serializer serialize the value itself
writer.WritePropertyName(additionalProperty.Key);
${renderSerializeProperty('additionalProperty.Value', model.additionalProperties, inputModel)}
}
}`;
}
return serializeAdditionalProperties;
}
function renderSerializeProperties(model: CommonModel, renderer: CSharpRenderer, inputModel: CommonInputModel) {
let serializeProperties = '';
if (model.properties !== undefined) {
for (const [propertyName, propertyModel] of Object.entries(model.properties)) {
const formattedPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(propertyName, propertyModel));
const modelInstanceVariable = `value.${formattedPropertyName}`;
serializeProperties += `if(${modelInstanceVariable} != null) {
// write property name and let the serializer serialize the value itself
writer.WritePropertyName("${propertyName}");
${renderSerializeProperty(modelInstanceVariable, propertyModel, inputModel)}
}\n`;
}
}
return serializeProperties;
}
function renderSerializePatternProperties(model: CommonModel, renderer: CSharpRenderer, inputModel: CommonInputModel) {
let serializePatternProperties = '';
if (model.patternProperties !== undefined) {
for (const [pattern, patternModel] of Object.entries(model.patternProperties)) {
let patternPropertyName = getUniquePropertyName(model, `${pattern}${DefaultPropertyNames.patternProperties}`);
patternPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(patternPropertyName, patternModel));
serializePatternProperties += `// Unwrap pattern properties in object
if(value.${patternPropertyName} != null) {
foreach (var patternProp in value.${patternPropertyName})
{
//Ignore any pattern properties which might already be part of the core properties
if (properties.Any(prop => prop.Name == patternProp.Key))
{
continue;
}
// write property name and let the serializer serialize the value itself
writer.WritePropertyName(patternProp.Key);
${renderSerializeProperty('patternProp.Value', patternModel, inputModel)}
}
}`;
}
}
return serializePatternProperties;
}
function renderPropertiesList(model: CommonModel, renderer: CSharpRenderer) {
const propertyFilter: string[] = [];
if (model.additionalProperties !== undefined) {
let additionalPropertyName = getUniquePropertyName(model, DefaultPropertyNames.additionalProperties);
additionalPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(additionalPropertyName, model.additionalProperties));
propertyFilter.push(`prop.Name != "${additionalPropertyName}"`);
}
for (const [pattern, patternModel] of Object.entries(model.patternProperties || {})) {
let patternPropertyName = getUniquePropertyName(model, `${pattern}${DefaultPropertyNames.patternProperties}`);
patternPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(patternPropertyName, patternModel));
propertyFilter.push(`prop.Name != "${patternPropertyName}"`);
}
let propertiesList = 'var properties = value.GetType().GetProperties();';
if (propertyFilter.length > 0) {
renderer.addDependency('using System.Linq;');
propertiesList = `var properties = value.GetType().GetProperties().Where(prop => ${propertyFilter.join(' && ')});`;
}
return propertiesList;
}
/**
* Render `serialize` function based on model
*/
function renderSerialize({ renderer, model, inputModel }: {
renderer: CSharpRenderer,
model: CommonModel,
inputModel: CommonInputModel
}): string {
const formattedModelName = renderer.nameType(model.$id);
const serializeProperties = renderSerializeProperties(model, renderer, inputModel);
const serializePatternProperties = renderSerializePatternProperties(model, renderer, inputModel);
const serializeAdditionalProperties = renderSerializeAdditionalProperties(model, renderer, inputModel);
const propertiesList = renderPropertiesList(model, renderer);
return `public override void Write(Utf8JsonWriter writer, ${formattedModelName} value, JsonSerializerOptions options)
{
if (value == null)
{
JsonSerializer.Serialize(writer, null);
return;
}
${propertiesList}
writer.WriteStartObject();
${renderer.indent(serializeProperties)}
${renderer.indent(serializePatternProperties)}
${renderer.indent(serializeAdditionalProperties)}
writer.WriteEndObject();
}`;
}
function renderDeserializeProperty(type: string, model: CommonModel, inputModel: CommonInputModel) {
if (model.$ref) {
const resolvedModel = inputModel.models[model.$ref];
const propertyModelKind = TypeHelpers.extractKind(resolvedModel);
//Referenced enums is the only one who need custom serialization
if (propertyModelKind === ModelKind.ENUM) {
return `${type}Extension.To${type}(JsonSerializer.Deserialize<dynamic>(ref reader, options))`;
}
}
return `JsonSerializer.Deserialize<${type}>(ref reader, options)`;
}
function renderDeserializeProperties(model: CommonModel, renderer: CSharpRenderer, inputModel: CommonInputModel) {
const propertyEntries = Object.entries(model.properties || {});
const deserializeProperties = propertyEntries.map(([prop, propModel]) => {
const formattedPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(prop, propModel));
const propertyModelType = renderer.renderType(propModel);
return `if (propertyName == "${prop}")
{
var value = ${renderDeserializeProperty(propertyModelType, propModel, inputModel)};
instance.${formattedPropertyName} = value;
continue;
}`;
});
return deserializeProperties.join('\n');
}
function renderDeserializePatternProperties(model: CommonModel, renderer: CSharpRenderer, inputModel: CommonInputModel) {
if (model.patternProperties === undefined) {
return '';
}
const patternProperties = Object.entries(model.patternProperties).map(([pattern, patternModel]) => {
let patternPropertyName = getUniquePropertyName(model, `${pattern}${DefaultPropertyNames.patternProperties}`);
patternPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(patternPropertyName, patternModel));
const patternPropertyType = renderer.renderType(patternModel);
return `if(instance.${patternPropertyName} == null) { instance.${patternPropertyName} = new Dictionary<string, ${patternPropertyType}>(); }
var match = Regex.Match(propertyName, @"${pattern}");
if (match.Success)
{
var deserializedValue = ${renderDeserializeProperty(patternPropertyType, patternModel, inputModel)};
instance.${patternPropertyName}.Add(propertyName, deserializedValue);
continue;
}`;
});
return patternProperties.join('\n');
}
function renderDeserializeAdditionalProperties(model: CommonModel, renderer: CSharpRenderer, inputModel: CommonInputModel) {
if (model.additionalProperties === undefined) {
return '';
}
let additionalPropertyName = getUniquePropertyName(model, DefaultPropertyNames.additionalProperties);
additionalPropertyName = FormatHelpers.upperFirst(renderer.nameProperty(additionalPropertyName, model.additionalProperties));
const additionalPropertyType = renderer.renderType(model.additionalProperties);
return `if(instance.${additionalPropertyName} == null) { instance.${additionalPropertyName} = new Dictionary<string, ${additionalPropertyType}>(); }
var deserializedValue = ${renderDeserializeProperty(additionalPropertyType, model.additionalProperties, inputModel)};
instance.${additionalPropertyName}.Add(propertyName, deserializedValue);
continue;`;
}
/**
* Render `deserialize` function based on model
*/
function renderDeserialize({ renderer, model, inputModel }: {
renderer: CSharpRenderer,
model: CommonModel,
inputModel: CommonInputModel
}): string {
const formattedModelName = renderer.nameType(model.$id);
const deserializeProperties = renderDeserializeProperties(model, renderer, inputModel);
const deserializePatternProperties = renderDeserializePatternProperties(model, renderer, inputModel);
const deserializeAdditionalProperties = renderDeserializeAdditionalProperties(model, renderer, inputModel);
return `public override ${formattedModelName} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
}
var instance = new ${formattedModelName}();
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return instance;
}
// Get the key.
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}
string propertyName = reader.GetString();
${renderer.indent(deserializeProperties, 4)}
${renderer.indent(deserializePatternProperties, 4)}
${renderer.indent(deserializeAdditionalProperties, 4)}
}
throw new JsonException();
}`;
}
/**
* Preset which adds `serialize` and `deserialize` functions to class.
*
* @implements {CSharpPreset}
*/
export const CSHARP_JSON_SERIALIZER_PRESET: CSharpPreset = {
class: {
self({ renderer, model, content, inputModel}) {
renderer.addDependency('using System.Text.Json;');
renderer.addDependency('using System.Text.Json.Serialization;');
renderer.addDependency('using System.Text.RegularExpressions;');
const formattedModelName = renderer.nameType(model.$id);
const deserialize = renderDeserialize({renderer, model, inputModel});
const serialize = renderSerialize({renderer, model, inputModel});
return `[JsonConverter(typeof(${formattedModelName}Converter))]
${content}
internal class ${formattedModelName}Converter : JsonConverter<${formattedModelName}>
{
public override bool CanConvert(Type objectType)
{
// this converter can be applied to any type
return true;
}
${renderer.indent(deserialize)}
${renderer.indent(serialize)}
}
`;
}
}
}; | the_stack |
import React, { Component } from "react";
import ReactDOM from "react-dom";
import * as d3 from "d3";
import { InfoTooltip } from "./InfoTooltip.tsx"
import { DirectionalHint } from '@fluentui/react';
import { IconButton } from '@fluentui/react/lib/Button';
type PerformanceCompatibilityState = {
data: any,
h1Performance: any,
testing: boolean,
training: boolean,
newError: boolean,
strictImitation: boolean,
selectedDataPoint: any,
transform: any
}
type PerformanceCompatibilityProps = {
data: any,
h1Performance: any,
testing: boolean,
training: boolean,
newError: boolean,
strictImitation: boolean,
selectedDataPoint: any,
lambdaLowerBound: number,
lambdaUpperBound: number,
compatibilityScoreType: string,
performanceMetric: string,
selectDataPoint: (d: any) => void,
getModelEvaluationData: (evaluationId: number) => void
}
class PerformanceCompatibility extends Component<PerformanceCompatibilityProps, PerformanceCompatibilityState> {
constructor(props) {
super(props);
this.state = {
data: props.data,
h1Performance: props.h1Performance,
testing: props.testing,
training: props.training,
newError: props.newError,
strictImitation: props.strictImitation,
selectedDataPoint: props.selectedDataPoint,
transform: d3.zoomIdentity
};
this.node = React.createRef<HTMLDivElement>();
this.zoomIn = () => {}
this.zoomOut = () => {}
this.resetZoom = () => {}
this.createPVCPlot = this.createPVCPlot.bind(this);
}
node: React.RefObject<HTMLDivElement>
zoomIn: Function
zoomOut: Function
resetZoom: Function
lastTransform: any
componentDidMount() {
if (this.props.h1Performance != null) {
this.createPVCPlot();
}
}
componentWillReceiveProps(nextProps) {
this.setState({
data: nextProps.data,
testing: nextProps.testing,
training: nextProps.training,
newError: nextProps.newError,
strictImitation: nextProps.strictImitation,
transform: this.lastTransform
});
}
componentDidUpdate() {
this.createPVCPlot();
}
createPVCPlot() {
var _this = this;
var body = d3.select(this.node.current);
var data = this.state.data;
var margin = { top: 15, right: 15, bottom: 20, left: 55 }
var h = 350 - margin.top - margin.bottom
var w = 425 - margin.left - margin.right
var formatPercentX = d3.format('.3f');
var formatPercentY = d3.format('.2f');
var colorMap = {
"training": "rgba(118, 197, 255, 0.30)",
"testing": "rgba(245, 81, 179, 0.30)"
};
var allDataPoints = [];
if (_this.state.training && _this.state.newError) {
allDataPoints = allDataPoints.concat(data.filter(d => (d["training"] && d["new-error"])));
}
if (_this.state.training && _this.state.strictImitation) {
allDataPoints = allDataPoints.concat(data.filter(d => (d["training"] && d["strict-imitation"])));
}
if (_this.state.testing && _this.state.newError) {
allDataPoints = allDataPoints.concat(data.filter(d => (d["testing"] && d["new-error"])));
}
if (_this.state.testing && _this.state.strictImitation) {
allDataPoints = allDataPoints.concat(data.filter(d => (d["testing"] && d["strict-imitation"])));
}
allDataPoints = allDataPoints.filter(d => d.lambda_c >= this.props.lambdaLowerBound && d.lambda_c <= this.props.lambdaUpperBound);
var btcValues = allDataPoints.map(d => d["btc"]);
var becValues = allDataPoints.map(d => d["bec"]);
var allValues = [].concat(btcValues).concat(becValues);
var allPerformance = allDataPoints.map(d => d["performance"]);
var allPerformanceWithH1 = allPerformance.concat(this.props.h1Performance);
var xScale = d3.scaleLinear()
.domain([
d3.min(allValues),
d3.max(allValues)
])
.range([0,w])
var yScale = d3.scaleLinear()
.domain([
(d3.min(allPerformanceWithH1) - 0.005),
(d3.max(allPerformanceWithH1) + 0.005)
])
.range([h,0])
var tooltip = d3.select(`#lambdactooltip-${_this.props.compatibilityScoreType}`);
// SVG
d3.select(`#${this.props.compatibilityScoreType}`).remove();
var zoom = d3.zoom().scaleExtent([1, 100]).on('zoom', doZoom);
var svg = body.insert('svg', '.plot-title-row')
.attr('id', this.props.compatibilityScoreType)
.attr('height', h + margin.top + margin.bottom)
.attr('width', w + margin.left + margin.right)
.call(zoom)
.on("wheel.zoom", null);
var plot = svg.append('g')
.attr('transform','translate(' + margin.left + ',' + margin.top + ')')
_this.zoomIn = () => {
svg.transition().duration(750).call(zoom.scaleBy, 2);
}
_this.zoomOut = () => {
svg.transition().duration(750).call(zoom.scaleBy, 0.5);
}
_this.resetZoom = () => {
svg.transition().duration(750).call(zoom.transform, d3.zoomIdentity);
}
// X-axis
var xAxis = d3.axisBottom()
.scale(xScale)
.tickFormat(formatPercentX)
.ticks(5);
// Y-axis
var yAxis = d3.axisLeft()
.scale(yScale)
.tickFormat(formatPercentY)
.ticks(5);
// X-axis
var xAxisDraw = plot.append('g')
.attr('class','axis')
.attr('id','xAxis')
.attr('transform', 'translate(0,' + h + ')')
.call(xAxis)
xAxisDraw.append('text')
.attr('id','xAxisLabel')
.attr('y', 25)
.attr('x',w/2)
.attr('dy','.71em')
.style('text-anchor','end')
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "black");
// Y-axis
var yAxisDraw = plot.append('g')
.attr('class','axis')
.attr('id','yAxis')
.call(yAxis)
yAxisDraw.append('text')
.attr('id', 'yAxisLabel')
.attr('transform','rotate(-90)')
.attr('x',-h/2+2.5*this.props.performanceMetric.length)
.attr('y',-50)
.attr('dy','.71em')
.style('text-anchor','end')
.text(this.props.performanceMetric)
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "black");
var h1AccuracyLine = plot.append("line")
.attr("x1", xScale(d3.min(allValues) - 0.005))
.attr("y1", yScale(this.props.h1Performance))
.attr("x2", xScale(d3.max(allValues)))
.attr("y2", yScale(this.props.h1Performance))
.attr("stroke", "#6f27db")
.attr("stroke-width", "1px")
.attr("stroke-dasharray", "5,5");
var h1AccuracyText = plot.append('text')
.attr("x", xScale(d3.min(allValues) - 0.057))
.attr("y", yScale(this.props.h1Performance))
.text(this.props.h1Performance.toFixed(3).toString())
.attr("font-family", "sans-serif")
.attr("font-size", "10px")
.attr("fill", "#6f27db");
// Make points outside the plotted area invisible
var clipId = `clip${this.props.compatibilityScoreType}`;
var clip = plot.append("defs")
.append("svg:clipPath")
.attr("id", clipId)
.append("svg:rect")
.attr('x', 0)
.attr('y', 0)
.attr('width', w)
.attr('height', h);
var plot = plot.append('g')
.attr("id", "scatterplot")
.attr("clip-path", `url(#${clipId})`);
function drawNewError() {
const newErrorData = allDataPoints.filter(d => d["new-error"]);
const radius = 8;
var circles = plot.selectAll('circle')
.data(newErrorData)
.enter()
.append('circle')
.attr('cx',function (d) { return xScale(d[_this.props.compatibilityScoreType]) })
.attr('cy',function (d) { return yScale(d['performance']) })
.attr('r', function(d) {
var datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index == datapointIndex) {
return 1.5 * radius;
} else {
return radius;
}
})
.attr('stroke','black')
.attr('stroke-width', function(d) {
var datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index == datapointIndex) {
return 3;
} else {
return 1;
}
})
.attr('fill',function (d,i) {
if (d["training"]) {
return colorMap["training"];
} else if (d["testing"]) {
return colorMap["testing"];
}
})
.on('mouseover', function (d) {
d3.select(this)
.transition()
.duration(500)
.attr('r',1.5*radius)
.attr('stroke-width',3);
tooltip.text(`lambda ${d["lambda_c"].toFixed(2)}`)
.style("opacity", 0.8);
})
.on('mouseout', function (d) {
var datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index != datapointIndex) {
d3.select(this)
.transition()
.duration(500)
.attr('r',radius)
.attr('stroke-width',1);
}
tooltip.style("opacity", 0);
tooltip.text("");
})
.on("mousemove", function() {
var scatterPlot = document.getElementById(`scatterplot-${_this.props.compatibilityScoreType}`);
var coords = d3.mouse(scatterPlot);
tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2 - 40}px`)
.style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`);
})
.on('click', (d, i) => {
_this.props.getModelEvaluationData(d["datapoint_index"]);
});
return circles;
}
// Calculates coordinates for the vertices of an equilateral triangle
// with centroid coordinates cx,cy and scaled by size
const sqrt3 = Math.sqrt(3);
function getTrianglePoints(cx: number, cy: number, size: number, xScale: Function, yScale: Function) {
const p1 = (xScale(cx) - sqrt3*size) + ',' + (yScale(cy) + size);
const p2 = (xScale(cx) + sqrt3*size) + ',' + (yScale(cy) + size);
const p3 = xScale(cx) + ',' + (yScale(cy) - 2*size);
// x,y points delimited by spaces
return p1 + ' ' + p2 + ' ' + p3 + ' ' + p1;
}
function drawStrictImitation() {
const getPoints = (d: any, size: number) => getTrianglePoints(d[_this.props.compatibilityScoreType], d['performance'], size, xScale, yScale);
const strictImitationData = allDataPoints.filter(d => d["strict-imitation"]);
const triangles = plot.selectAll('polyline')
.data(strictImitationData)
.enter()
.append('polyline')
.attr('points', function(d) {
const datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index == datapointIndex) {
return getPoints(d, 8);
} else {
return getPoints(d, 4);
}
})
.attr('stroke','black')
.attr('stroke-width', function(d) {
const datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index == datapointIndex) {
return 3;
} else {
return 1;
}
})
.attr('fill',function (d,i) {
if (d["training"]) {
return colorMap["training"];
} else if (d["testing"]) {
return colorMap["testing"];
}
})
.on('mouseover', function (d) {
d3.select(this)
.transition()
.duration(500)
.attr('points', d => getPoints(d, 8))
.attr('stroke-width',3);
tooltip.text(`lambda ${d["lambda_c"].toFixed(2)}`)
.style("opacity", 0.8);
})
.on('mouseout', function (d) {
var datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index != datapointIndex) {
d3.select(this)
.transition()
.duration(500)
.attr('points', d => getPoints(d, 4))
.attr('stroke-width',1);
}
tooltip.style("opacity", 0);
tooltip.text("");
})
.on("mousemove", function() {
var scatterPlot = document.getElementById(`scatterplot-${_this.props.compatibilityScoreType}`);
var coords = d3.mouse(scatterPlot);
tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2 - 40}px`)
.style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`);
})
.on('click', (d, i) => {
_this.props.getModelEvaluationData(d["datapoint_index"]);
});
return triangles;
}
const circles = drawNewError();
const triangles = drawStrictImitation();
svg.call(zoom.transform, _this.state.transform);
function doZoom() {
const transform = d3.event.transform;
if (transform != null) {
_this.lastTransform = transform;
const xScaleNew = transform.rescaleX(xScale);
const yScaleNew = transform.rescaleY(yScale);
xAxis.scale(xScaleNew);
xAxisDraw.call(xAxis);
yAxis.scale(yScaleNew)
yAxisDraw.call(yAxis);
circles.attr('cx',function (d) { return xScaleNew(d[_this.props.compatibilityScoreType]) })
.attr('cy',function (d) { return yScaleNew(d['performance']) });
const getPoints = (d: any, size: number) => getTrianglePoints(d[_this.props.compatibilityScoreType], d['performance'], size, xScaleNew, yScaleNew);
triangles.attr('points', function(d) {
const datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index == datapointIndex) {
return getPoints(d, 8);
} else {
return getPoints(d, 4);
}
}).on('mouseover', function (d) {
d3.select(this)
.transition()
.duration(500)
.attr('points', d => getPoints(d, 8))
.attr('stroke-width',3);
tooltip.text(`lambda ${d["lambda_c"].toFixed(2)}`)
.style("opacity", 0.8);
}).on('mouseout', function (d) {
var datapointIndex = (_this.props.selectedDataPoint != null)? _this.props.selectedDataPoint.datapoint_index: null;
if (d.datapoint_index != datapointIndex) {
d3.select(this)
.transition()
.duration(500)
.attr('points', d => getPoints(d, 4))
.attr('stroke-width',1);
}
tooltip.style("opacity", 0);
tooltip.text("");
});
h1AccuracyLine.attr("y1", yScaleNew(_this.props.h1Performance))
.attr("y2", yScaleNew(_this.props.h1Performance))
h1AccuracyText.attr("y", yScaleNew(_this.props.h1Performance))
}
}
}
render() {
let title = this.props.compatibilityScoreType.toUpperCase();
let message = "UNDEFINED";
if (title == "BTC") {
message = "Backward Trust Compatibility (BTC) describes the percentage of trust preserved after an update."
} else if (title == "BEC") {
message = "Backward Error Compatibility (BEC) captures the probability that a mistake made by the newly trained model is not new."
}
return (
<div>
<div style={{display: "flex", flexDirection: "row", alignItems: "center"}}>
<h3 style={{fontFamily: "'Segoe UI', sans-serif", fontSize: "20px", fontWeight: "normal", marginRight: "8px"}}>Model accuracy - {title}</h3>
<InfoTooltip message={message} direction={DirectionalHint.bottomCenter} />
<div style={{marginLeft: "auto"}}>
<button className="reset-zoom-button" onClick={() => this.resetZoom()}>reset</button>
<IconButton iconProps={{iconName: "ZoomIn"}} onClick={() => this.zoomIn()} styles={{root: {marginRight: "12px", border: "solid #A09C98 1px"}}}/>
<IconButton iconProps={{iconName: "ZoomOut"}} onClick={() => this.zoomOut()} styles={{root: {marginRight: "12px", border: "solid #A09C98 1px"}}}/>
</div>
</div>
<div className="plot" ref={this.node} id={`scatterplot-${this.props.compatibilityScoreType}`}>
<div className="tooltip" id={`lambdactooltip-${this.props.compatibilityScoreType}`} />
<div className="plot-title-row">
{title}
</div>
</div>
</div>
);
}
}
export default PerformanceCompatibility; | the_stack |
import { EventBus, EventBusOffListener } from './EventBus'
import { loadResource, LoadResourceUrlType } from './loadResource'
import { mapValues, noop } from 'lodash-uni'
declare const wx: any
/**
* 微信 JSSDK 支持的 API。
*
* @public
*/
export type WechatJsApi =
| 'checkJsApi'
| 'updateAppMessageShareData'
| 'updateTimelineShareData'
| 'onMenuShareTimeline'
| 'onMenuShareAppMessage'
| 'onMenuShareQQ'
| 'onMenuShareQZone'
| 'startRecord'
| 'stopRecord'
| 'onVoiceRecordEnd'
| 'playVoice'
| 'pauseVoice'
| 'stopVoice'
| 'onVoicePlayEnd'
| 'uploadVoice'
| 'downloadVoice'
| 'chooseImage'
| 'previewImage'
| 'uploadImage'
| 'downloadImage'
| 'translateVoice'
| 'getNetworkType'
| 'openLocation'
| 'getLocation'
| 'hideOptionMenu'
| 'showOptionMenu'
| 'hideMenuItems'
| 'showMenuItems'
| 'hideAllNonBaseMenuItem'
| 'showAllNonBaseMenuItem'
| 'closeWindow'
| 'scanQRCode'
| 'chooseWXPay'
| 'openProductSpecificView'
| 'addCard'
| 'chooseCard'
| 'openCard'
/**
* @public
*/
export interface WechatConfigParams {
/**
* 开启调试模式。
*
* 调用的所有api的返回值会在客户端 alert 出来,
* 若要查看传入的参数,可以在 pc 端打开,
* 参数信息会通过 log 打出,仅在 pc 端时才会打印。
*
* @default false
*/
debug?: boolean
/**
* 公众号的唯一标识。
*/
appId: string
/**
* 生成签名的时间戳。
*/
timestamp: number | string
/**
* 生成签名的随机串。
*/
nonceStr: string
/**
* 签名。
*/
signature: string
/**
* 需要使用的JS接口列表。
*
* @default []
*/
jsApiList?: WechatJsApi[]
/**
* 是否可分享。
*
* 设置为 `true` 将把分享系列接口自动加入 `jsApiList`。
*
* @default true
*/
sharable?: boolean
/**
* 当全局变量 `wx` 不存在时,自动引入微信 JSSDK。
*
* - 设为 `false` 可禁止自动引入;
* - 设为版本号表示引入特定版本的 JSSDK;
* - 设为链接表示通过该链接引入 JSSDK。
*
* @default '1.4.0'
*/
autoLoadJSSDK?: false | string
}
/**
* @public
*/
export type WechatErrorCallback = (err: any) => void
/**
* @public
*/
export interface WechatUpdateShareDataParams {
/** 分享标题 */
title?: string | (() => string)
/** 分享描述 */
desc?: string | (() => string)
/** 分享链接,该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致 */
link?: string | (() => string)
/** 分享图标地址 */
imgUrl?: string | (() => string)
}
/**
* @public
*/
export interface WechatChooseImageParams {
/**
* 选择图片数量。
*
* @default 9
*/
count?: number
/**
* 图片质量,可以指定是原图还是压缩图。
*
* @default ['original', 'compressed']
*/
sizeType?: Array<'original' | 'compressed'>
/**
* 选择来源,可以指定是相册还是相机。
*
* @default ['album', 'camera']
*/
sourceType?: Array<'album' | 'camera'>
}
/**
* @public
*/
export interface WechatPreviewImageParams {
/**
* 当前显示图片的链接。
*
* @default urls[0]
*/
current?: string
/**
* 需要预览的图片链接列表。
*/
urls: string[]
}
/**
* @public
*/
export interface WechatUploadImageParams {
/**
* 需要上传的图片的本地 ID,由 chooseImage 接口获得。
*/
localId: string
/**
* 是否显示进度提示。
*
* @default false
*/
isShowProgressTips?: boolean
}
/**
* @public
*/
export interface WechatOpenLocationParams {
/**
* 纬度,浮点数,范围为 90 ~ -90。
*/
latitude: number
/**
* 经度,浮点数,范围为 180 ~ -180。
*/
longitude: number
/**
* 位置名。
*/
name: string
/**
* 地址详情说明。
*/
address?: string
/**
* 地图缩放级别,整形值,范围从 1 ~ 28。
*
* @default 28
*/
scale?: number
/**
* 在查看位置界面底部显示的超链接,可点击跳转。
*/
infoUrl?: string
}
export interface WechatRequestPaymentParams {
/**
* 支付签名时间戳。
*/
timestamp: number
/**
* 支付签名随机串。
*/
nonceStr: string
/**
* 统一支付接口返回的 prepay_id 参数值,如:`prepay_id=xxx`。
*/
package: string
/**
* 签名方式。
*/
signType: string
/**
* 支付签名。
*/
paySign: string
}
/**
* 微信内网页的非基础菜单列表。
*
* @public
*/
export type WechatNonBaseMenuItem =
| 'menuItem:share:appMessage'
| 'menuItem:share:timeline'
| 'menuItem:share:qq'
| 'menuItem:share:weiboApp'
| 'menuItem:favorite'
| 'menuItem:share:facebook'
| 'menuItem:share:QZone'
| 'menuItem:editTag'
| 'menuItem:delete'
| 'menuItem:copyUrl'
| 'menuItem:originPage'
| 'menuItem:readMode'
| 'menuItem:openWithQQBrowser'
| 'menuItem:openWithSafari'
| 'menuItem:share:email'
| 'menuItem:share:brand'
/**
* 微信 JSSDK 支持的分享 API 列表。
*/
const shareJsApiList: WechatJsApi[] = [
'updateAppMessageShareData',
'updateTimelineShareData',
'onMenuShareAppMessage',
'onMenuShareTimeline',
'onMenuShareQQ',
'onMenuShareQZone',
]
/**
* 对微信 JSSDK 的封装。
*
* @public
* @example
* ```typescript
* const wechat = new Wechat()
* getWechatConfigAsync().then(config => {
* wechat.config(config)
* })
* wechat.updateShareData({
* title: '分享标题',
* desc: '分享描述',
* link: '分享链接',
* imgUrl: '缩略图地址',
* })
* wechat.invoke('scanQRCode').then(res => {
* // => API 调用结果
* })
* ```
*/
export class Wechat {
/**
* 微信 JSSDK 是否已准备完成。
*/
private ready = false
/**
* 消息巴士。
*/
private bus = new EventBus<{
/**
* 微信 JSSDK 准备完成时触发。
*/
ready: () => void
/**
* 调用微信 JSSDK 出错时时触发。
*/
error: WechatErrorCallback
}>()
/**
* 上一次设置分享时的参数。
*/
private prevShareParams: WechatUpdateShareDataParams = {}
/**
* 注入微信 `JSSDK` 的权限验证配置参数。
*/
public configParams: WechatConfigParams = {} as any
/**
* 构造函数。
*
* @param params 注入微信 `JSSDK` 的权限验证配置参数
*/
constructor(params?: WechatConfigParams) {
if (params) {
this.config(params)
}
}
/**
* 注入微信 `JSSDK` 的权限验证配置。
*
* @param params 配置参数
*/
config(params: WechatConfigParams = this.configParams) {
this.configParams = params
const config = () => {
const sharable =
typeof params.sharable === 'boolean' ? params.sharable : true
wx.config({
...params,
jsApiList: [
...(params.jsApiList || []),
...(sharable ? shareJsApiList : []),
],
})
if (!this.ready) {
wx.ready(() => {
this.ready = true
this.bus.emit('ready')
})
wx.error((err: any) => {
this.bus.emit('error', err)
})
}
}
if (typeof wx !== 'undefined') {
config()
} else {
const autoLoadJSSDK =
params.autoLoadJSSDK == null ? '1.4.0' : params.autoLoadJSSDK
if (autoLoadJSSDK !== false) {
const jssdkUrl = /^[0-9.]+$/.test(autoLoadJSSDK)
? `https://res.wx.qq.com/open/js/jweixin-${autoLoadJSSDK}.js`
: autoLoadJSSDK
const alternateJssdkUrl = jssdkUrl.replace(
/^https:\/\/res\.wx\.qq\.com\//,
'https://res2.wx.qq.com/',
)
loadResource({
type: LoadResourceUrlType.js,
path: jssdkUrl,
alternatePath: alternateJssdkUrl,
})
.then(([scriptEl]) => {
scriptEl.parentNode?.removeChild(scriptEl)
}, noop)
.then(() => {
if (typeof wx === 'undefined') {
throw new Error('微信 JSSDK 加载失败')
}
config()
})
} else {
if (typeof wx === 'undefined') {
throw new Error('请先引入微信 JSSDK')
}
config()
}
}
}
/**
* 判断当前客户端版本是否支持指定 JS 接口。
*
* @param jsApiList 需要检测的 JS 接口列表
* @returns 以键值对的形式返回,可用的 `api` 值 `true`,不可用为 `false`
*/
checkJsApi<T extends WechatJsApi>(
jsApiList: T[],
): Promise<Record<T, boolean>> {
return this.invoke<
{
jsApiList: T[]
},
{
checkResult: Record<T, boolean>
}
>('checkJsApi', { jsApiList }).then(res => res.checkResult)
}
/**
* 设置分享数据。
*
* **注意**:每次分享的数据会和上次分享的数据合并作为最终分享的数据,因此,可以设置全局的分享数据。
*
* @param params 分享数据
*/
updateShareData(params: WechatUpdateShareDataParams): Promise<void> {
params = {
...this.prevShareParams,
...params,
}
this.prevShareParams = params
params = mapValues(params, value =>
typeof value === 'function' ? value() : value,
)
return shareJsApiList.reduce<Promise<any>>((prev, jsApi) => {
const next = () => this.invoke<WechatUpdateShareDataParams>(jsApi, params)
return prev.then(next, next)
}, Promise.resolve())
}
/**
* 选择图片。
*
* @param params 参数
* @returns 选定照片的本地 ID 列表,它们可以作为 img 标签的 src 属性显示图片
*/
chooseImage(params?: WechatChooseImageParams): Promise<string[]> {
return this.invoke<
WechatChooseImageParams,
{
localIds: string[]
}
>('chooseImage', params).then(res => res.localIds)
}
/**
* 预览图片。
*
* @param params 参数
*/
previewImage(params: WechatPreviewImageParams): Promise<any> {
return this.invoke<WechatPreviewImageParams>('previewImage', {
urls: params.urls,
current: params.current || params.urls[0],
})
}
/**
* 上传图片。
*
* **备注:** 上传图片有效期3天,
* 可用微信多媒体接口下载图片到自己的服务器,
* 此处获得的服务器端 ID 即 `media_id`。
*
* @param params 参数
* @returns 图片的服务器端 ID
*/
uploadImage(params: WechatUploadImageParams): Promise<string> {
return this.invoke<
{
localId: string
isShowProgressTips: 0 | 1
},
{
serverId: string
}
>('uploadImage', {
localId: params.localId,
isShowProgressTips: params.isShowProgressTips ? 1 : 0,
}).then(res => res.serverId)
}
/**
* 使用微信内置地图查看位置。
*
* @param params 参数
*/
openLocation(params: WechatOpenLocationParams): Promise<any> {
return this.invoke<WechatOpenLocationParams>('openLocation', params)
}
/**
* 关闭当前网页窗口。
*/
closeWindow(): Promise<any> {
return this.invoke('closeWindow')
}
/**
* 批量隐藏非基础菜单项。
*
* @param menuList 要隐藏的非基础菜单项列表
*/
hideNonBaseMenuItems(menuList: WechatNonBaseMenuItem[]): Promise<any> {
return this.invoke<{
menuList: WechatNonBaseMenuItem[]
}>('hideMenuItems', { menuList })
}
/**
* 批量显示非基础菜单项。
*
* @param menuList 要显示的非基础菜单项列表
*/
showNonBaseMenuItems(menuList: WechatNonBaseMenuItem[]): Promise<any> {
return this.invoke<{
menuList: WechatNonBaseMenuItem[]
}>('showMenuItems', { menuList })
}
/**
* 隐藏所有的非基础菜单项。
*/
hideAllNonBaseMenuItems(): Promise<any> {
return this.invoke('hideAllNonBaseMenuItem')
}
/**
* 显示所有的非基础菜单项。
*/
showAllNonBaseMenuItems(): Promise<any> {
return this.invoke('showAllNonBaseMenuItem')
}
/**
* 发起微信支付。
*
* @param params 参数
*/
requestPayment(params: WechatRequestPaymentParams): Promise<any> {
return this.invoke('chooseWXPay', params)
}
/**
* 错误处理。
*
* @param callback 出错时的回调函数
*/
onError(callback: WechatErrorCallback): EventBusOffListener {
return this.bus.on('error', callback)
}
/**
* 调用 JSSDK 的 API 方法。
*
* @param jsApi 要调用的 API 名称
* @param params 传给 API 的参数
* @returns 调用结果
*/
invoke<P extends Record<string, any> = Record<string, any>, T = any>(
jsApi: WechatJsApi,
params: P = {} as any,
): Promise<T> {
return new Promise((resolve, reject) => {
const invoke = () => {
if (!wx[jsApi]) return reject(`wx.${jsApi} 不可用`)
this.config()
wx[jsApi]({
...params,
success: resolve,
fail: reject,
cancel: reject,
})
}
if (typeof wx === 'undefined' || !this.ready) {
this.bus.once('ready', invoke)
} else {
invoke()
}
})
}
} | the_stack |
import { testTokenization } from '../test/testRunner';
testTokenization('pla', [
// Keywords
// .i
[
{
line: '.i 50',
tokens: [
{ startIndex: 0, type: 'keyword.i.pla' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'number.pla' }
]
},
{
line: ' .i 333 # Input',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'keyword.i.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'number.pla' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'comment.pla' }
]
}
],
// .o
[
{
line: '.o 7',
tokens: [
{ startIndex: 0, type: 'keyword.o.pla' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'number.pla' }
]
},
{
line: ' .o 1000 ',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 1, type: 'keyword.o.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.pla' },
{ startIndex: 8, type: '' }
]
}
],
// .mv
[
{
line: '.mv 9 4 3 21 1',
tokens: [
{ startIndex: 0, type: 'keyword.mv.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'number.pla' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'number.pla' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'number.pla' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'number.pla' }
]
},
{
line: '.mv 22 22',
tokens: [
{ startIndex: 0, type: 'keyword.mv.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.pla' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'number.pla' }
]
}
],
// .ilb
[
{
line: '.ilb in1 in2 in3 in4 in5',
tokens: [
{ startIndex: 0, type: 'keyword.ilb.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'identifier.pla' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'identifier.pla' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'identifier.pla' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'identifier.pla' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'identifier.pla' }
]
},
{
line: '.ilb input<0> input<1> input<2> input<3>',
tokens: [
{ startIndex: 0, type: 'keyword.ilb.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'identifier.pla' },
{ startIndex: 10, type: 'delimiter.angle.pla' },
{ startIndex: 11, type: 'number.pla' },
{ startIndex: 12, type: 'delimiter.angle.pla' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'identifier.pla' },
{ startIndex: 19, type: 'delimiter.angle.pla' },
{ startIndex: 20, type: 'number.pla' },
{ startIndex: 21, type: 'delimiter.angle.pla' },
{ startIndex: 22, type: '' },
{ startIndex: 23, type: 'identifier.pla' },
{ startIndex: 28, type: 'delimiter.angle.pla' },
{ startIndex: 29, type: 'number.pla' },
{ startIndex: 30, type: 'delimiter.angle.pla' },
{ startIndex: 31, type: '' },
{ startIndex: 32, type: 'identifier.pla' },
{ startIndex: 37, type: 'delimiter.angle.pla' },
{ startIndex: 38, type: 'number.pla' },
{ startIndex: 39, type: 'delimiter.angle.pla' }
]
}
],
// .ob
[
{
line: '.ob out1 out2 out3',
tokens: [
{ startIndex: 0, type: 'keyword.ob.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pla' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'identifier.pla' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'identifier.pla' }
]
},
{
line: '.ob output<0> output<1>',
tokens: [
{ startIndex: 0, type: 'keyword.ob.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pla' },
{ startIndex: 10, type: 'delimiter.angle.pla' },
{ startIndex: 11, type: 'number.pla' },
{ startIndex: 12, type: 'delimiter.angle.pla' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'identifier.pla' },
{ startIndex: 20, type: 'delimiter.angle.pla' },
{ startIndex: 21, type: 'number.pla' },
{ startIndex: 22, type: 'delimiter.angle.pla' }
]
}
],
// .label
[
{
line: '.label in1 in2 in3 in4 in5',
tokens: [
{ startIndex: 0, type: 'keyword.label.pla' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'identifier.pla' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'identifier.pla' },
{ startIndex: 14, type: '' },
{ startIndex: 15, type: 'identifier.pla' },
{ startIndex: 18, type: '' },
{ startIndex: 19, type: 'identifier.pla' },
{ startIndex: 22, type: '' },
{ startIndex: 23, type: 'identifier.pla' }
]
},
{
line: '.label var=5 part1 part2 part3 part4',
tokens: [
{ startIndex: 0, type: 'keyword.label.pla' },
{ startIndex: 6, type: '' },
{ startIndex: 8, type: 'identifier.pla' },
{ startIndex: 11, type: 'delimiter.pla' },
{ startIndex: 12, type: 'number.pla' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'identifier.pla' },
{ startIndex: 19, type: '' },
{ startIndex: 20, type: 'identifier.pla' },
{ startIndex: 25, type: '' },
{ startIndex: 26, type: 'identifier.pla' },
{ startIndex: 31, type: '' },
{ startIndex: 32, type: 'identifier.pla' }
]
}
],
// .type
[
{
line: '.type fr',
tokens: [
{ startIndex: 0, type: 'keyword.type.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'type.pla' }
]
},
{
line: ' .type fdr # Comment ',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 1, type: 'keyword.type.pla' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'type.pla' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'comment.pla' }
]
},
{
line: '.type other',
tokens: [
{ startIndex: 0, type: 'keyword.type.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'type.pla' }
]
}
],
// .phase
[
{
line: '.phase 010',
tokens: [
{ startIndex: 0, type: 'keyword.phase.pla' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'number.pla' }
]
}
],
// .pair
[
{
line: '.pair 2 (aa bb) (cc dd) ## Comment',
tokens: [
{ startIndex: 0, type: 'keyword.pair.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'number.pla' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'delimiter.parenthesis.pla' },
{ startIndex: 9, type: 'identifier.pla' },
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'identifier.pla' },
{ startIndex: 14, type: 'delimiter.parenthesis.pla' },
{ startIndex: 15, type: '' },
{ startIndex: 16, type: 'delimiter.parenthesis.pla' },
{ startIndex: 17, type: 'identifier.pla' },
{ startIndex: 19, type: '' },
{ startIndex: 20, type: 'identifier.pla' },
{ startIndex: 22, type: 'delimiter.parenthesis.pla' },
{ startIndex: 23, type: '' },
{ startIndex: 24, type: 'comment.pla' }
]
}
],
// .symbolic
[
{
line: '.symbolic aa<2> aa<1> aa<0> ; BB CC DD ;',
tokens: [
{ startIndex: 0, type: 'keyword.symbolic.pla' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.pla' },
{ startIndex: 12, type: 'delimiter.angle.pla' },
{ startIndex: 13, type: 'number.pla' },
{ startIndex: 14, type: 'delimiter.angle.pla' },
{ startIndex: 15, type: '' },
{ startIndex: 16, type: 'identifier.pla' },
{ startIndex: 18, type: 'delimiter.angle.pla' },
{ startIndex: 19, type: 'number.pla' },
{ startIndex: 20, type: 'delimiter.angle.pla' },
{ startIndex: 21, type: '' },
{ startIndex: 22, type: 'identifier.pla' },
{ startIndex: 24, type: 'delimiter.angle.pla' },
{ startIndex: 25, type: 'number.pla' },
{ startIndex: 26, type: 'delimiter.angle.pla' },
{ startIndex: 27, type: '' },
{ startIndex: 28, type: 'delimiter.pla' },
{ startIndex: 29, type: '' },
{ startIndex: 30, type: 'identifier.pla' },
{ startIndex: 32, type: '' },
{ startIndex: 33, type: 'identifier.pla' },
{ startIndex: 35, type: '' },
{ startIndex: 36, type: 'identifier.pla' },
{ startIndex: 38, type: '' },
{ startIndex: 39, type: 'delimiter.pla' }
]
},
{
line: '.symbolic state<3> state<2>;aaa bbb; # comment',
tokens: [
{ startIndex: 0, type: 'keyword.symbolic.pla' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.pla' },
{ startIndex: 15, type: 'delimiter.angle.pla' },
{ startIndex: 16, type: 'number.pla' },
{ startIndex: 17, type: 'delimiter.angle.pla' },
{ startIndex: 18, type: '' },
{ startIndex: 19, type: 'identifier.pla' },
{ startIndex: 24, type: 'delimiter.angle.pla' },
{ startIndex: 25, type: 'number.pla' },
{ startIndex: 26, type: 'delimiter.angle.pla' },
{ startIndex: 27, type: 'delimiter.pla' },
{ startIndex: 28, type: 'identifier.pla' },
{ startIndex: 31, type: '' },
{ startIndex: 32, type: 'identifier.pla' },
{ startIndex: 35, type: 'delimiter.pla' },
{ startIndex: 36, type: '' },
{ startIndex: 37, type: 'comment.pla' }
]
}
],
// .symbolic-output
[
{
line: '.symbolic-output out<2> out<1> out<0> ; signal_a signal_b signal_c ;',
tokens: [
{ startIndex: 0, type: 'keyword.symbolic-output.pla' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'identifier.pla' },
{ startIndex: 20, type: 'delimiter.angle.pla' },
{ startIndex: 21, type: 'number.pla' },
{ startIndex: 22, type: 'delimiter.angle.pla' },
{ startIndex: 23, type: '' },
{ startIndex: 24, type: 'identifier.pla' },
{ startIndex: 27, type: 'delimiter.angle.pla' },
{ startIndex: 28, type: 'number.pla' },
{ startIndex: 29, type: 'delimiter.angle.pla' },
{ startIndex: 30, type: '' },
{ startIndex: 31, type: 'identifier.pla' },
{ startIndex: 34, type: 'delimiter.angle.pla' },
{ startIndex: 35, type: 'number.pla' },
{ startIndex: 36, type: 'delimiter.angle.pla' },
{ startIndex: 37, type: '' },
{ startIndex: 38, type: 'delimiter.pla' },
{ startIndex: 39, type: '' },
{ startIndex: 40, type: 'identifier.pla' },
{ startIndex: 48, type: '' },
{ startIndex: 49, type: 'identifier.pla' },
{ startIndex: 57, type: '' },
{ startIndex: 58, type: 'identifier.pla' },
{ startIndex: 66, type: '' },
{ startIndex: 67, type: 'delimiter.pla' }
]
}
],
// .kiss
[
{
line: '.kiss #.kiss',
tokens: [
{ startIndex: 0, type: 'keyword.kiss.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'comment.pla' }
]
}
],
// .p
[
{
line: '.p 400',
tokens: [
{ startIndex: 0, type: 'keyword.p.pla' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'number.pla' }
]
}
],
// .e
[
{
line: ' .e ',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 1, type: 'keyword.e.pla' },
{ startIndex: 3, type: '' }
]
}
],
// PLA rows
[
{
line: '0-010|1000|100000000000000000000000000|0010000000',
tokens: [{ startIndex: 0, type: 'string.pla' }]
},
{
line: '--------------0 00000000000010',
tokens: [
{ startIndex: 0, type: 'string.pla' },
{ startIndex: 15, type: '' },
{ startIndex: 16, type: 'string.pla' }
]
},
{
line: '0~~0 1-0 # Comment',
tokens: [
{ startIndex: 0, type: 'string.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'string.pla' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'comment.pla' }
]
}
],
// Full example #1
[
{
line: '.i 4',
tokens: [
{ startIndex: 0, type: 'keyword.i.pla' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'number.pla' }
]
},
{
line: '.o 3',
tokens: [
{ startIndex: 0, type: 'keyword.o.pla' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'number.pla' }
]
},
{
line: '',
tokens: []
},
{
line: '# Comment only line',
tokens: [{ startIndex: 0, type: 'comment.pla' }]
},
{
line: '.ilb Q1 Q0 D N',
tokens: [
{ startIndex: 0, type: 'keyword.ilb.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'identifier.pla' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.pla' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'identifier.pla' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'identifier.pla' }
]
},
{
line: '.ob T1 T0 input_1',
tokens: [
{ startIndex: 0, type: 'keyword.ob.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pla' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'identifier.pla' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.pla' }
]
},
{
line: '.p 5',
tokens: [
{ startIndex: 0, type: 'keyword.p.pla' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'number.pla' }
]
},
{
line: '0--- 100',
tokens: [
{ startIndex: 0, type: 'string.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'string.pla' }
]
},
{
line: '1-1- 010',
tokens: [
{ startIndex: 0, type: 'string.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'string.pla' }
]
},
{
line: '.e',
tokens: [{ startIndex: 0, type: 'keyword.e.pla' }]
}
],
// Full example #2
[
{
line: '.mv 8 5 -10 -10 6',
tokens: [
{ startIndex: 0, type: 'keyword.mv.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'number.pla' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'number.pla' },
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'number.pla' },
{ startIndex: 15, type: '' },
{ startIndex: 16, type: 'number.pla' }
]
},
{
line: '.ilb in1 in0 wait ack nack',
tokens: [
{ startIndex: 0, type: 'keyword.ilb.pla' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'identifier.pla' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'identifier.pla' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'identifier.pla' },
{ startIndex: 17, type: '' },
{ startIndex: 18, type: 'identifier.pla' },
{ startIndex: 21, type: '' },
{ startIndex: 22, type: 'identifier.pla' }
]
},
{
line: '.ob wait wait2 in3 pending ack delay',
tokens: [
{ startIndex: 0, type: 'keyword.ob.pla' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pla' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'identifier.pla' },
{ startIndex: 14, type: '' },
{ startIndex: 15, type: 'identifier.pla' },
{ startIndex: 18, type: '' },
{ startIndex: 19, type: 'identifier.pla' },
{ startIndex: 26, type: '' },
{ startIndex: 27, type: 'identifier.pla' },
{ startIndex: 30, type: '' },
{ startIndex: 31, type: 'identifier.pla' }
]
},
{
line: '.type fr',
tokens: [
{ startIndex: 0, type: 'keyword.type.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'type.pla' }
]
},
{
line: '.kiss',
tokens: [{ startIndex: 0, type: 'keyword.kiss.pla' }]
},
{
line: '--1-- - wait 110000',
tokens: [
{ startIndex: 0, type: 'string.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 10, type: 'string.pla' },
{ startIndex: 11, type: '' },
{ startIndex: 19, type: 'identifier.pla' },
{ startIndex: 23, type: '' },
{ startIndex: 28, type: 'string.pla' }
]
},
{
line: '--1-- wait wait2 110000 # row comment',
tokens: [
{ startIndex: 0, type: 'string.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 10, type: 'identifier.pla' },
{ startIndex: 14, type: '' },
{ startIndex: 18, type: 'identifier.pla' },
{ startIndex: 23, type: '' },
{ startIndex: 28, type: 'string.pla' },
{ startIndex: 34, type: '' },
{ startIndex: 35, type: 'comment.pla' }
]
},
{
line: '--0-1 delay ack 101000',
tokens: [
{ startIndex: 0, type: 'string.pla' },
{ startIndex: 5, type: '' },
{ startIndex: 10, type: 'identifier.pla' },
{ startIndex: 15, type: '' },
{ startIndex: 19, type: 'identifier.pla' },
{ startIndex: 22, type: '' },
{ startIndex: 27, type: 'string.pla' }
]
},
{
line: '.end',
tokens: [{ startIndex: 0, type: 'keyword.end.pla' }]
}
]
]); | the_stack |
import {
authClient as auth,
authClientWithSession as authWithSession,
authSubscriptionClient,
clientApiAutoConfirmOffSignupsEnabledClient as phoneClient,
clientApiAutoConfirmDisabledClient as signUpDisabledClient,
clientApiAutoConfirmEnabledClient as signUpEnabledClient,
} from './lib/clients'
import { mockUserCredentials } from './lib/utils'
describe('GoTrueClient', () => {
afterEach(async () => {
await auth.signOut()
await authWithSession.signOut()
})
describe('Sessions', () => {
test('setSession should return no error', async () => {
const { email, password } = mockUserCredentials()
const { error, session } = await authWithSession.signUp({
email,
password,
})
expect(error).toBeNull()
expect(session).not.toBeNull()
await authWithSession.setSession(session?.refresh_token as string)
const { user } = await authWithSession.update({ data: { hello: 'world' } })
expect(user).not.toBeNull()
expect(user?.user_metadata).toStrictEqual({ hello: 'world' })
})
test('session() should return the currentUser session', async () => {
const { email, password } = mockUserCredentials()
const { error, session } = await authWithSession.signUp({
email,
password,
})
expect(error).toBeNull()
expect(session).not.toBeNull()
const userSession = authWithSession.session()
expect(userSession).not.toBeNull()
expect(userSession).toHaveProperty('access_token')
expect(userSession).toHaveProperty('user')
})
test('getSessionFromUrl() can only be called from a browser', async () => {
const { error, data } = await authWithSession.getSessionFromUrl()
expect(error?.message).toEqual('No browser detected.')
expect(data).toBeNull()
})
test('refreshSession() raises error if not logged in', async () => {
const { error, user, data } = await authWithSession.refreshSession()
expect(error?.message).toEqual('Not logged in.')
expect(user).toBeNull()
expect(data).toBeNull()
})
test('refreshSession() forces refreshes the session to get a new refresh token for same user', async () => {
const { email, password } = mockUserCredentials()
const { error: initialError, session } = await authWithSession.signUp({
email,
password,
})
expect(initialError).toBeNull()
expect(session).not.toBeNull()
const refreshToken = session?.refresh_token
const { error, user, data } = await authWithSession.refreshSession()
expect(error).toBeNull()
expect(user).not.toBeNull()
expect(data).not.toBeNull()
expect(user?.email).toEqual(email)
expect(data).toHaveProperty('refresh_token')
expect(refreshToken).not.toEqual(data?.refresh_token)
})
})
describe('Authentication', () => {
test('setAuth() should set the Auth headers on a new client', async () => {
const { email, password } = mockUserCredentials()
const { session } = await auth.signUp({
email,
password,
})
const access_token = session?.access_token || null
authWithSession.setAuth(access_token as string)
const authBearer = authWithSession.session()?.access_token
expect(authBearer).toEqual(access_token)
})
})
test('signUp() with email', async () => {
const { email, password } = mockUserCredentials()
const { error, session, user } = await auth.signUp({
email,
password,
})
expect(error).toBeNull()
expect(session).not.toBeNull()
expect(user).not.toBeNull()
expect(user?.email).toEqual(email)
})
describe('Phone OTP Auth', () => {
test('signUp() when phone sign up missing provider account', async () => {
const { phone, password } = mockUserCredentials()
const { error, session, user } = await phoneClient.signUp({
phone,
password,
})
expect(error).not.toBeNull()
expect(session).toBeNull()
expect(user).toBeNull()
expect(error?.message).toEqual('Error sending confirmation sms: Missing Twilio account SID')
})
test('signUp() with phone', async () => {
const { phone, password } = mockUserCredentials()
const { error, session, user } = await phoneClient.signUp({
phone,
password,
})
expect(error).not.toBeNull()
expect(error?.status).toEqual(400)
expect(session).toBeNull()
expect(user).toBeNull()
// expect(user?.phone).toEqual(phone)
})
test('verifyOTP()', async () => {
// unable to test
})
})
test('signUp() the same user twice should not share email already registered message', async () => {
const { email, password } = mockUserCredentials()
await auth.signUp({
email,
password,
})
// sign up again
const { error, session, user } = await auth.signUp({
email,
password,
})
expect(session).toBeNull()
expect(user).toBeNull()
expect(error?.message).toMatch(/^User already registered/)
})
test('signIn()', async () => {
const { email, password } = mockUserCredentials()
await auth.signUp({
email,
password,
})
const { error, session, user } = await auth.signIn({
email,
password,
})
expect(error).toBeNull()
expect(session).toMatchObject({
access_token: expect.any(String),
refresh_token: expect.any(String),
expires_in: expect.any(Number),
expires_at: expect.any(Number),
user: {
id: expect.any(String),
email: expect.any(String),
phone: expect.any(String),
aud: expect.any(String),
email_confirmed_at: expect.any(String),
last_sign_in_at: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
app_metadata: {
provider: 'email',
},
},
})
expect(user).toMatchObject({
id: expect.any(String),
email: expect.any(String),
phone: expect.any(String),
aud: expect.any(String),
email_confirmed_at: expect.any(String),
last_sign_in_at: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
app_metadata: {
provider: 'email',
},
})
expect(user?.email).toBe(email)
})
test('signIn() with refreshToken', async () => {
const { email, password } = mockUserCredentials()
const { error: initialError, session: initialSession } = await authWithSession.signUp({
email,
password,
})
expect(initialError).toBeNull()
expect(initialSession).not.toBeNull()
const refreshToken = initialSession?.refresh_token
const { error, user, session } = await authWithSession.signIn({ refreshToken })
expect(error).toBeNull()
expect(session).toMatchObject({
access_token: expect.any(String),
refresh_token: expect.any(String),
expires_in: expect.any(Number),
expires_at: expect.any(Number),
user: {
id: expect.any(String),
email: expect.any(String),
phone: expect.any(String),
aud: expect.any(String),
email_confirmed_at: expect.any(String),
last_sign_in_at: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
app_metadata: {
provider: 'email',
},
},
})
expect(user).toMatchObject({
id: expect.any(String),
email: expect.any(String),
phone: expect.any(String),
aud: expect.any(String),
email_confirmed_at: expect.any(String),
last_sign_in_at: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
app_metadata: {
provider: 'email',
},
})
expect(user).not.toBeNull()
expect(user?.email).toBe(email)
})
test('signOut', async () => {
const { email, password } = mockUserCredentials()
await authWithSession.signUp({
email,
password,
})
await authWithSession.signIn({
email,
password,
})
const res = await authWithSession.signOut()
expect(res).toBeTruthy()
})
})
describe('User management', () => {
test('Get user', async () => {
const { email, password } = mockUserCredentials()
const { session } = await authWithSession.signUp({
email,
password,
})
const user = authWithSession.user()
expect(user).toMatchObject({
id: expect.any(String),
email: expect.any(String),
phone: expect.any(String),
aud: expect.any(String),
email_confirmed_at: expect.any(String),
last_sign_in_at: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
app_metadata: {
provider: 'email',
},
})
expect(session?.user?.email).toBe(email)
})
test('Update user', async () => {
const { email, password } = mockUserCredentials()
await auth.signUp({
email,
password,
})
const userMetadata = { hello: 'world' }
const { error, user } = await auth.update({ data: userMetadata })
expect(error).toBeNull()
expect(user).toMatchObject({
id: expect.any(String),
aud: expect.any(String),
email: expect.any(String),
phone: expect.any(String),
updated_at: expect.any(String),
last_sign_in_at: expect.any(String),
email_confirmed_at: expect.any(String),
created_at: expect.any(String),
user_metadata: {
hello: 'world',
},
})
expect(user).not.toBeNull()
expect(user?.email).toBe(email)
expect(user?.user_metadata).toStrictEqual(userMetadata)
})
test('Get user after updating', async () => {
const { email, password } = mockUserCredentials()
await auth.signUp({
email,
password,
})
const userMetadata = { hello: 'world' }
await auth.update({ data: userMetadata })
const user = auth.user()
expect(user).toMatchObject({
id: expect.any(String),
aud: expect.any(String),
email: expect.any(String),
phone: expect.any(String),
updated_at: expect.any(String),
last_sign_in_at: expect.any(String),
email_confirmed_at: expect.any(String),
created_at: expect.any(String),
user_metadata: userMetadata,
})
expect(user?.email).toBe(email)
})
test('Get user after logging out', async () => {
const { email, password } = mockUserCredentials()
await authWithSession.signUp({
email,
password,
})
await authWithSession.signIn({
email,
password,
})
const user = await authWithSession.user()
expect(user).not.toBeNull()
await authWithSession.signOut()
const userAfterSignOut = authWithSession.user()
expect(userAfterSignOut).toBeNull()
})
test('signIn() with the wrong password', async () => {
const { email, password } = mockUserCredentials()
const { error, session } = await auth.signIn({
email,
password: password + '-wrong',
})
expect(error).not.toBeNull()
expect(error?.message).not.toBeNull()
expect(session).toBeNull()
})
})
describe('The auth client can signin with third-party oAuth providers', () => {
test('signIn() with Provider', async () => {
const { error, url, provider } = await auth.signIn({
provider: 'google',
})
expect(error).toBeNull()
expect(url).toBeTruthy()
expect(provider).toBeTruthy()
})
test('signIn() with Provider can append a redirectUrl ', async () => {
const { error, url, provider } = await auth.signIn(
{
provider: 'google',
},
{
redirectTo: 'https://localhost:9000/welcome',
}
)
expect(error).toBeNull()
expect(url).toBeTruthy()
expect(provider).toBeTruthy()
})
test('signIn() with Provider can append scopes', async () => {
const { error, url, provider } = await auth.signIn(
{
provider: 'github',
},
{
scopes: 'repo',
}
)
expect(error).toBeNull()
expect(url).toBeTruthy()
expect(provider).toBeTruthy()
})
test('signIn() with Provider can append multiple options', async () => {
const { error, url, provider } = await auth.signIn(
{
provider: 'github',
},
{
redirectTo: 'https://localhost:9000/welcome',
scopes: 'repo',
}
)
expect(error).toBeNull()
expect(url).toBeTruthy()
expect(provider).toBeTruthy()
})
describe('Developers can subscribe and unsubscribe', () => {
const { data: subscription } = authSubscriptionClient.onAuthStateChange(() =>
console.log('onAuthStateChange was called')
)
test('Subscribe a listener', async () => {
// @ts-expect-error 'Allow access to protected stateChangeEmitters'
expect(authSubscriptionClient.stateChangeEmitters.size).toBeTruthy()
})
test('Unsubscribe a listener', async () => {
subscription?.unsubscribe()
// @ts-expect-error 'Allow access to protected stateChangeEmitters'
expect(authSubscriptionClient.stateChangeEmitters.size).toBeFalsy()
})
})
describe('Sign Up Enabled', () => {
test('User can sign up', async () => {
const { email, password } = mockUserCredentials()
const { error, user } = await signUpEnabledClient.signUp({
email,
password,
})
expect(error).toBeNull()
expect(user).not.toBeNull()
expect(user?.email).toEqual(email)
})
})
describe('Sign Up Disabled', () => {
test('User cannot sign up', async () => {
const { email, password } = mockUserCredentials()
const { error, user } = await signUpDisabledClient.signUp({
email,
password,
})
expect(user).toBeNull()
expect(error).not.toBeNull()
expect(error?.message).toEqual('Signups not allowed for this instance')
})
})
}) | the_stack |
import AxiosError from 'axios-error';
import get from 'lodash/get';
import { MergeExclusive } from 'type-fest';
import { MessengerClient } from 'bottender';
import * as Types from './FacebookTypes';
function handleError(err: AxiosError): never {
if (err.response && err.response.data) {
const error = get(err, 'response.data.error');
if (error) {
const msg = `Facebook API - ${error.code} ${error.type} ${error.message}`;
throw new AxiosError(msg, err);
}
}
throw new AxiosError(err.message, err);
}
export default class FacebookClient extends MessengerClient {
/**
* Publish new comments to any object.
*
* @see https://developers.facebook.com/docs/graph-api/reference/object/comments
*
* @param objectId - ID of the object.
* @param comment - A comment text or a comment object.
* @param options -
*/
public sendComment(
objectId: string,
comment: string | Types.InputComment
): Promise<{ id: string }> {
const body = typeof comment === 'string' ? { message: comment } : comment;
return this.axios
.post<{ id: string }>(`/${objectId}/comments`, body, {
params: {
access_token: this.accessToken,
},
})
.then((res) => res.data, handleError);
}
/**
* Add new likes to any object.
*
* @see https://developers.facebook.com/docs/graph-api/reference/object/likes
*
* @param objectId - ID of the object.
*/
public sendLike(objectId: string): Promise<{ success: true }> {
return this.axios
.post<{ success: true }>(`/${objectId}/likes`, undefined, {
params: {
access_token: this.accessToken,
},
})
.then((res) => res.data, handleError);
}
/**
* Get the data of the comment.
*
* @see https://developers.facebook.com/docs/graph-api/reference/comment
*
* @param commentId - ID of the comment.
* @param options -
*/
public getComment<
T extends Types.CommentField = 'id' | 'message' | 'created_time'
>(
commentId: string,
{
fields = ['id' as T, 'message' as T, 'created_time' as T],
}: { fields?: T[] } = {}
): Promise<
Pick<
Types.Comment,
Types.CamelCaseUnion<Types.CommentKeyMap, typeof fields[number]>
>
> {
const conjunctFields = Array.isArray(fields) ? fields.join(',') : fields;
return this.axios
.get<
Pick<
Types.Comment,
Types.CamelCaseUnion<Types.CommentKeyMap, typeof fields[number]>
>
>(`/${commentId}`, {
params: {
fields: conjunctFields,
access_token: this.accessToken,
},
})
.then((res) => res.data, handleError);
}
/**
* Get comments of the object.
*
* @see https://developers.facebook.com/docs/graph-api/reference/v7.0/object/comments
*
* @param objectId - ID of the object.
* @param options -
*/
public getComments<
T extends Types.CommentField = 'id' | 'message' | 'created_time',
U extends boolean = false
>(
objectId: string,
{
limit,
summary,
filter,
order,
fields = ['id' as T, 'message' as T, 'created_time' as T],
}: Types.GetCommentsOptions<T, U> = {}
): Promise<
Types.PagingData<
Pick<
Types.Comment,
Types.CamelCaseUnion<Types.CommentKeyMap, typeof fields[number]>
>[]
> &
(U extends true
? {
summary: {
order: 'ranked' | 'chronological' | 'reverse_chronological';
totalCount: number;
canComment: boolean;
};
}
: any)
> {
const conjunctFields = Array.isArray(fields) ? fields.join(',') : fields;
return this.axios
.get<
Types.PagingData<
Pick<
Types.Comment,
Types.CamelCaseUnion<Types.CommentKeyMap, typeof fields[number]>
>[]
> &
(U extends true
? {
summary: {
order: 'ranked' | 'chronological' | 'reverse_chronological';
totalCount: number;
canComment: boolean;
};
}
: any)
>(`/${objectId}/comments`, {
params: {
limit,
summary: summary ? 'true' : undefined,
filter,
order,
fields: conjunctFields,
access_token: this.accessToken,
},
})
.then((res) => res.data, handleError);
}
/**
* Get the data of likes on the object.
*
* @see https://developers.facebook.com/docs/graph-api/reference/object/likes
*
* @param objectId - ID of the comment.
* @param options -
*/
public getLikes(
objectId: string,
{ summary }: Types.GetLikesOptions = {}
): Promise<Types.Likes> {
return this.axios
.get<{
id: string;
likes: Types.Likes;
}>(`/${objectId}/likes`, {
params: {
summary: summary ? 'true' : undefined,
access_token: this.accessToken,
},
})
.then((res) => res.data.likes, handleError);
}
/**
* Get metrics for pages.
*
* @see https://developers.facebook.com/docs/graph-api/reference/v7.0/insights
*
* @param options -
*/
public getPageInsights<
D extends (
| ({
id: string;
title: string;
description: string;
period: P;
} & {
name: Exclude<
P extends 'day'
? Types.PageInsightsMetricDay
: P extends 'week'
? Types.PageInsightsMetricWeek
: P extends 'days_28'
? Types.PageInsightsMetricDays28
: never,
| 'page_tab_views_login_top_unique'
| 'page_tab_views_login_top'
| 'page_tab_views_logout_top'
| 'page_negative_feedback_by_type'
| 'page_positive_feedback_by_type'
| 'page_fans_by_like_source'
| 'page_fans_by_like_source_unique'
| 'page_fans_by_unlike_source_unique'
| 'page_fans_by_unlike_source'
| 'page_content_activity_by_action_type_unique'
| 'page_content_activity_by_action_type'
>;
values: {
value: number;
endTime: string;
}[];
})
| {
name:
| 'page_tab_views_login_top_unique'
| 'page_tab_views_login_top'
| 'page_tab_views_logout_top';
values: {
value: {
allactivity?: number;
app?: number;
info?: number;
insights?: number;
likes?: number;
locations?: number;
photos?: number;
photosAlbums?: number;
photosStream?: number;
profile?: number;
profileInfo?: number;
profileLikes?: number;
profilePhotos?: number;
timeline?: number;
events?: number;
videos?: number;
wall?: number;
tabHome?: number;
reviews?: number;
about?: number;
profileHome?: number;
profileVideos?: number;
profilePosts?: number;
community?: number;
posts?: number;
home?: number;
};
endTime: string;
}[];
}
| {
name: 'page_negative_feedback_by_type';
values: {
value: {
hideClicks?: number;
hideAllClicks?: number;
reportSpamClicks?: number;
unlikePageClicks?: number;
};
endTime: string;
}[];
}
| {
name: 'page_positive_feedback_by_type';
values: {
value: {
answer?: number;
claim?: number;
comment?: number;
like?: number;
link?: number;
other?: number;
rsvp?: number;
};
endTime: string;
}[];
}
| {
name: 'page_fans_by_like_source' | 'page_fans_by_like_source_unique';
values: {
value: {
ads?: number;
newsFeed?: number;
pageSuggestions?: number;
restoredLikesFromReactivatedAccounts?: number;
search?: number;
yourPage?: number;
other?: number;
};
endTime: string;
}[];
}
| {
name:
| 'page_fans_by_unlike_source_unique'
| 'page_fans_by_unlike_source';
values: {
value: {
deactivatedOrMemorializedAccountRemovals?: number;
other?: number;
suspiciousAccountRemovals?: number;
unlikesFromPagePostsOrNewsFeed?: number;
unlikesFromSearch?: number;
};
endTime: string;
}[];
}
| {
name:
| 'page_content_activity_by_action_type_unique'
| 'page_content_activity_by_action_type';
values: {
value: {
checkin?: number;
coupon?: number;
event?: number;
fan?: number;
mention?: number;
pagePost?: number;
question?: number;
userPost?: number;
other?: number;
};
endTime: string;
}[];
}
)[],
P extends 'day' | 'week' | 'days_28'
>(
options: {
metric: P extends 'day'
? Types.PageInsightsMetricDay[]
: P extends 'week'
? Types.PageInsightsMetricWeek[]
: P extends 'days_28'
? Types.PageInsightsMetricDays28[]
: never;
period: P;
} & MergeExclusive<
{ datePreset?: Types.DatePreset },
{
since?: string | Date;
until?: string | Date;
}
>
): Promise<D> {
return this.axios
.get<{
data: D;
paging: {
previous: string;
next: string;
};
}>('/me/insights', {
params: {
access_token: this.accessToken,
period: options.period,
metric: options.metric.join(','),
date_preset: 'datePreset' in options ? options.datePreset : undefined,
since: 'since' in options ? options.since : undefined,
until: 'until' in options ? options.until : undefined,
},
})
.then((res) => res.data.data, handleError);
}
/**
* Get metrics for page posts.
*
* @see https://developers.facebook.com/docs/graph-api/reference/v7.0/insights
*
* @param postId - ID of the post.
* @param options -
*/
public getPostInsights<
D extends {
id: string;
title: string;
description: string;
name: P extends 'day'
? Types.PostInsightsMetricDay
: P extends 'lifetime'
? Types.PostInsightsMetricLifetime
: never;
period: P;
values: P extends 'day'
? {
value: number;
endTime: string;
}[]
: P extends 'lifetime'
? {
value: number;
}
: never;
}[],
P extends 'day' | 'lifetime'
>(
postId: string,
options: {
metric: P extends 'day'
? Types.PostInsightsMetricDay[]
: P extends 'lifetime'
? Types.PostInsightsMetricLifetime[]
: never;
period?: P;
} & MergeExclusive<
{
datePreset?: Types.DatePreset;
},
{
since?: string | Date;
until?: string | Date;
}
>
): Promise<D> {
return this.axios
.get<{
data: D;
paging: {
previous: string;
next: string;
};
}>(`/${postId}/insights`, {
params: {
access_token: this.accessToken,
period: options.period,
metric: options.metric.join(','),
date_preset: 'datePreset' in options ? options.datePreset : undefined,
since: 'since' in options ? options.since : undefined,
until: 'until' in options ? options.until : undefined,
},
})
.then((res) => res.data.data, handleError);
}
} | the_stack |
* 内容审核 Ocr 文字鉴政、敏感任务结果类型
*/
export interface VodPoliticalOcrReviewResult {
/**
* 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
*/
Status: string
/**
* 错误码,0:成功,其他值:失败。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg: string
/**
* Ocr 文字涉政、敏感评分,分值为0到100。
*/
Confidence: number
/**
* Ocr 文字涉政、敏感结果建议,取值范围:
pass。
review。
block。
*/
Suggestion: string
/**
* Ocr 文字有涉政、敏感嫌疑的视频片段列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
SegmentSet: Array<VodOcrTextSegmentItem>
}
/**
* 识别出人脸对应的候选人。
*/
export interface Candidate {
/**
* 识别出人脸对应的候选人数组。当前返回相似度最高的候选人。
*/
Name: string
/**
* 相似度,0-100之间。
*/
Confidence: number
}
/**
* 暴恐识别结果。
*/
export interface TerrorismResult {
/**
* 该识别场景的错误码:
0表示成功,
-1表示系统错误,
-2表示引擎错误,
-1400表示图片解码失败。
*/
Code: number
/**
* 错误码描述信息。
*/
Msg: string
/**
* 识别场景的审核结论:
PASS:正常
REVIEW:疑似
BLOCK:违规
*/
Suggestion: string
/**
* 图像涉恐的分数,0-100之间,分数越高涉恐几率越大。
Type为LABEL时:
0到86,Suggestion建议为PASS
86到91,Suggestion建议为REVIEW
91到100,Suggestion建议为BLOCK
Type为FACE时:
0到55,Suggestion建议为PASS
55到60,Suggestion建议为REVIEW
60到100,Suggestion建议为BLOCK
*/
Confidence: number
/**
* Type取值为‘FACE’时,人脸识别的结果列表。基于图片中实际检测到的人脸数,返回数组最大值不超过5个。
*/
FaceResults: Array<FaceResult>
/**
* 暴恐识别返回的详细标签后期开放。
*/
AdvancedInfo: string
/**
* 取值'LABEL' 或‘FACE’,LABEL表示结论和置信度来自标签分类,FACE表示结论和置信度来自人脸识别。
*/
Type: string
}
/**
* 内容审核 Asr 文字鉴政、敏感任务结果类型
*/
export interface VodPoliticalAsrReviewResult {
/**
* 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
*/
Status: string
/**
* 错误码,0:成功,其他值:失败。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg: string
/**
* 嫌疑片段审核结果建议,取值范围:
pass。
review。
block。
Asr 文字涉政、敏感评分,分值为0到100。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* Asr 文字涉政、敏感结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* Asr 文字有涉政、敏感嫌疑的视频片段列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
SegmentSet: Array<VodAsrTextSegmentItem>
}
/**
* VideoModeration返回参数结构体
*/
export interface VideoModerationResponse {
/**
* 视频审核任务ID
*/
VodTaskId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 媒体文件元信息。
*/
export interface VodMetaData {
/**
* 上传的媒体文件大小(视频为 HLS 时,大小是 m3u8 和 ts 文件大小的总和),单位:字节。
注意:此字段可能返回 null,表示取不到有效值。
*/
Size: number
/**
* 容器类型,例如 m4a,mp4 等。
注意:此字段可能返回 null,表示取不到有效值。
*/
Container: string
/**
* 视频流码率平均值与音频流码率平均值之和,单位:bps。
注意:此字段可能返回 null,表示取不到有效值。
*/
Bitrate: number
/**
* 视频流高度的最大值,单位:px。
注意:此字段可能返回 null,表示取不到有效值。
*/
Height: number
/**
* 视频流宽度的最大值,单位:px。
注意:此字段可能返回 null,表示取不到有效值。
*/
Width: number
/**
* 视频时长,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
Duration: number
/**
* 视频拍摄时的选择角度,单位:度。
注意:此字段可能返回 null,表示取不到有效值。
*/
Rotate: number
/**
* 视频流信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
VideoStreamSet: Array<VodVideoStreamItem>
/**
* 音频流信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
AudioStreamSet: Array<VodAudioStreamItem>
/**
* 视频时长,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
VideoDuration: number
/**
* 音频时长,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
AudioDuration: number
}
/**
* ImageModeration返回参数结构体
*/
export interface ImageModerationResponse {
/**
* 识别场景的审核结论:
PASS:正常
REVIEW:疑似
BLOCK:违规
*/
Suggestion?: string
/**
* 色情识别结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
PornResult?: PornResult
/**
* 暴恐识别结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
TerrorismResult?: TerrorismResult
/**
* 政治敏感识别结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
PoliticsResult?: PoliticsResult
/**
* 透传字段,透传简单信息。
*/
Extra?: string
/**
* 恶心内容识别结果。
注意:此字段可能返回 null,表示取不到有效值。
*/
DisgustResult?: DisgustResult
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 文件视频流信息
*/
export interface VodVideoStreamItem {
/**
* 视频流的码率,单位:bps。
注意:此字段可能返回 null,表示取不到有效值。
*/
Bitrate: number
/**
* 视频流的高度,单位:px。
注意:此字段可能返回 null,表示取不到有效值。
*/
Height: number
/**
* 视频流的宽度,单位:px。
注意:此字段可能返回 null,表示取不到有效值。
*/
Width: number
/**
* 视频流的编码格式,例如 h264。
注意:此字段可能返回 null,表示取不到有效值。
*/
Codec: string
/**
* 帧率,单位:hz。
注意:此字段可能返回 null,表示取不到有效值。
*/
Fps: number
}
/**
* ImageModeration请求参数结构体
*/
export interface ImageModerationRequest {
/**
* 本次调用支持的识别场景,可选值如下:
1. PORN,即色情识别
2. TERRORISM,即暴恐识别
3. POLITICS,即政治敏感识别
支持多场景(Scenes)一起检测。例如,使用 Scenes=["PORN", "TERRORISM"],即对一张图片同时进行色情识别和暴恐识别。
*/
Scenes: Array<string>
/**
* 图片URL地址。
图片限制:
• 图片格式:PNG、JPG、JPEG。
• 图片大小:所下载图片经Base64编码后不超过4M。图片下载时间不超过3秒。
• 图片像素:大于50*50像素,否则影响识别效果;
• 长宽比:长边:短边<5;
接口响应时间会受到图片下载时间的影响,建议使用更可靠的存储服务,推荐将图片存储在腾讯云COS。
*/
ImageUrl?: string
/**
* 预留字段,后期用于展示更多识别信息。
*/
Config?: string
/**
* 透传字段,透传简单信息。
*/
Extra?: string
/**
* 图片经过base64编码的内容。最大不超过4M。与ImageUrl同时存在时优先使用ImageUrl字段。
*/
ImageBase64?: string
}
/**
* VideoModeration请求参数结构体
*/
export interface VideoModerationRequest {
/**
* 需要审核的视频的URL地址
*/
VideoUrl: string
/**
* 开发者标识
*/
DeveloperId?: string
/**
* 审核完成后回调地址
*/
CBUrl?: string
/**
* 透传字段,透传简单信息。
*/
Extra?: string
}
/**
* 内容审核鉴政任务结果类型
*/
export interface VodPoliticalReviewSegmentItem {
/**
* 嫌疑片段起始的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
StartTimeOffset: number
/**
* 嫌疑片段结束的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
EndTimeOffset: number
/**
* 嫌疑片段涉政分数。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* 嫌疑片段鉴政结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 涉政人物、违规图标名字。
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string
/**
* 嫌疑片段鉴政结果标签。
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 嫌疑图片 URL (图片不会永久存储,到达
PicUrlExpireTime 时间点后图片将被删除)。
注意:此字段可能返回 null,表示取不到有效值。
*/
Url: string
/**
* 嫌疑图片 URL 失效时间,使用 ISO 日期格式。
注意:此字段可能返回 null,表示取不到有效值。
*/
PicUrlExpireTimeStamp: number
/**
* 涉政人物、违规图标出现的区域坐标 (像素级),[x1, y1, x2, y2],即左上角坐标、右下角坐标。
注意:此字段可能返回 null,表示取不到有效值。
*/
AreaCoordSet: Array<number>
}
/**
* 内容审核鉴黄任务结果类型
*/
export interface VodPornReviewResult {
/**
* 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
*/
Status: string
/**
* 错误码,0:成功,其他值:失败。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg: string
/**
* 视频鉴黄评分,分值为0到100。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* 鉴黄结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 视频鉴黄结果标签,取值范围:
porn:色情。
sexy:性感。
vulgar:低俗。
intimacy:亲密行为。
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 有涉黄嫌疑的视频片段列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
SegmentSet: Array<VodPornReviewSegmentItem>
}
/**
* 恶心识别结果。
*/
export interface DisgustResult {
/**
* 该识别场景的错误码:
0表示成功,
-1表示系统错误,
-2表示引擎错误。
*/
Code: number
/**
* 错误码描述信息。
*/
Msg: string
/**
* 识别场景的审核结论:
PASS:正常
REVIEW:疑似
BLOCK:违规
*/
Suggestion: string
/**
* 图像恶心的分数,0-100之间,分数越高恶心几率越大。
*/
Confidence: number
}
/**
* 内容审核涉黄/暴恐嫌疑片段
*/
export interface VodPornReviewSegmentItem {
/**
* 嫌疑片段起始的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
StartTimeOffset: number
/**
* 嫌疑片段结束的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
EndTimeOffset: number
/**
* 嫌疑片段涉黄分数。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* 嫌疑片段鉴黄结果标签。
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 嫌疑片段鉴黄结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 嫌疑图片 URL (图片不会永久存储,到达
PicUrlExpireTime 时间点后图片将被删除)。
注意:此字段可能返回 null,表示取不到有效值。
*/
Url: string
/**
* 嫌疑图片 URL 失效时间,使用 ISO 日期格式。
注意:此字段可能返回 null,表示取不到有效值。
*/
PicUrlExpireTimeStamp: number
}
/**
* 涉政信息
*/
export interface VodPoliticalReviewResult {
/**
* 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
*/
Status: string
/**
* 错误码,0:成功,其他值:失败。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg: string
/**
* 视频涉政评分,分值为0到100。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* 涉政结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 视频鉴政结果标签,取值范围:
politician:政治人物。
violation_photo:违规图标。
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 有涉政嫌疑的视频片段列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
SegmentSet: Array<VodPoliticalReviewSegmentItem>
}
/**
* 文件音频流信息
*/
export interface VodAudioStreamItem {
/**
* 音频流的码率,单位:bps。
注意:此字段可能返回 null,表示取不到有效值。
*/
Bitrate: number
/**
* 音频流的采样率,单位:hz。
注意:此字段可能返回 null,表示取不到有效值。
*/
SamplingRate: number
/**
* 音频流的编码格式,例如 aac。
注意:此字段可能返回 null,表示取不到有效值。
*/
Codec: string
}
/**
* 内容审核 Ocr 文字审核嫌疑片段
*/
export interface VodOcrTextSegmentItem {
/**
* 嫌疑片段起始的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
StartTimeOffset: number
/**
* 嫌疑片段结束的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
EndTimeOffset: number
/**
* 嫌疑片段置信度。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* 嫌疑片段审核结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 嫌疑关键词列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
KeywordSet: Array<string>
/**
* 嫌疑文字出现的区域坐标 (像素级),[x1, y1, x2, y2],即左上角坐标、右下角坐标。
注意:此字段可能返回 null,表示取不到有效值。
*/
AreaCoordSet: Array<number>
}
/**
* 政治敏感识别结果。
*/
export interface PoliticsResult {
/**
* 该识别场景的错误码:
0表示成功,
-1表示系统错误,
-2表示引擎错误,
-1400表示图片解码失败,
-1401表示图片不符合规范。
*/
Code: number
/**
* 错误码描述信息。
*/
Msg: string
/**
* 识别场景的审核结论:
PASS:正常
REVIEW:疑似
BLOCK:违规
*/
Suggestion: string
/**
* 图像涉政的分数,0-100之间,分数越高涉政几率越大。
Type为DNA时:
0到75,Suggestion建议为PASS
75到90,Suggestion建议为REVIEW
90到100,Suggestion建议为BLOCK
Type为FACE时:
0到55,Suggestion建议为PASS
55到60,Suggestion建议为REVIEW
60到100,Suggestion建议为BLOCK
*/
Confidence: number
/**
* Type取值为‘FACE’时,人脸识别的结果列表。基于图片中实际检测到的人脸数,返回数组最大值不超过5个。
*/
FaceResults: Array<FaceResult>
/**
* 取值'DNA' 或‘FACE’。DNA表示结论和置信度来自图像指纹,FACE表示结论和置信度来自人脸识别。
*/
Type: string
/**
* 鉴政识别返回的详细标签后期开放。
*/
AdvancedInfo: string
}
/**
* 内容审核 Asr 文字审核嫌疑片段
*/
export interface VodAsrTextSegmentItem {
/**
* 嫌疑片段起始的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
StartTimeOffset: number
/**
* 嫌疑片段结束的偏移时间,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
EndTimeOffset: number
/**
* 嫌疑片段置信度。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* 嫌疑片段审核结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 嫌疑关键词列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
KeywordSet: Array<string>
}
/**
* 色情识别结果。
*/
export interface PornResult {
/**
* 该识别场景的错误码:
0表示成功,
-1表示系统错误,
-2表示引擎错误,
-1400表示图片解码失败。
*/
Code: number
/**
* 错误码描述信息。
*/
Msg: string
/**
* 识别场景的审核结论:
PASS:正常
REVIEW:疑似
BLOCK:违规
*/
Suggestion: string
/**
* 算法对于Suggestion的置信度,0-100之间,值越高,表示对于Suggestion越确定。
*/
Confidence: number
/**
* 预留字段,后期用于展示更多识别信息。
*/
AdvancedInfo: string
/**
* 取值'LABEL‘,LABEL表示结论和置信度来自标签分类。
*/
Type: string
}
/**
* DescribeVideoTask请求参数结构体
*/
export interface DescribeVideoTaskRequest {
/**
* 需要查询的视频审核的任务ID
*/
VodTaskId: string
}
/**
* 暴恐信息
*/
export interface VodTerrorismReviewResult {
/**
* 视频暴恐评分,分值为0到100。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* 暴恐结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 视频暴恐结果标签,取值范围:
guns:武器枪支。
crowd:人群聚集。
police:警察部队。
bloody:血腥画面。
banners:暴恐旗帜。
militant:武装分子。
explosion:爆炸火灾。
terrorists:暴恐人物。
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
*/
Status: string
/**
* 错误码,0:成功,其他值:失败。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg: string
/**
* 有暴恐嫌疑的视频片段列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
SegmentSet: Array<VodPornReviewSegmentItem>
}
/**
* 人脸识别结果。
*/
export interface FaceResult {
/**
* 检测出的人脸框位置。
*/
FaceRect: FaceRect
/**
* 候选人列表。当前返回相似度最高的候选人。
*/
Candidates: Array<Candidate>
}
/**
* Asr 文字涉黄信息
*/
export interface VodPornAsrReviewResult {
/**
* 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
*/
Status: string
/**
* 错误码,0:成功,其他值:失败。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg: string
/**
* Asr 文字涉黄评分,分值为0到100。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* Asr 文字涉黄结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* Asr 文字有涉黄嫌疑的视频片段列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
SegmentSet: Array<VodAsrTextSegmentItem>
}
/**
* DescribeVideoTask返回参数结构体
*/
export interface DescribeVideoTaskResponse {
/**
* 任务状态,取值:
WAITING:等待中;
PROCESSING:处理中;
FINISH:已完成。
*/
Status?: string
/**
* 任务开始执行的时间,采用 ISO 日期格式。
*/
BeginProcessTime?: string
/**
* 任务执行完毕的时间,采用 ISO 日期格式。
*/
FinishTime?: string
/**
* 视频内容审核智能画面鉴黄任务的查询结果。
*/
PornResult?: VodPornReviewResult
/**
* 视频内容审核智能画面鉴恐任务的查询结果。
*/
TerrorismResult?: VodTerrorismReviewResult
/**
* 视频内容审核智能画面鉴政任务的查询结果。
*/
PoliticalResult?: VodPoliticalReviewResult
/**
* 视频内容审核 Ocr 文字鉴政任务的查询结果。
*/
PoliticalOcrResult?: VodPoliticalOcrReviewResult
/**
* 视频内容审核 Asr 文字鉴黄任务的查询结果。
*/
PornAsrResult?: VodPornAsrReviewResult
/**
* 视频内容审核 Asr 文字鉴政任务的查询结果。
*/
PoliticalAsrResult?: VodPoliticalAsrReviewResult
/**
* 视频内容审核 Ocr 文字鉴黄任务的查询结果。
*/
PornOcrResult?: VodPornOcrResult
/**
* 原始视频的元信息。
*/
MetaData?: VodMetaData
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 识别出的人脸在图片中的位置。
*/
export interface FaceRect {
/**
* 人脸区域左上角横坐标。
*/
X: number
/**
* 人脸区域左上角纵坐标。
*/
Y: number
/**
* 人脸区域宽度。
*/
Width: number
/**
* 人脸区域高度。
*/
Height: number
}
/**
* 内容审核 Ocr 文字鉴黄任务结果类型
*/
export interface VodPornOcrResult {
/**
* 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
*/
Status: string
/**
* 错误码,0:成功,其他值:失败。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* 错误信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg: string
/**
* Ocr 文字涉黄评分,分值为0到100。
注意:此字段可能返回 null,表示取不到有效值。
*/
Confidence: number
/**
* Ocr 文字涉黄结果建议,取值范围:
pass。
review。
block。
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* Ocr 文字有涉黄嫌疑的视频片段列表。
注意:此字段可能返回 null,表示取不到有效值。
*/
SegmentSet: Array<VodOcrTextSegmentItem>
} | the_stack |
import type { AlignType, Point, TableColumn } from '@yozora/ast'
import { TableCellType, TableRowType, TableType } from '@yozora/ast'
import { AsciiCodePoint, isWhitespaceCharacter } from '@yozora/character'
import type {
IMatchBlockHookCreator,
IPhrasingContentLine,
IResultOfEatAndInterruptPreviousSibling,
IResultOfEatLazyContinuationText,
IResultOfEatOpener,
IYastBlockToken,
} from '@yozora/core-tokenizer'
import { calcEndPoint, calcStartPoint } from '@yozora/core-tokenizer'
import type { ITableCellToken, ITableRowToken, IThis, IToken, T } from './types'
/**
* A table is an arrangement of data with rows and columns, consisting of
* a single header row, a delimiter row separating the header from the data,
* and zero or more data rows.
*
* Each row consists of cells containing arbitrary text, in which inlines
* are parsed, separated by pipes (|). A leading and trailing pipe is also
* recommended for clarity of reading, and if there’s otherwise parsing
* ambiguity. Spaces between pipes and cell content are trimmed. Block-level
* elements cannot be inserted in a table.
*
* @see https://github.github.com/gfm/#table
* @see https://github.com/syntax-tree/mdast#tablerow
* @see https://github.com/syntax-tree/mdast#tablecell
*/
export const match: IMatchBlockHookCreator<T, IToken, IThis> = function (api) {
return {
isContainingBlock: false,
eatOpener,
eatAndInterruptPreviousSibling,
eatLazyContinuationText,
}
function eatOpener(): IResultOfEatOpener<T, IToken> {
return null
}
function eatAndInterruptPreviousSibling(
line: Readonly<IPhrasingContentLine>,
prevSiblingToken: Readonly<IYastBlockToken>,
): IResultOfEatAndInterruptPreviousSibling<T, IToken> {
/**
* Four spaces is too much
* @see https://github.github.com/gfm/#example-57
*/
if (line.countOfPrecedeSpaces >= 4) return null
const { nodePoints, endIndex, firstNonWhitespaceIndex } = line
if (firstNonWhitespaceIndex >= endIndex) return null
const columns: TableColumn[] = []
/**
* eat leading optional pipe
*/
let c = nodePoints[firstNonWhitespaceIndex].codePoint
let cIndex =
c === AsciiCodePoint.VERTICAL_SLASH ? firstNonWhitespaceIndex + 1 : firstNonWhitespaceIndex
for (; cIndex < endIndex; ) {
for (; cIndex < endIndex; ++cIndex) {
c = nodePoints[cIndex].codePoint
if (!isWhitespaceCharacter(c)) break
}
if (cIndex >= endIndex) break
// eat left optional colon
let leftColon = false
if (c === AsciiCodePoint.COLON) {
leftColon = true
cIndex += 1
}
let hyphenCount = 0
for (; cIndex < endIndex; ++cIndex) {
c = nodePoints[cIndex].codePoint
if (c !== AsciiCodePoint.MINUS_SIGN) break
hyphenCount += 1
}
// hyphen must be exist
if (hyphenCount <= 0) return null
// eat right optional colon
let rightColon = false
if (cIndex < endIndex && c === AsciiCodePoint.COLON) {
rightColon = true
cIndex += 1
}
// eating next pipe
for (; cIndex < endIndex; ++cIndex) {
c = nodePoints[cIndex].codePoint
if (isWhitespaceCharacter(c)) continue
if (c === AsciiCodePoint.VERTICAL_SLASH) {
cIndex += 1
break
}
// There are other non-white space characters
return null
}
let align: AlignType = null
if (leftColon && rightColon) align = 'center'
else if (leftColon) align = 'left'
else if (rightColon) align = 'right'
const column: TableColumn = { align }
columns.push(column)
}
if (columns.length <= 0) return null
const lines = api.extractPhrasingLines(prevSiblingToken)
if (lines == null || lines.length < 1) return null
/**
* The header row must match the delimiter row in the number of cells.
* If not, a table will not be recognized
* @see https://github.github.com/gfm/#example-203
*/
let cellCount = 0,
hasNonWhitespaceBeforePipe = false
const previousLine = lines[lines.length - 1]
for (let pIndex = previousLine.startIndex; pIndex < previousLine.endIndex; ++pIndex) {
const p = nodePoints[pIndex]
if (isWhitespaceCharacter(p.codePoint)) continue
if (p.codePoint === AsciiCodePoint.VERTICAL_SLASH) {
if (hasNonWhitespaceBeforePipe || cellCount > 0) cellCount += 1
hasNonWhitespaceBeforePipe = false
continue
}
hasNonWhitespaceBeforePipe = true
/**
* Include a pipe in a cell’s content by escaping it,
* including inside other inline spans
*/
if (p.codePoint === AsciiCodePoint.BACKSLASH) pIndex += 1
}
if (hasNonWhitespaceBeforePipe && columns.length > 1) cellCount += 1
if (cellCount !== columns.length) return null
const row = calcTableRow(previousLine, columns)
const nextIndex = endIndex
const token: IToken = {
nodeType: TableType,
position: {
start: calcStartPoint(previousLine.nodePoints, previousLine.startIndex),
end: calcEndPoint(nodePoints, nextIndex - 1),
},
columns,
rows: [row],
}
return {
token,
nextIndex,
remainingSibling: api.rollbackPhrasingLines(
lines.slice(0, lines.length - 1),
prevSiblingToken,
),
}
}
function eatLazyContinuationText(
line: Readonly<IPhrasingContentLine>,
token: IToken,
): IResultOfEatLazyContinuationText {
if (line.firstNonWhitespaceIndex >= line.endIndex) {
return { status: 'notMatched' }
}
const row = calcTableRow(line, token.columns)
if (row == null) return { status: 'notMatched' }
token.rows.push(row)
return { status: 'opening', nextIndex: line.endIndex }
}
// process table row
function calcTableRow(line: IPhrasingContentLine, columns: TableColumn[]): ITableRowToken {
const { nodePoints, startIndex, endIndex, firstNonWhitespaceIndex } = line
// eat leading pipe
let p = nodePoints[firstNonWhitespaceIndex]
let i =
p.codePoint === AsciiCodePoint.VERTICAL_SLASH
? firstNonWhitespaceIndex + 1
: firstNonWhitespaceIndex
// eat table cells
const cells: ITableCellToken[] = []
for (; i < endIndex; i += 1) {
/**
* Spaces between pipes and cell content are trimmed
*/
for (; i < endIndex; ++i) {
p = nodePoints[i]
if (!isWhitespaceCharacter(p.codePoint)) break
}
// Start point of the table-cell.
const startPoint: Point =
i < endIndex ? calcStartPoint(nodePoints, i) : calcEndPoint(nodePoints, endIndex - 1)
// Eating cell contents.
const cellStartIndex = i,
cellFirstNonWhitespaceIndex = i
for (; i < endIndex; ++i) {
p = nodePoints[i]
/**
* Include a pipe in a cell’s content by escaping it,
* including inside other inline spans
*/
if (p.codePoint === AsciiCodePoint.BACKSLASH) {
i += 1
continue
}
// pipe are boundary character
if (p.codePoint === AsciiCodePoint.VERTICAL_SLASH) break
}
let cellEndIndex = i
for (; cellEndIndex > cellStartIndex; --cellEndIndex) {
const p = nodePoints[cellEndIndex - 1]
if (!isWhitespaceCharacter(p.codePoint)) break
}
// End point of the table-cell
const endPoint: Point = calcEndPoint(nodePoints, i - 1)
const lines: IPhrasingContentLine[] =
cellFirstNonWhitespaceIndex >= cellEndIndex
? []
: [
{
nodePoints,
startIndex: cellStartIndex,
endIndex: cellEndIndex,
firstNonWhitespaceIndex: cellFirstNonWhitespaceIndex,
countOfPrecedeSpaces: cellFirstNonWhitespaceIndex - cellStartIndex,
},
]
const cell: ITableCellToken = {
nodeType: TableCellType,
position: { start: startPoint, end: endPoint },
lines: lines,
}
cells.push(cell)
/**
* If there are greater, the excess is ignored
* @see https://github.github.com/gfm/#example-204
*/
if (cells.length >= columns.length) break
}
// Start point of the table-row
const startPoint: Point = calcStartPoint(nodePoints, startIndex)
// End point of the table-row
const endPoint: Point = calcEndPoint(nodePoints, endIndex - 1)
/**
* The remainder of the table’s rows may vary in the number of cells.
* If there are a number of cells fewer than the number of cells in
* the header row, empty cells are inserted. If there are greater,
* the excess is ignored
* @see https://github.github.com/gfm/#example-204
*/
for (let c = cells.length; c < columns.length; ++c) {
const cell: ITableCellToken = {
nodeType: TableCellType,
position: { start: { ...endPoint }, end: { ...endPoint } },
lines: [],
}
cells.push(cell)
}
const row: ITableRowToken = {
nodeType: TableRowType,
position: { start: startPoint, end: endPoint },
cells,
}
return row
}
}
/**
* Find delimiter row
*
* The delimiter row consists of cells whose only content are
* hyphens (-), and optionally, a leading or trailing colon (:),
* or both, to indicate left, right, or center alignment respectively.
* @see https://github.github.com/gfm/#delimiter-row
*/
// function calcTableColumn(
// nodePoints: ReadonlyArray<INodePoint>,
// currentLine: IPhrasingContentLine,
// previousLine: IPhrasingContentLine,
// ): TableColumn[] | null {
// /**
// * The previous line of the delimiter line must not be blank line
// */
// if (previousLine.firstNonWhitespaceIndex >= previousLine.endIndex) {
// return null
// }
// /**
// * Four spaces is too much
// * @see https://github.github.com/gfm/#example-57
// */
// if (currentLine.firstNonWhitespaceIndex - currentLine.startIndex >= 4) return null
// const columns: TableColumn[] = []
// /**
// * eat leading optional pipe
// */
// let p = nodePoints[currentLine.firstNonWhitespaceIndex]
// let cIndex =
// p.codePoint === AsciiCodePoint.VERTICAL_SLASH
// ? currentLine.firstNonWhitespaceIndex + 1
// : currentLine.firstNonWhitespaceIndex
// for (; cIndex < currentLine.endIndex; ) {
// for (; cIndex < currentLine.endIndex; ++cIndex) {
// p = nodePoints[cIndex]
// if (!isWhitespaceCharacter(p.codePoint)) break
// }
// if (cIndex >= currentLine.endIndex) break
// // eat left optional colon
// let leftColon = false
// if (p.codePoint === AsciiCodePoint.COLON) {
// leftColon = true
// cIndex += 1
// }
// let hyphenCount = 0
// for (; cIndex < currentLine.endIndex; ++cIndex) {
// p = nodePoints[cIndex]
// if (p.codePoint !== AsciiCodePoint.MINUS_SIGN) break
// hyphenCount += 1
// }
// // hyphen must be exist
// if (hyphenCount <= 0) return null
// // eat right optional colon
// let rightColon = false
// if (cIndex < currentLine.endIndex && p.codePoint === AsciiCodePoint.COLON) {
// rightColon = true
// cIndex += 1
// }
// // eating next pipe
// for (; cIndex < currentLine.endIndex; ++cIndex) {
// p = nodePoints[cIndex]
// if (isWhitespaceCharacter(p.codePoint)) continue
// if (p.codePoint === AsciiCodePoint.VERTICAL_SLASH) {
// cIndex += 1
// break
// }
// // There are other non-white space characters
// return null
// }
// let align: AlignType = null
// if (leftColon && rightColon) align = 'center'
// else if (leftColon) align = 'left'
// else if (rightColon) align = 'right'
// const column: TableColumn = { align }
// columns.push(column)
// }
// if (columns.length <= 0) return null
// /**
// * The header row must match the delimiter row in the number of cells.
// * If not, a table will not be recognized
// * @see https://github.github.com/gfm/#example-203
// */
// let cellCount = 0,
// hasNonWhitespaceBeforePipe = false
// for (let pIndex = previousLine.startIndex; pIndex < previousLine.endIndex; ++pIndex) {
// const p = nodePoints[pIndex]
// if (isWhitespaceCharacter(p.codePoint)) continue
// if (p.codePoint === AsciiCodePoint.VERTICAL_SLASH) {
// if (hasNonWhitespaceBeforePipe || cellCount > 0) cellCount += 1
// hasNonWhitespaceBeforePipe = false
// continue
// }
// hasNonWhitespaceBeforePipe = true
// /**
// * Include a pipe in a cell’s content by escaping it,
// * including inside other inline spans
// */
// if (p.codePoint === AsciiCodePoint.BACKSLASH) pIndex += 1
// }
// if (hasNonWhitespaceBeforePipe && columns.length > 1) cellCount += 1
// if (cellCount !== columns.length) return null
// // Successfully matched to a legal table delimiter line
// return columns
// } | the_stack |
import * as THREE from 'three';
// @ts-ignore
import julian from 'julian';
import Stats from 'three/examples/jsm/libs/stats.module';
import {
BloomEffect,
EffectComposer,
EffectPass,
RenderPass,
// @ts-ignore
} from 'postprocessing';
import type { Scene, Object3D, Vector3, WebGL1Renderer } from 'three';
import Camera from './Camera';
import { KeplerParticles } from './KeplerParticles';
import { NaturalSatellites } from './EphemPresets';
import { ShapeObject } from './ShapeObject';
import { Skybox } from './Skybox';
import { SpaceObject } from './SpaceObject';
import { SphereObject } from './SphereObject';
import { StaticParticles } from './StaticParticles';
import { Stars } from './Stars';
import { getDefaultBasePath } from './util';
import { setScaleFactor, rescaleArray } from './Scale';
import type { Coordinate3d } from './Coordinates';
// TODO(ian): Make this an interface.
export interface SimulationObject {
update: (jd: number, force: boolean) => void;
get3jsObjects(): THREE.Object3D[];
getId(): string;
}
interface CameraOptions {
initialPosition?: Coordinate3d;
enableDrift?: boolean;
}
interface DebugOptions {
showAxes?: boolean;
showGrid?: boolean;
showStats?: boolean;
}
interface SpacekitOptions {
basePath: string;
startDate?: Date;
jd?: number;
jdDelta?: number;
jdPerSecond?: number;
unitsPerAu?: number;
startPaused?: boolean;
maxNumParticles?: number;
particleTextureUrl?: string;
particleDefaultSize?: number;
camera?: CameraOptions;
debug?: DebugOptions;
}
export interface SimulationContext {
simulation: Simulation;
options: SpacekitOptions;
objects: {
renderer: WebGL1Renderer;
camera: Camera;
scene: Scene;
particles: KeplerParticles;
composer?: EffectComposer;
};
container: {
width: number;
height: number;
};
}
/**
* The main entrypoint of a visualization.
*
* This class wraps a THREE.js scene, controls, skybox, etc in an animated
* Simulation.
*
* @example
* ```
* const sim = new Spacekit.Simulation(document.getElementById('my-container'), {
* basePath: '../path/to/assets',
* startDate: Date.now(),
* jd: 0.0,
* jdDelta: 10.0,
* jdPerSecond: 100.0, // overrides jdDelta
* startPaused: false,
* unitsPerAu: 1.0,
* maxNumParticles: 2**16,
* camera: {
* initialPosition: [0, -10, 5],
* enableDrift: false,
* },
* debug: {
* showAxes: false,
* showGrid: false,
* showStats: false,
* },
* });
* ```
*/
export class Simulation {
public onTick?: () => void;
private simulationElt: HTMLCanvasElement;
private options: SpacekitOptions;
private jd: number;
private jdDelta?: number;
private jdPerSecond: number;
private isPaused: boolean;
private enableCameraDrift: boolean;
private cameraDefaultPos: Coordinate3d;
private camera: Camera;
private useLightSources: boolean;
private lightPosition?: Vector3;
private subscribedObjects: Record<string, SimulationObject>;
private particles: KeplerParticles;
private stats?: Stats;
private fps: number;
private lastUpdatedTime: number;
private lastStaticCameraUpdateTime: number;
private lastResizeUpdateTime: number;
private renderEnabled: boolean;
private initialRenderComplete: boolean;
private scene: Scene;
private renderer: WebGL1Renderer;
private composer?: EffectComposer;
/**
* @param {HTMLCanvasElement} simulationElt The container for this simulation.
* @param {Object} options for simulation
* @param {String} options.basePath Path to simulation assets and data
* @param {Date} options.startDate The start date and time for this
* simulation.
* @param {Number} options.jd The JD date of this simulation.
* Defaults to 0
* @param {Number} options.jdDelta The number of JD to add every tick of
* the simulation.
* @param {Number} options.jdPerSecond The number of jd to add every second.
* Use this instead of `jdDelta` for constant motion that does not vary with
* framerate. Defaults to 100.
* @param {Number} options.unitsPerAu The number of "position" units in the
* simulation that represent an AU. This is an optional setting that you may
* use if the default (1 unit = 1 AU) is too small for your simulation (e.g.
* if you are representing a planetary system). Depending on your graphics
* card, you may begin to notice inaccuracies at fractional scales of GL
* units, so it becomes necessary to scale the whole visualization. Defaults
* to 1.0.
* @param {boolean} options.startPaused Whether the simulation should start
* in a paused state.
* @param {Number} options.maxNumParticles The maximum number of particles in
* the visualization. Try choosing a number that is larger than your
* particles, but not too much larger. It's usually good enough to choose the
* next highest power of 2. If you're not showing many particles (tens of
* thousands+), you don't need to worry about this.
* @param {String} options.particleTextureUrl The texture for the default
* particle system.
* @param {Number} options.particleDefaultSize The default size for the
* particle system.
* @param {Object} options.camera Options for camera
* @param {Array.<Number>} options.camera.initialPosition Initial X, Y, Z
* coordinates of the camera. Defaults to [0, -10, 5].
* @param {boolean} options.camera.enableDrift Set true to have the camera
* float around slightly. False by default.
* @param {Object} options.debug Options dictating debug state.
* @param {boolean} options.debug.showAxes Show X, Y, and Z axes
* @param {boolean} options.debug.showGrid Show grid on XY plane
* @param {boolean} options.debug.showStats Show FPS and other stats
* (requires stats.js).
*/
constructor(simulationElt: HTMLCanvasElement, options: SpacekitOptions) {
this.simulationElt = simulationElt;
this.options = options || {};
this.options.basePath = this.options.basePath || getDefaultBasePath();
this.jd =
typeof this.options.jd === 'undefined'
? Number(julian(this.options.startDate || new Date()))
: this.options.jd;
this.jdDelta = this.options.jdDelta;
this.jdPerSecond = this.options.jdPerSecond || 100;
this.isPaused = options.startPaused || false;
this.onTick = undefined;
this.enableCameraDrift = false;
this.cameraDefaultPos = rescaleArray([0, -10, 5]);
if (this.options.camera) {
this.enableCameraDrift = !!this.options.camera.enableDrift;
if (this.options.camera.initialPosition) {
this.cameraDefaultPos = rescaleArray(
this.options.camera.initialPosition,
);
}
}
this.useLightSources = false;
this.lightPosition = undefined;
this.subscribedObjects = {};
// This makes controls.lookAt and other objects treat the positive Z axis
// as "up" direction.
THREE.Object3D.DefaultUp = new THREE.Vector3(0, 0, 1);
// Scale
if (this.options.unitsPerAu) {
setScaleFactor(this.options.unitsPerAu);
}
// stats.js panel
this.stats = undefined;
this.fps = 1;
this.lastUpdatedTime = Date.now();
this.lastStaticCameraUpdateTime = Date.now();
this.lastResizeUpdateTime = Date.now();
// Rendering
this.renderEnabled = true;
this.initialRenderComplete = false;
this.animate = this.animate.bind(this);
this.renderer = this.initRenderer();
this.scene = new THREE.Scene();
this.camera = new Camera(this.getContext());
this.composer = null;
// Orbit particle system must be initialized after scene is created and
// scale is set.
this.particles = new KeplerParticles(
{
textureUrl:
this.options.particleTextureUrl ||
'{{assets}}/sprites/smallparticle.png',
jd: this.jd,
maxNumParticles: this.options.maxNumParticles,
defaultSize: this.options.particleDefaultSize,
},
this,
);
this.init();
this.animate();
}
/**
* @private
*/
private init() {
// Camera
this.camera
.get3jsCamera()
.position.set(
this.cameraDefaultPos[0],
this.cameraDefaultPos[1],
this.cameraDefaultPos[2],
);
// window.cam = camera.get3jsCamera();
// Events
this.simulationElt.onmousedown = this.simulationElt.ontouchstart = () => {
// When user begins interacting with the visualization, disable camera
// drift.
this.enableCameraDrift = false;
};
(() => {
let listenToCameraEvents = false;
this.camera.get3jsCameraControls().addEventListener('change', () => {
// Camera will send a few initial events - ignore these.
if (listenToCameraEvents) {
this.staticForcedUpdate();
}
});
setTimeout(() => {
// Send an update when the visualization is done loading.
this.staticForcedUpdate();
listenToCameraEvents = true;
this.initialRenderComplete = true;
}, 0);
})();
this.simulationElt.addEventListener('resize', () => {
this.resizeUpdate();
});
window.addEventListener('resize', () => {
this.resizeUpdate();
});
// Helper
if (this.options.debug) {
if (this.options.debug.showGrid) {
const gridHelper = new THREE.GridHelper(undefined, undefined);
gridHelper.geometry.rotateX(Math.PI / 2);
this.scene.add(gridHelper);
}
if (this.options.debug.showAxes) {
this.scene.add(new THREE.AxesHelper(0.5));
}
if (this.options.debug.showStats) {
this.stats = new (Stats as any)();
this.stats!.showPanel(0);
this.simulationElt.appendChild(this.stats!.dom);
}
}
// Set up effect composer, etc.
this.initPasses();
}
/**
* @private
*/
private initRenderer(): THREE.WebGL1Renderer {
// TODO(ian): Upgrade to webgl 2. See https://discourse.threejs.org/t/webgl2-breaking-custom-shader/16603/4
const renderer = new THREE.WebGL1Renderer({
antialias: true,
//logarithmicDepthBuffer: true,
});
console.info(
'Max texture resolution:',
renderer.capabilities.maxTextureSize,
);
const maxPrecision = renderer.capabilities.getMaxPrecision('highp');
if (maxPrecision !== 'highp') {
console.warn(
`Shader maximum precision is "${maxPrecision}", GPU rendering may not be accurate.`,
);
}
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(
this.simulationElt.offsetWidth,
this.simulationElt.offsetHeight,
);
this.simulationElt.appendChild(renderer.domElement);
return renderer;
}
/**
* @private
*/
private initPasses() {
//const smaaEffect = new SMAAEffect(assets.get("smaa-search"), assets.get("smaa-area"));
//smaaEffect.colorEdgesMaterial.setEdgeDetectionThreshold(0.065);
const camera = this.camera.get3jsCamera();
/*
const sunGeometry = new THREE.SphereBufferGeometry(
rescaleNumber(0.004),
16,
);
const sunMaterial = new THREE.MeshBasicMaterial({
color: 0xffddaa,
transparent: true,
depthWrite: false,
fog: false,
});
const sun = new THREE.Mesh(sunGeometry, sunMaterial);
const rescaled = rescaleArray([0.1, 0.1, 0.0]);
sun.position.set(rescaled[0], rescaled[1], rescaled[2]);
sun.updateMatrix();
sun.updateMatrixWorld();
const godRaysEffect = new GodRaysEffect(camera, sun, {
color: 0xfff5f2,
blur: false,
});
*/
//godRaysEffect.dithering = true;
const bloomEffect = new BloomEffect(this.scene, camera, {
width: 240,
height: 240,
luminanceThreshold: 0.2,
});
bloomEffect.inverted = true;
bloomEffect.blendMode.opacity.value = 2.3;
const renderPass = new RenderPass(this.scene, camera);
renderPass.renderToScreen = false;
const effectPass = new EffectPass(
camera,
/*smaaEffect, godRaysEffect*/ bloomEffect,
);
effectPass.renderToScreen = true;
const composer = new EffectComposer(this.renderer);
composer.addPass(renderPass);
composer.addPass(effectPass);
this.composer = composer;
}
/**
* @private
*/
private update(force = false) {
for (const objId in this.subscribedObjects) {
if (this.subscribedObjects.hasOwnProperty(objId)) {
this.subscribedObjects[objId].update(this.jd, force);
}
}
}
/**
* Performs a forced update of all elements in the view. This is used for when the system isn't animating but the
* objects need to update their data to properly capture things like updated label positions.
* @private
*/
private staticForcedUpdate() {
if (this.isPaused) {
const now = Date.now();
const timeDelta = now - this.lastStaticCameraUpdateTime;
const threshold = 30;
// TODO(ian): Also do this based on viewport change. Otherwise things like scrolling don't work well.
if (timeDelta > threshold) {
this.update(true /* force */);
this.lastStaticCameraUpdateTime = now;
}
}
}
/**
* @private
* Updates the size of the control and forces a refresh of components whenever the control is being resized.
*/
private resizeUpdate() {
const now = Date.now();
const timeDelta = now - this.lastResizeUpdateTime;
const threshold = 30;
if (timeDelta > threshold) {
const newWidth = this.simulationElt.offsetWidth;
const newHeight = this.simulationElt.offsetHeight;
if (newWidth === 0 && newHeight === 0) {
return;
}
const camera = this.camera.get3jsCamera();
camera.aspect = newWidth / newHeight;
camera.updateProjectionMatrix();
this.renderer.setSize(newWidth, newHeight);
this.staticForcedUpdate();
this.lastResizeUpdateTime = now;
}
}
/**
* @private
* TODO(ian): Move this into Camera
*/
private doCameraDrift() {
// Follow floating path around
const timer = 0.0001 * Date.now();
const pos = this.cameraDefaultPos;
const cam = this.camera.get3jsCamera();
cam.position.x = pos[0] + (pos[0] * (Math.cos(timer) + 1)) / 3;
cam.position.z = pos[2] + (pos[2] * (Math.sin(timer) + 1)) / 3;
}
/**
* @private
*/
private animate() {
if (!this.renderEnabled && this.initialRenderComplete) {
return;
}
window.requestAnimationFrame(this.animate);
if (this.stats) {
this.stats.begin();
}
if (!this.isPaused) {
if (this.jdDelta) {
this.jd += this.jdDelta;
} else {
// N jd per second
this.jd += this.jdPerSecond / this.fps;
}
const timeDelta = (Date.now() - this.lastUpdatedTime) / 1000;
this.lastUpdatedTime = Date.now();
this.fps = 1 / timeDelta || 1;
// Update objects in this simulation
this.update();
}
// Update camera drifting, if applicable
if (this.enableCameraDrift) {
this.doCameraDrift();
}
this.camera.update();
// Update three.js scene
this.renderer.render(this.scene, this.camera.get3jsCamera());
//this.composer.render(0.1);
if (this.onTick) {
this.onTick();
}
if (this.stats) {
this.stats.end();
}
}
/**
* Add a spacekit object (usually a SpaceObject) to the visualization.
* @see SpaceObject
* @param {Object} obj Object to add to visualization
* @param {boolean} noUpdate Set to true if object does not need to be
* animated.
*/
addObject(obj: SimulationObject, noUpdate: boolean = false) {
obj.get3jsObjects().map((x) => {
this.scene.add(x);
});
if (!noUpdate) {
// Call for updates as time passes.
const objId = obj.getId();
if (this.subscribedObjects[objId]) {
console.error(
`Object id is not unique: "${objId}". This could prevent objects from updating correctly.`,
);
}
this.subscribedObjects[objId] = obj;
}
}
/**
* Removes an object from the visualization.
* @param {Object} obj Object to remove
*/
removeObject(obj: SpaceObject) {
// TODO(ian): test this and avoid memory leaks...
obj.get3jsObjects().map((x) => {
this.scene.remove(x);
});
if (typeof obj.removalCleanup === 'function') {
obj.removalCleanup();
}
delete this.subscribedObjects[obj.getId()];
}
/**
* Shortcut for creating a new SpaceObject belonging to this visualization.
* Takes any SpaceObject arguments.
* @see SpaceObject
*/
// @ts-ignore
createObject(...args): SpaceObject {
// @ts-ignore
return new SpaceObject(...args, this);
}
/**
* Shortcut for creating a new ShapeObject belonging to this visualization.
* Takes any ShapeObject arguments.
* @see ShapeObject
*/
// @ts-ignore
createShape(...args): ShapeObject {
// @ts-ignore
return new ShapeObject(...args, this);
}
/**
* Shortcut for creating a new SphereOjbect belonging to this visualization.
* Takes any SphereObject arguments.
* @see SphereObject
*/
// @ts-ignore
createSphere(...args): SphereObject {
// @ts-ignore
return new SphereObject(...args, this);
}
/**
* Shortcut for creating a new StaticParticles object belonging to this visualization.
* Takes any StaticParticles arguments.
* @see SphereObject
*/
// @ts-ignore
createStaticParticles(...args): StaticParticles {
// @ts-ignore
return new StaticParticles(...args, this);
}
/**
* Shortcut for creating a new Skybox belonging to this visualization. Takes
* any Skybox arguments.
* @see Skybox
*/
// @ts-ignore
createSkybox(...args): Skybox {
// @ts-ignore
return new Skybox(...args, this);
}
/**
* Shortcut for creating a new Stars object belonging to this visualization.
* Takes any Stars arguments.
* @see Stars
*/
// @ts-ignore
createStars(...args): Stars {
if (args.length) {
// @ts-ignore
return new Stars(...args, this);
}
// No arguments supplied
return new Stars({}, this);
}
/**
* Creates an ambient light source. This will dimly light everything in the
* visualization.
* @param {Number} color Color of light, default 0x333333
*/
createAmbientLight(color: number = 0x333333) {
this.scene.add(new THREE.AmbientLight(color));
this.useLightSources = true;
}
/**
* Creates a light source. This will make the shape of your objects visible
* and provide some contrast.
* @param {Array.<Number>} pos Position of light source. Defaults to moving
* with camera.
* @param {Number} color Color of light, default 0xFFFFFF
*/
createLight(
pos: Coordinate3d | undefined = undefined,
color: number = 0xffffff,
) {
if (this.lightPosition) {
console.warn(
"Spacekit doesn't support more than one light source for SphereObjects",
);
}
this.lightPosition = new THREE.Vector3();
// Pointlight is for standard meshes created by ShapeObjects.
// TODO(ian): Remove this point light.
const pointLight = new THREE.PointLight();
if (typeof pos === 'undefined') {
// The light comes from the camera.
// FIXME(ian): This only affects the point source.
this.camera.get3jsCameraControls().addEventListener('change', () => {
this.lightPosition!.copy(this.camera.get3jsCamera().position);
pointLight.position.copy(this.camera.get3jsCamera().position);
});
} else {
const rescaled = rescaleArray(pos);
this.lightPosition.set(rescaled[0], rescaled[1], rescaled[2]);
pointLight.position.set(rescaled[0], rescaled[1], rescaled[2]);
}
this.scene.add(pointLight);
this.useLightSources = true;
}
getLightPosition(): Vector3 | undefined {
return this.lightPosition;
}
isUsingLightSources(): boolean {
return this.useLightSources;
}
/**
* Returns a promise that receives a NaturalSatellites object when it is
* resolved.
* @return {Promise<NaturalSatellites>} NaturalSatellites object that is
* ready to load.
*
* @see {NaturalSatellites}
*/
loadNaturalSatellites(): Promise<NaturalSatellites> {
return new NaturalSatellites(this).load();
}
/**
* Installs a scroll handler that only renders the visualization while it is
* in the user's viewport.
*
* The scroll handler currently binds to the window object only.
*/
renderOnlyInViewport() {
let previouslyInView = true;
const isInView = () => {
const rect = this.simulationElt.getBoundingClientRect();
const windowHeight =
window.innerHeight || document.documentElement.clientHeight;
const windowWidth =
window.innerWidth || document.documentElement.clientWidth;
const vertInView =
rect.top <= windowHeight && rect.top + rect.height >= 0;
const horInView = rect.left <= windowWidth && rect.left + rect.width >= 0;
return vertInView && horInView;
};
window.addEventListener('scroll', () => {
const inView = isInView();
if (previouslyInView && !inView) {
// Went out of view
this.renderEnabled = false;
previouslyInView = false;
} else if (!previouslyInView && inView) {
// Came into view
this.renderEnabled = true;
window.requestAnimationFrame(this.animate);
previouslyInView = true;
}
});
if (!isInView()) {
// Initial state is render enabled, so disable it if currently out of
// view.
this.renderEnabled = false;
previouslyInView = false;
}
}
/**
* Adjust camera position so that the object fits within the viewport. If
* applicable, this function will fit around the object's orbit.
* @param {SpaceObject} spaceObj Object to fit within viewport.
* @param {Number} offset Add some extra room in the viewport. Increase to be
* further zoomed out, decrease to be closer. Default 3.0.
*/
async zoomToFit(
spaceObj: SpaceObject,
offset: number = 3.0,
): Promise<boolean> {
const orbit = spaceObj.getOrbit();
const obj = orbit
? orbit.getOrbitShape()
: await spaceObj.getBoundingObject();
if (obj) {
this.doZoomToFit(obj, offset);
return true;
}
return false;
}
/**
* @private
* Perform the actual zoom to fit behavior.
* @param {Object3D} obj Three.js object to fit within viewport.
* @param {Number} offset Add some extra room in the viewport. Increase to be
* further zoomed out, decrease to be closer. Default 3.0.
*/
private doZoomToFit(obj: Object3D, offset: number) {
const boundingBox = new THREE.Box3();
boundingBox.setFromObject(obj);
const center = new THREE.Vector3();
boundingBox.getCenter(center);
const size = new THREE.Vector3();
boundingBox.getSize(size);
// Get the max side of the bounding box (fits to width OR height as needed)
const camera = this.camera.get3jsCamera();
const maxDim = Math.max(size.x, size.y, size.z);
const fov = camera.fov * (Math.PI / 180);
const cameraZ = Math.abs((maxDim / 2) * Math.tan(fov * 2)) * offset;
const objectWorldPosition = new THREE.Vector3();
obj.getWorldPosition(objectWorldPosition);
const directionVector = camera.position.sub(objectWorldPosition); // Get vector from camera to object
const unitDirectionVector = directionVector.normalize(); // Convert to unit vector
const newpos = unitDirectionVector.multiplyScalar(cameraZ);
camera.position.x = newpos.x;
camera.position.y = newpos.y;
camera.position.z = newpos.z;
camera.updateProjectionMatrix();
// Update default camera pos so if drift is on, camera will drift around
// its new position.
this.cameraDefaultPos = [newpos.x, newpos.y, newpos.z];
}
/**
* Run the animation
*/
start() {
this.lastUpdatedTime = Date.now();
this.isPaused = false;
}
/**
* Stop the animation
*/
stop() {
this.isPaused = true;
}
/**
* Gets the current JD date of the simulation
* @return {Number} JD date
*/
getJd(): number {
return this.jd;
}
/**
* Sets the JD date of the simulation.
* @param {Number} val JD date
*/
setJd(val: number) {
this.jd = val;
this.update(true);
}
/**
* Get a date object representing local date and time of the simulation.
* @return {Date} Date of simulation
*/
getDate(): Date {
return julian.toDate(this.jd);
}
/**
* Set the local date and time of the simulation.
* @param {Date} date Date of simulation
*/
setDate(date: Date) {
this.setJd(Number(julian(date)));
}
/**
* Get the JD per frame of the visualization.
*/
getJdDelta() {
if (!this.jdDelta) {
return this.jdPerSecond / this.fps;
}
return this.jdDelta;
}
/**
* Set the JD per frame of the visualization. This will override any
* existing "JD per second" setting.
* @param {Number} delta JD per frame
*/
setJdDelta(delta: number) {
this.jdDelta = delta;
}
/**
* Get the JD change per second of the visualization.
* @return {Number | undefined} JD per second, undefined if jd per second is
* not set.
*/
getJdPerSecond(): number | undefined {
if (this.jdDelta) {
// Jd per second can vary
return undefined;
}
return this.jdPerSecond;
}
/**
* Set the JD change per second of the visualization.
* @param {Number} x JD per second
*/
setJdPerSecond(x: number) {
// Delta overrides jd per second, so unset it.
this.jdDelta = undefined;
this.jdPerSecond = x;
}
/**
* Get an object that contains useful context for this visualization
* @return {Object} Context object
*/
getContext(): SimulationContext {
return {
simulation: this,
options: this.options,
objects: {
particles: this.particles,
camera: this.camera,
scene: this.scene,
renderer: this.renderer,
composer: this.composer,
},
container: {
width: this.simulationElt.offsetWidth,
height: this.simulationElt.offsetHeight,
},
};
}
/**
* Get the element containing this simulation
* @return {HTMLElement} The html container of this simulation
*/
getSimulationElement(): HTMLCanvasElement {
return this.simulationElt;
}
/**
* Get the Camera and CameraControls wrapper object
* @return {Camera} The Camera wrapper
*/
getViewer(): Camera {
return this.camera;
}
/**
* Get the three.js scene object
* @return {THREE.Scene} The THREE.js scene object
*/
getScene(): THREE.Scene {
return this.scene;
}
/**
* Get the three.js renderer
* @return {THREE.WebGL1Renderer} The THREE.js renderer
*/
getRenderer(): THREE.WebGL1Renderer {
return this.renderer;
}
/**
* Enable or disable camera drift.
* @param {boolean} driftOn True if you want the camera to float around a bit
*/
setCameraDrift(driftOn: boolean) {
this.enableCameraDrift = driftOn;
}
}
export default Simulation; | the_stack |
import { Buffer } from "buffer";
import { Vault, requestUrl } from "obsidian";
import { Queue } from "@fyears/tsqueue";
import chunk from "lodash/chunk";
import flatten from "lodash/flatten";
import { getReasonPhrase } from "http-status-codes";
import { RemoteItem, VALID_REQURL, WebdavConfig } from "./baseTypes";
import { decryptArrayBuffer, encryptArrayBuffer } from "./encrypt";
import { bufferToArrayBuffer, getPathFolder, mkdirpInVault } from "./misc";
import { log } from "./moreOnLog";
import type {
FileStat,
WebDAVClient,
RequestOptionsWithState,
Response,
ResponseDataDetailed,
} from "webdav/web";
import { getPatcher } from "webdav/web";
if (VALID_REQURL) {
getPatcher().patch(
"request",
async (
options: RequestOptionsWithState
): Promise<Response | ResponseDataDetailed<any>> => {
const transformedHeaders = { ...options.headers };
delete transformedHeaders["host"];
delete transformedHeaders["Host"];
delete transformedHeaders["content-length"];
delete transformedHeaders["Content-Length"];
const r = await requestUrl({
url: options.url,
method: options.method,
body: options.data as string | ArrayBuffer,
headers: transformedHeaders,
});
let r2: Response | ResponseDataDetailed<any> = undefined;
if (options.responseType === undefined) {
r2 = {
data: undefined,
status: r.status,
statusText: getReasonPhrase(r.status),
headers: r.headers,
};
} else if (options.responseType === "json") {
r2 = {
data: r.json,
status: r.status,
statusText: getReasonPhrase(r.status),
headers: r.headers,
};
} else if (options.responseType === "text") {
r2 = {
data: r.text,
status: r.status,
statusText: getReasonPhrase(r.status),
headers: r.headers,
};
} else if (options.responseType === "arraybuffer") {
r2 = {
data: r.arrayBuffer,
status: r.status,
statusText: getReasonPhrase(r.status),
headers: r.headers,
};
} else {
throw Error(
`do not know how to deal with responseType = ${options.responseType}`
);
}
return r2;
}
);
}
// getPatcher().patch("request", (options: any) => {
// // console.log("using fetch");
// const r = fetch(options.url, {
// method: options.method,
// body: options.data as any,
// headers: options.headers,
// signal: options.signal,
// })
// .then((rsp) => {
// if (options.responseType === undefined) {
// return Promise.all([undefined, rsp]);
// }
// if (options.responseType === "json") {
// return Promise.all([rsp.json(), rsp]);
// }
// if (options.responseType === "text") {
// return Promise.all([rsp.text(), rsp]);
// }
// if (options.responseType === "arraybuffer") {
// return Promise.all([rsp.arrayBuffer(), rsp]);
// }
// })
// .then(([d, r]) => {
// return {
// data: d,
// status: r.status,
// statusText: r.statusText,
// headers: r.headers,
// };
// });
// // console.log("using fetch");
// return r;
// });
import { AuthType, BufferLike, createClient } from "webdav/web";
export type { WebDAVClient } from "webdav/web";
export const DEFAULT_WEBDAV_CONFIG = {
address: "",
username: "",
password: "",
authType: "basic",
manualRecursive: false,
depth: "auto_unknown",
remoteBaseDir: "",
} as WebdavConfig;
const getWebdavPath = (fileOrFolderPath: string, remoteBaseDir: string) => {
let key = fileOrFolderPath;
if (fileOrFolderPath === "/" || fileOrFolderPath === "") {
// special
key = `/${remoteBaseDir}/`;
}
if (!fileOrFolderPath.startsWith("/")) {
key = `/${remoteBaseDir}/${fileOrFolderPath}`;
}
return key;
};
const getNormPath = (fileOrFolderPath: string, remoteBaseDir: string) => {
if (
!(
fileOrFolderPath === `/${remoteBaseDir}` ||
fileOrFolderPath.startsWith(`/${remoteBaseDir}/`)
)
) {
throw Error(
`"${fileOrFolderPath}" doesn't starts with "/${remoteBaseDir}/"`
);
}
// if (fileOrFolderPath.startsWith("/")) {
// return fileOrFolderPath.slice(1);
// }
return fileOrFolderPath.slice(`/${remoteBaseDir}/`.length);
};
const fromWebdavItemToRemoteItem = (x: FileStat, remoteBaseDir: string) => {
let key = getNormPath(x.filename, remoteBaseDir);
if (x.type === "directory" && !key.endsWith("/")) {
key = `${key}/`;
}
return {
key: key,
lastModified: Date.parse(x.lastmod).valueOf(),
size: x.size,
remoteType: "webdav",
etag: x.etag || undefined,
} as RemoteItem;
};
export class WrappedWebdavClient {
webdavConfig: WebdavConfig;
remoteBaseDir: string;
client: WebDAVClient;
vaultFolderExists: boolean;
saveUpdatedConfigFunc: () => Promise<any>;
constructor(
webdavConfig: WebdavConfig,
remoteBaseDir: string,
saveUpdatedConfigFunc: () => Promise<any>
) {
this.webdavConfig = webdavConfig;
this.remoteBaseDir = remoteBaseDir;
this.vaultFolderExists = false;
this.saveUpdatedConfigFunc = saveUpdatedConfigFunc;
}
init = async () => {
// init client if not inited
const headers = {
"Cache-Control": "no-cache",
};
if (this.client === undefined) {
if (
this.webdavConfig.username !== "" &&
this.webdavConfig.password !== ""
) {
this.client = createClient(this.webdavConfig.address, {
username: this.webdavConfig.username,
password: this.webdavConfig.password,
headers: headers,
authType:
this.webdavConfig.authType === "digest"
? AuthType.Digest
: AuthType.Password,
});
} else {
log.info("no password");
this.client = createClient(this.webdavConfig.address, {
headers: headers,
});
}
}
// check vault folder
if (this.vaultFolderExists) {
// pass
} else {
const res = await this.client.exists(`/${this.remoteBaseDir}/`);
if (res) {
// log.info("remote vault folder exits!");
this.vaultFolderExists = true;
} else {
log.info("remote vault folder not exists, creating");
await this.client.createDirectory(`/${this.remoteBaseDir}/`);
log.info("remote vault folder created!");
this.vaultFolderExists = true;
}
}
// adjust depth parameter
if (this.webdavConfig.depth === "auto_unknown") {
let testPassed = false;
try {
const res = await this.client.customRequest(`/${this.remoteBaseDir}/`, {
method: "PROPFIND",
headers: {
Depth: "infinity",
},
responseType: "text",
});
if (res.status === 403) {
throw Error("not support Infinity, get 403");
} else {
testPassed = true;
this.webdavConfig.depth = "auto_infinity";
this.webdavConfig.manualRecursive = false;
}
} catch (error) {
testPassed = false;
}
if (!testPassed) {
try {
const res = await this.client.customRequest(
`/${this.remoteBaseDir}/`,
{
method: "PROPFIND",
headers: {
Depth: "1",
},
responseType: "text",
}
);
testPassed = true;
this.webdavConfig.depth = "auto_1";
this.webdavConfig.manualRecursive = true;
} catch (error) {
testPassed = false;
}
}
if (testPassed) {
// the depth option has been changed
// save the setting
if (this.saveUpdatedConfigFunc !== undefined) {
await this.saveUpdatedConfigFunc();
log.info(
`webdav depth="auto_unknown" is changed to ${this.webdavConfig.depth}`
);
}
}
}
};
}
export const getWebdavClient = (
webdavConfig: WebdavConfig,
remoteBaseDir: string,
saveUpdatedConfigFunc: () => Promise<any>
) => {
return new WrappedWebdavClient(
webdavConfig,
remoteBaseDir,
saveUpdatedConfigFunc
);
};
export const getRemoteMeta = async (
client: WrappedWebdavClient,
fileOrFolderPath: string
) => {
await client.init();
const remotePath = getWebdavPath(fileOrFolderPath, client.remoteBaseDir);
// log.info(`remotePath = ${remotePath}`);
const res = (await client.client.stat(remotePath, {
details: false,
})) as FileStat;
return fromWebdavItemToRemoteItem(res, client.remoteBaseDir);
};
export const uploadToRemote = async (
client: WrappedWebdavClient,
fileOrFolderPath: string,
vault: Vault,
isRecursively: boolean = false,
password: string = "",
remoteEncryptedKey: string = "",
uploadRaw: boolean = false,
rawContent: string | ArrayBuffer = ""
) => {
await client.init();
let uploadFile = fileOrFolderPath;
if (password !== "") {
uploadFile = remoteEncryptedKey;
}
uploadFile = getWebdavPath(uploadFile, client.remoteBaseDir);
const isFolder = fileOrFolderPath.endsWith("/");
if (isFolder && isRecursively) {
throw Error("upload function doesn't implement recursive function yet!");
} else if (isFolder && !isRecursively) {
if (uploadRaw) {
throw Error(`you specify uploadRaw, but you also provide a folder key!`);
}
// folder
if (password === "") {
// if not encrypted, mkdir a remote folder
await client.client.createDirectory(uploadFile, {
recursive: false, // the sync algo should guarantee no need to recursive
});
const res = await getRemoteMeta(client, uploadFile);
return res;
} else {
// if encrypted, upload a fake file with the encrypted file name
await client.client.putFileContents(uploadFile, "", {
overwrite: true,
onUploadProgress: (progress: any) => {
// log.info(`Uploaded ${progress.loaded} bytes of ${progress.total}`);
},
});
return await getRemoteMeta(client, uploadFile);
}
} else {
// file
// we ignore isRecursively parameter here
let localContent = undefined;
if (uploadRaw) {
if (typeof rawContent === "string") {
localContent = new TextEncoder().encode(rawContent).buffer;
} else {
localContent = rawContent;
}
} else {
localContent = await vault.adapter.readBinary(fileOrFolderPath);
}
let remoteContent = localContent;
if (password !== "") {
remoteContent = await encryptArrayBuffer(localContent, password);
}
// updated 20220326: the algorithm guarantee this
// // we need to create folders before uploading
// const dir = getPathFolder(uploadFile);
// if (dir !== "/" && dir !== "") {
// await client.client.createDirectory(dir, { recursive: false });
// }
await client.client.putFileContents(uploadFile, remoteContent, {
overwrite: true,
onUploadProgress: (progress: any) => {
log.info(`Uploaded ${progress.loaded} bytes of ${progress.total}`);
},
});
return await getRemoteMeta(client, uploadFile);
}
};
export const listFromRemote = async (
client: WrappedWebdavClient,
prefix?: string
) => {
if (prefix !== undefined) {
throw Error("prefix not supported");
}
await client.init();
let contents = [] as FileStat[];
if (
client.webdavConfig.depth === "auto_1" ||
client.webdavConfig.depth === "manual_1"
) {
// the remote doesn't support infinity propfind,
// we need to do a bfs here
const q = new Queue([`/${client.remoteBaseDir}`]);
const CHUNK_SIZE = 10;
while (q.length > 0) {
const itemsToFetch = [];
while (q.length > 0) {
itemsToFetch.push(q.pop());
}
const itemsToFetchChunks = chunk(itemsToFetch, CHUNK_SIZE);
// log.debug(itemsToFetchChunks);
const subContents = [] as FileStat[];
for (const singleChunk of itemsToFetchChunks) {
const r = singleChunk.map((x) => {
return client.client.getDirectoryContents(x, {
deep: false,
details: false /* no need for verbose details here */,
// TODO: to support .obsidian,
// we need to load all files including dot,
// anyway to reduce the resources?
// glob: "/**" /* avoid dot files by using glob */,
}) as Promise<FileStat[]>;
});
const r2 = flatten(await Promise.all(r));
subContents.push(...r2);
}
for (let i = 0; i < subContents.length; ++i) {
const f = subContents[i];
contents.push(f);
if (f.type === "directory") {
q.push(f.filename);
}
}
}
} else {
// the remote supports infinity propfind
contents = (await client.client.getDirectoryContents(
`/${client.remoteBaseDir}`,
{
deep: true,
details: false /* no need for verbose details here */,
// TODO: to support .obsidian,
// we need to load all files including dot,
// anyway to reduce the resources?
// glob: "/**" /* avoid dot files by using glob */,
}
)) as FileStat[];
}
return {
Contents: contents.map((x) =>
fromWebdavItemToRemoteItem(x, client.remoteBaseDir)
),
};
};
const downloadFromRemoteRaw = async (
client: WrappedWebdavClient,
fileOrFolderPath: string
) => {
await client.init();
const buff = (await client.client.getFileContents(
getWebdavPath(fileOrFolderPath, client.remoteBaseDir)
)) as BufferLike;
if (buff instanceof ArrayBuffer) {
return buff;
} else if (buff instanceof Buffer) {
return bufferToArrayBuffer(buff);
}
throw Error(`unexpected file content result with type ${typeof buff}`);
};
export const downloadFromRemote = async (
client: WrappedWebdavClient,
fileOrFolderPath: string,
vault: Vault,
mtime: number,
password: string = "",
remoteEncryptedKey: string = "",
skipSaving: boolean = false
) => {
await client.init();
const isFolder = fileOrFolderPath.endsWith("/");
if (!skipSaving) {
await mkdirpInVault(fileOrFolderPath, vault);
}
// the file is always local file
// we need to encrypt it
if (isFolder) {
// mkdirp locally is enough
// do nothing here
return new ArrayBuffer(0);
} else {
let downloadFile = fileOrFolderPath;
if (password !== "") {
downloadFile = remoteEncryptedKey;
}
downloadFile = getWebdavPath(downloadFile, client.remoteBaseDir);
const remoteContent = await downloadFromRemoteRaw(client, downloadFile);
let localContent = remoteContent;
if (password !== "") {
localContent = await decryptArrayBuffer(remoteContent, password);
}
if (!skipSaving) {
await vault.adapter.writeBinary(fileOrFolderPath, localContent, {
mtime: mtime,
});
}
return localContent;
}
};
export const deleteFromRemote = async (
client: WrappedWebdavClient,
fileOrFolderPath: string,
password: string = "",
remoteEncryptedKey: string = ""
) => {
if (fileOrFolderPath === "/") {
return;
}
let remoteFileName = fileOrFolderPath;
if (password !== "") {
remoteFileName = remoteEncryptedKey;
}
remoteFileName = getWebdavPath(remoteFileName, client.remoteBaseDir);
await client.init();
try {
await client.client.deleteFile(remoteFileName);
// log.info(`delete ${remoteFileName} succeeded`);
} catch (err) {
console.error("some error while deleting");
log.info(err);
}
};
export const checkConnectivity = async (
client: WrappedWebdavClient,
callbackFunc?: any
) => {
if (
!(
client.webdavConfig.address.startsWith("http://") ||
client.webdavConfig.address.startsWith("https://")
)
) {
const err = "Error: the url should start with http(s):// but it does not!";
log.debug(err);
if (callbackFunc !== undefined) {
callbackFunc(err);
}
return false;
}
try {
await client.init();
const results = await getRemoteMeta(client, "/");
if (results === undefined) {
const err = "results is undefined";
log.debug(err);
if (callbackFunc !== undefined) {
callbackFunc(err);
}
return false;
}
return true;
} catch (err) {
log.debug(err);
if (callbackFunc !== undefined) {
callbackFunc(err);
}
return false;
}
}; | the_stack |
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
OnDestroy,
Output,
QueryList,
ViewChild
} from '@angular/core';
import { async } from '@angular/core/testing';
import { render } from '@testing-library/angular';
import { noop, Observable } from 'rxjs';
import { ObservableChildren } from './observable-children';
describe.only('@ObservableChildren', () => {
describe('when using template reference variables', () => {
it('should query elements and store query list', async () => {
@Component({
template: `
<ul>
<li #item>Item 1</li>
<li #item>Item 2</li>
<li #item>Item 3</li>
</ul>
`
})
class TestComponent {
@ObservableChildren('item', 'click')
clicks$: Observable<any>;
}
const { fixture } = await render(TestComponent);
const componentInstance = fixture.componentInstance as TestComponent;
const queryList = componentInstance['__clicks$'] as QueryList<ElementRef>;
expect(componentInstance['__clicks$'] instanceof QueryList).toBe(true);
expect(queryList.length).toBe(3);
expect(queryList.first instanceof ElementRef).toBe(true);
});
it('should query elements and create single event stream for all elements', async () => {
@Component({
template: `
<ul>
<li data-testid="item-1" #item>Item 1</li>
<li data-testid="item-2" #item>Item 2</li>
<li data-testid="item-3" #item>Item 3</li>
</ul>
`
})
class TestComponent {
@ObservableChildren('item', 'click')
clicks$: Observable<any>;
}
const { fixture, click, getByTestId } = await render(TestComponent);
const componentInstance = fixture.componentInstance as TestComponent;
const nextSpy = jest.fn();
componentInstance.clicks$.subscribe(nextSpy, noop, noop);
click(getByTestId('item-1'));
expect(nextSpy).toHaveBeenCalledTimes(1);
click(getByTestId('item-2'));
expect(nextSpy).toHaveBeenCalledTimes(2);
click(getByTestId('item-3'));
expect(nextSpy).toHaveBeenCalledTimes(3);
});
it('should listen for view changes and update the stream', async () => {
@Component({
template: `
<ul>
<li #li attr.data-testid="item-{{ text }}" *ngFor="let text of items">Item {{ text }}</li>
</ul>
<button data-testid="add" (click)="add()">Add</button>
<button data-testid="remove" (click)="remove()">Remove</button>
`
})
class TestComponent {
@ObservableChildren('li', 'click')
clicks$: Observable<any>;
items = [1, 2, 3];
add() {
this.items.push(this.items.length + 1);
}
remove() {
this.items.pop();
}
}
const { fixture, click, getByTestId, queryByTestId } = await render(TestComponent);
const componentInstance = fixture.componentInstance as TestComponent;
const queryList = componentInstance['__clicks$'] as QueryList<ElementRef>;
const nextSpy = jest.fn();
componentInstance.clicks$.subscribe(nextSpy, noop, noop);
expect(queryList.length).toBe(3);
// add element
click(getByTestId('add'));
expect(queryList.length).toBe(4);
click(getByTestId('item-4'));
expect(nextSpy).toHaveBeenCalledTimes(1);
// add one more element
click(getByTestId('add'));
expect(queryList.length).toBe(5);
click(getByTestId('item-5'));
expect(nextSpy).toHaveBeenCalledTimes(2);
// remove element
click(getByTestId('remove'));
expect(queryList.length).toBe(4);
expect(queryByTestId('item-5')).toBeNull();
// remove one more element
click(getByTestId('remove'));
expect(queryList.length).toBe(3);
expect(queryByTestId('item-4')).toBeNull();
});
it('should call original ngAfterViewInit', async () => {
const afterViewInitSpy = jest.fn();
@Component({
template: `
<ul>
<li #item>Item 1</li>
<li #item>Item 2</li>
<li #item>Item 3</li>
</ul>
`
})
class TestComponent implements AfterViewInit {
@ObservableChildren('item', 'click')
clicks$: Observable<any>;
ngAfterViewInit = afterViewInitSpy;
}
await render(TestComponent);
expect(afterViewInitSpy).toHaveBeenCalledTimes(1);
});
});
describe('when using components', () => {
it('should query component and store instance on target', async () => {
@Component({
template: `
<foo></foo>
<foo></foo>
`
})
class TestComponent {
@ObservableChildren(FooComponent, 'testEvent')
testEvent$: Observable<any>;
}
const { fixture } = await render(TestComponent, {
declarations: [FooComponent]
});
const componentInstance = fixture.componentInstance as TestComponent;
const queryList = componentInstance['__testEvent$'] as QueryList<FooComponent>;
expect(queryList instanceof QueryList).toBe(true);
expect(queryList.length).toBe(2);
expect(queryList.first instanceof FooComponent).toBe(true);
});
it('should create event stream', async () => {
@Component({
template: `
<foo></foo>
<foo></foo>
`
})
class TestComponent {
@ObservableChildren(FooComponent, 'testEvent')
testEvent$: Observable<any>;
}
const { fixture, click, getAllByTestId } = await render(TestComponent, {
declarations: [FooComponent]
});
const componentInstance = fixture.componentInstance as TestComponent;
expect(componentInstance.testEvent$ instanceof Observable).toBe(true);
const nextSpy = jest.fn();
componentInstance.testEvent$.subscribe(nextSpy, noop, noop);
click(getAllByTestId('foo-button')[0]);
expect(nextSpy).toHaveBeenCalledTimes(1);
click(getAllByTestId('foo-button')[1]);
expect(nextSpy).toHaveBeenCalledTimes(2);
});
it('should throw error if output does not exist', async(async () => {
const errorSpy = jest.fn(error => {
expect(error.message).toMatch(
`[ObservableChildren] Cannot create event stream for 'nonsense' on target 'FooComponent'. Event does not exist.`
);
});
@Component({
template: `
<foo></foo>
`
})
class TestComponent implements AfterViewInit {
@ObservableChildren(FooComponent, 'nonsense')
testEvent$: Observable<any>;
ngAfterViewInit() {
this.testEvent$.subscribe(noop, errorSpy, noop);
}
}
await render(TestComponent, {
declarations: [FooComponent]
});
}));
it('should call original ngAfterViewInit', async () => {
const afterViewInitSpy = jest.fn();
@Component({
template: `
<foo></foo>
`
})
class TestComponent implements AfterViewInit {
@ObservableChildren(FooComponent, 'nonsense')
testEvent$: Observable<any>;
ngAfterViewInit = afterViewInitSpy;
}
await render(TestComponent, {
declarations: [FooComponent]
});
expect(afterViewInitSpy).toHaveBeenCalledTimes(1);
});
});
describe('when query result is undefined', () => {
it('should not throw error and return empty query list', async(async () => {
const errorSpy = jest.fn();
@Component({
template: ''
})
class TestComponent implements AfterViewInit {
@ObservableChildren('button', 'click')
buttonClick$: Observable<any>;
ngAfterViewInit() {
this.buttonClick$.subscribe(noop, errorSpy, noop);
}
}
const renderResult = render(TestComponent);
expect(renderResult).resolves.toBeDefined();
const { fixture } = await renderResult;
const componentInstance = fixture.componentInstance as TestComponent;
const queryList = componentInstance['__buttonClick$'];
expect(queryList.length).toBe(0);
expect(errorSpy).not.toHaveBeenCalled();
expect(componentInstance.buttonClick$).toBeDefined();
}));
});
describe('when element is destroyed and re-created', () => {
it('should re-create event stream', async () => {
@Component({
template: `
<div *ngIf="showElement" data-testid="div" #div>Some Content</div>
<button data-testid="toggle" (click)="showElement = !showElement">Toggle</button>
`
})
class TestComponent {
showElement = true;
@ObservableChildren('div', 'click')
clicks$: Observable<any>;
}
const { fixture, getByTestId, click, queryByTestId } = await render(TestComponent);
const componentInstance = fixture.componentInstance as TestComponent;
const queryList = componentInstance['__clicks$'] as QueryList<ElementRef>;
const nextSpy = jest.fn();
const completeSpy = jest.fn();
componentInstance.clicks$.subscribe(nextSpy, noop, completeSpy);
click(getByTestId('div'));
expect(nextSpy).toHaveBeenCalledTimes(1);
// hide element
click(getByTestId('toggle'));
expect(queryList.length).toBe(0);
expect(queryByTestId('div')).toBeNull();
expect(completeSpy).not.toHaveBeenCalled();
// show element again
click(getByTestId('toggle'));
expect(queryList.length).toBe(1);
expect(queryByTestId('div')).not.toBeNull();
click(getByTestId('div'));
expect(nextSpy).toHaveBeenCalledTimes(2);
});
});
describe('when child component is destroyed and re-created', () => {
it('should re-create event stream', async () => {
@Component({
template: `
<bar *ngIf="showComponent">Test</bar>
<button data-testid="toggle" (click)="showComponent = !showComponent">Toggle</button>
`
})
class TestComponent {
showComponent = true;
@ViewChild(BarComponent, { static: false })
bar: BarComponent;
}
const { fixture, getByTestId, click, queryByTestId } = await render(TestComponent, {
declarations: [BarComponent]
});
const componentInstance = fixture.componentInstance as TestComponent;
const nextSpy = jest.fn();
const completeSpy = jest.fn();
componentInstance.bar.buttonClick$.subscribe(nextSpy, noop, completeSpy);
click(getByTestId('bar-item-1'));
expect(nextSpy).toHaveBeenCalledTimes(1);
// hide component
click(getByTestId('toggle'));
expect(completeSpy).toHaveBeenCalledTimes(1);
expect(componentInstance.bar).toBeUndefined();
// show component
click(getByTestId('toggle'));
componentInstance.bar.buttonClick$.subscribe(nextSpy, noop, completeSpy);
click(getByTestId('bar-item-3'));
expect(nextSpy).toHaveBeenCalledTimes(2);
});
});
describe('when destroyed', () => {
it('should complete event stream', async () => {
@Component({
template: `
<button data-testid="button" #button>Test</button>
`
})
class TestComponent {
@ObservableChildren('button', 'click')
buttonClick$: Observable<any>;
}
const { fixture } = await render(TestComponent);
const componentInstance = fixture.componentInstance as TestComponent;
const completeSpy = jest.fn();
componentInstance.buttonClick$.subscribe(noop, noop, completeSpy);
fixture.destroy();
expect(completeSpy).toHaveBeenCalled();
});
it('should call original ngOnDestroy', async () => {
const onDestroySpy = jest.fn();
@Component({
template: `
<foo></foo>
`
})
class TestComponent implements OnDestroy {
@ObservableChildren(FooComponent, 'nonsense')
testEvent$: Observable<any>;
ngOnDestroy() {
console.log('original ngOnDestroy');
}
}
const { fixture } = await render(TestComponent, {
declarations: [FooComponent]
});
const logSpy = jest.spyOn(console, 'log').mockImplementation();
fixture.destroy();
expect(logSpy).toHaveBeenCalledWith('original ngOnDestroy');
});
});
});
@Component({
selector: 'foo',
template: `
<button data-testid="foo-button" (click)="testEvent.emit('payload')">Click Me</button>
`
})
class FooComponent {
@Output() testEvent = new EventEmitter();
}
@Component({
selector: 'bar',
template: `
<ul>
<li data-testid="bar-item-1" #item>Item 1</li>
<li data-testid="bar-item-2" #item>Item 2</li>
<li data-testid="bar-item-3" #item>Item 3</li>
</ul>
`
})
class BarComponent {
@ObservableChildren('item', 'click')
buttonClick$: Observable<any>;
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import Regexes from '../../../../../resources/regexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { NetMatches } from '../../../../../types/net_matches';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
ce?: string;
helldiver?: boolean;
energyCount?: number;
orbs?: { [id: string]: string };
fiendCount?: number;
orbOutput?: string[];
warped?: { [id: string]: { x: number; y: number } };
haveSeenMoltingPlumage?: boolean;
}
// List of events:
// https://github.com/xivapi/ffxiv-datamining/blob/master/csv/DynamicEvent.csv
//
// These ids are (unfortunately) gathered by hand and don't seem to correlate
// to any particular bits of data. However, there's a game log message when you
// register for a CE and an 0x21 message with this id when you accept and
// teleport in. This avoids having to translate all of these names and also
// guarantees that the player is actually in the CE for the purpose of
// filtering triggers.
const ceIds: { [ce: string]: string } = {
// Kill It with Fire
kill: '1D4',
// The Baying of the Hound(s)
hounds: '1CC',
// Vigil for the Lost
vigil: '1D0',
// Aces High
aces: '1D2',
// The Shadow of Death's Hand
shadow: '1CD',
// The Final Furlong
furlong: '1D5',
// The Hunt for Red Choctober
choctober: '1CA',
// Beast of Man
beast: '1DB',
// The Fires of War
fires: '1D6',
// Patriot Games
patriot: '1D1',
// Trampled under Hoof
trampled: '1CE',
// And the Flames Went Higher
flames: '1D3',
// Metal Fox Chaos
metal: '1CB',
// Rise of the Robots'
robots: '1DF',
// Where Strode the Behemoth
behemoth: '1DC',
// The Battle of Castrum Lacus Litore
castrum: '1D7',
// Albeleo
albeleo: '1DA',
// Adrammelech
adrammelech: '1D8',
};
// 9443: torrid orb (fire)
// 9444: frozen orb (ice)
// 9445: aqueous orb (water)
// 9446: charged orb (thunder)
// 9447: vortical orb (wind)
// 9448: sabulous orb (stone)
const orbNpcNameIdToOutputString: { [id: string]: string } = {
'9443': 'stop',
'9444': 'move',
'9445': 'knockback',
'9446': 'out',
'9447': 'in',
'9448': 'rings',
};
const orbOutputStrings = {
unknown: Outputs.unknown,
knockback: Outputs.knockback,
stop: {
en: 'Stop',
de: 'Stopp',
fr: 'Arrêtez',
ja: '動かない',
cn: '停停停',
ko: '멈추기',
},
// Special case.
stopOutside: {
en: 'Stop (Out)',
de: 'Stop (Außen)',
fr: 'Arrêtez (Extérieur)',
ja: 'ストップ (外に)',
cn: '停停停 (外面)',
ko: '멈추기 (바깥에서)',
},
move: {
en: 'Move',
de: 'Bewegen',
fr: 'Bougez',
ja: '動け',
cn: '动动动',
ko: '움직이기',
},
in: Outputs.in,
out: {
en: 'Out',
de: 'Raus',
fr: 'Exterieur',
ja: '外へ',
cn: '远离',
ko: '밖으로',
},
rings: {
en: 'Rings',
de: 'Ringe',
fr: 'Anneaux',
ja: 'ドーナツ',
cn: '月环',
ko: '고리장판',
},
};
// TODO: promote something like this to Conditions?
const tankBusterOnParty = (ceName?: string) =>
(data: Data, matches: NetMatches['StartsUsing']) => {
if (ceName && data.ce !== ceName)
return false;
if (matches.target === data.me)
return true;
if (data.role !== 'healer')
return false;
return data.party.inParty(matches.target);
};
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheBozjanSouthernFront,
timelineFile: 'bozjan_southern_front.txt',
timeline: [
(data) => {
// The MRV missile is the first ability that hits the entire raid, but only the bottom raid.
// Hopefully you have not died to the one ability before this. We'll insert one line into
// the timeline here that will see if the player by name was hit by a bottom raid aoe,
// and then jump to the correct timeline. There's no "autos without targets" shenanigans
// that we can do here, like in BA.
const regex = Regexes.ability({ id: '51FD', target: data.me });
const line = `20036.9 "--helldiver--" sync /${regex.source}/ window 100,100 jump 30036.9`;
return [
'hideall "--helldiver--"',
line,
];
},
],
resetWhenOutOfCombat: false,
timelineTriggers: [
{
id: 'Bozja South Castrum Lyon Winds\' Peak',
regex: /Winds' Peak/,
beforeSeconds: 5,
response: Responses.knockback(),
},
],
triggers: [
{
id: 'Bozja South Falling Asleep',
type: 'GameLog',
netRegex: NetRegexes.gameLog({ line: '7 minutes have elapsed since your last activity..*?', capture: false }),
netRegexDe: NetRegexes.gameLog({ line: 'Seit deiner letzten Aktivität sind 7 Minuten vergangen..*?', capture: false }),
netRegexFr: NetRegexes.gameLog({ line: 'Votre personnage est inactif depuis 7 minutes.*?', capture: false }),
netRegexJa: NetRegexes.gameLog({ line: '操作がない状態になってから7分が経過しました。.*?', capture: false }),
netRegexCn: NetRegexes.gameLog({ line: '已经7分钟没有进行任何操作.*?', capture: false }),
netRegexKo: NetRegexes.gameLog({ line: '7분 동안 아무 조작을 하지 않았습니다.*?', capture: false }),
response: Responses.wakeUp(),
},
{
id: 'Bozja South Critical Engagement',
type: 'ActorControl',
netRegex: NetRegexes.network6d({ command: '80000014' }),
run: (data, matches) => {
// This fires when you win, lose, or teleport out.
if (matches.data0 === '00') {
if (data.ce && data.options.Debug)
console.log(`Stop CE: ${data.ce}`);
// Stop any active timelines.
data.StopCombat();
// Prevent further triggers for any active CEs from firing.
delete data.ce;
return;
}
delete data.ce;
const ceId = matches.data0.toUpperCase();
for (const key in ceIds) {
if (ceIds[key] === ceId) {
if (data.options.Debug)
console.log(`Start CE: ${key} (${ceId})`);
data.ce = key;
return;
}
}
if (data.options.Debug)
console.log(`Start CE: ??? (${ceId})`);
},
},
{
id: 'Bozja South Choctober Choco Slash',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Red Comet', id: '506C' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Rot(?:e|er|es|en) Meteor', id: '506C' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Comète Rouge', id: '506C' }),
netRegexJa: NetRegexes.startsUsing({ source: 'レッドコメット', id: '506C' }),
netRegexCn: NetRegexes.startsUsing({ source: '红色彗星', id: '506C' }),
netRegexKo: NetRegexes.startsUsing({ source: '붉은 혜성', id: '506C' }),
condition: tankBusterOnParty('choctober'),
response: Responses.tankBuster(),
},
{
id: 'Bozja South Castrum Bottom Check',
type: 'Ability',
// TODO: netRegex could take (data) => {} here so we could do a target: data.me?
netRegex: NetRegexes.ability({ source: '4th Legion Helldiver', id: '51FD' }),
netRegexDe: NetRegexes.ability({ source: 'Höllentaucher Der Iv\\. Legion', id: '51FD' }),
netRegexFr: NetRegexes.ability({ source: 'Plongeur Infernal De La 4E Légion', id: '51FD' }),
netRegexJa: NetRegexes.ability({ source: 'Ivレギオン・ヘルダイバー', id: '51FD' }),
netRegexCn: NetRegexes.ability({ source: '第四军团地狱潜者', id: '51FD' }),
netRegexKo: NetRegexes.ability({ source: 'Iv군단 헬다이버', id: '51FD' }),
condition: Conditions.targetIsYou(),
run: (data) => data.helldiver = true,
},
{
id: 'Bozja South Castrum Helldiver MRV Missile',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: '4th Legion Helldiver', id: '51FC', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Höllentaucher Der Iv\\. Legion', id: '51FC', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Plongeur Infernal De La 4E Légion', id: '51FC', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'Ivレギオン・ヘルダイバー', id: '51FC', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '第四军团地狱潜者', id: '51FC', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: 'Iv군단 헬다이버', id: '51FC', capture: false }),
// This won't play the first time, but that seems better than a false positive for the top.
condition: (data) => data.helldiver,
response: Responses.aoe(),
},
{
id: 'Bozja South Castrum Helldiver Lateral Dive',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: '4th Legion Helldiver', id: '51EA', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Höllentaucher Der Iv\\. Legion', id: '51EA', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Plongeur Infernal De La 4E Légion', id: '51EA', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'Ivレギオン・ヘルダイバー', id: '51EA', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '第四军团地狱潜者', id: '51EA', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: 'Iv군단 헬다이버', id: '51EA', capture: false }),
condition: (data) => data.helldiver,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stand in dive charge',
de: 'Stehe im Ansturm',
fr: 'Restez dans la charge',
ja: '直線頭割りに入る',
cn: '进入直线分摊',
ko: '돌진 장판 위에 서기',
},
},
},
{
id: 'Bozja South Castrum Helldiver Magitek Missiles',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: '4th Legion Helldiver', id: '51FF' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Höllentaucher Der Iv\\. Legion', id: '51FF' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Plongeur Infernal De La 4E Légion', id: '51FF' }),
netRegexJa: NetRegexes.startsUsing({ source: 'Ivレギオン・ヘルダイバー', id: '51FF' }),
netRegexCn: NetRegexes.startsUsing({ source: '第四军团地狱潜者', id: '51FF' }),
netRegexKo: NetRegexes.startsUsing({ source: 'Iv군단 헬다이버', id: '51FF' }),
condition: tankBusterOnParty(),
response: Responses.tankBuster(),
},
{
id: 'Bozja South Castrum Helldiver Infrared Blast',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: '4th Legion Helldiver', id: '51EC', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Höllentaucher Der Iv\\. Legion', id: '51EC', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Plongeur Infernal De La 4E Légion', id: '51EC', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'Ivレギオン・ヘルダイバー', id: '51EC', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '第四军团地狱潜者', id: '51EC', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: 'Iv군단 헬다이버', id: '51EC', capture: false }),
condition: (data) => data.helldiver,
delaySeconds: 6,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Take one tether',
de: 'Nimm eine´Verbindung',
fr: 'Prenez un lien',
ja: '線を取る',
cn: '接线',
ko: '선 하나 낚아채기',
},
},
},
{
id: 'Bozja South Castrum Helldiver Joint Attack',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: '4th Legion Helldiver', id: '51F2', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Höllentaucher Der Iv\\. Legion', id: '51F2', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Plongeur Infernal De La 4E Légion', id: '51F2', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'Ivレギオン・ヘルダイバー', id: '51F2', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '第四军团地狱潜者', id: '51F2', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: 'Iv군단 헬다이버', id: '51F2', capture: false }),
condition: (data) => data.helldiver,
response: Responses.killAdds(),
},
{
id: 'Bozja South Castrum Brionac Electric Anvil',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Brionac', id: '51DD' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Brionac', id: '51DD' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Brionac', id: '51DD' }),
netRegexJa: NetRegexes.startsUsing({ source: 'ブリューナク', id: '51DD' }),
netRegexCn: NetRegexes.startsUsing({ source: '布里欧纳克', id: '51DD' }),
netRegexKo: NetRegexes.startsUsing({ source: '브류나크', id: '51DD' }),
condition: tankBusterOnParty(),
response: Responses.tankBuster(),
},
{
id: 'Bozja South Castrum Brionac False Thunder Left',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Brionac', id: '51CE', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Brionac', id: '51CE', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Brionac', id: '51CE', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'ブリューナク', id: '51CE', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '布里欧纳克', id: '51CE', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '브류나크', id: '51CE', capture: false }),
condition: (data) => !data.helldiver,
response: Responses.goLeft(),
},
{
id: 'Bozja South Castrum Brionac False Thunder Right',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Brionac', id: '51CF', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Brionac', id: '51CF', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Brionac', id: '51CF', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'ブリューナク', id: '51CF', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '布里欧纳克', id: '51CF', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '브류나크', id: '51CF', capture: false }),
condition: (data) => !data.helldiver,
response: Responses.goRight(),
},
{
id: 'Bozja South Castrum Brionac Anti-Warmachina Weaponry',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Brionac', id: '51CD', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Brionac', id: '51CD', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Brionac', id: '51CD', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'ブリューナク', id: '51CD', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '布里欧纳克', id: '51CD', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '브류나크', id: '51CD', capture: false }),
condition: (data) => !data.helldiver,
delaySeconds: 6.5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Kill Magitek Core',
de: 'Besiege Magitek-Reaktor',
fr: 'Tuez le Cœur magitek',
ja: '魔導コアを撃破',
cn: '击杀魔导核心',
ko: '마도 핵 죽이기',
},
},
},
{
id: 'Bozja South Castrum Brionac Energy Generation',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Brionac', id: '51D0', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Brionac', id: '51D0', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Brionac', id: '51D0', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'ブリューナク', id: '51D0', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '布里欧纳克', id: '51D0', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '브류나크', id: '51D0', capture: false }),
condition: (data) => !data.helldiver,
preRun: (data) => data.energyCount = (data.energyCount ?? 0) + 1,
infoText: (data, _matches, output) => {
if (data.energyCount === 1)
return output.getUnderOrb!();
if (data.energyCount === 2)
return output.goCorner!();
// TODO: triggers for energy generation.
// It'd be nice to do this, but you barely see #3, let alone #5.
// #1 is always get under orb
// #2 is always get to corners
// #3 has two spawn options (#1 or #2 callout), interorb tethers
// #4 magentism to/from orb, but orbs don't have tethers
// #5 magentism to/from orb, interorb tethers
// https://docs.google.com/document/d/1gSHyYA4Qg_tEz-GK9N7ppAdbXQIL91MoYYWJ651lDMk/edit#
// Energy generation is 51D0 is spawning orbs
// Lightsphere is 9437, Darksphere is 9438.
// Pos: (63,-222,249.4999) (94380000011982).
// Pos: (80,-229,249.4999) (94380000011982).
// Pos: (80,-215,249.4999) (94380000011982).
// Pos: (97,-222,249.4999) (94380000011982).
},
outputStrings: {
getUnderOrb: {
en: 'Get Under Orb',
de: 'Geh unter einem Orb',
fr: 'Allez sous l\'Orbe',
ja: '白玉に安置',
cn: '靠近白球',
ko: '구슬 아래로',
},
goCorner: {
en: 'Go To Corner',
de: 'Geh in die Ecken',
fr: 'Allez dans un coin',
ja: 'コーナーへ',
cn: '去角落',
ko: '구석으로',
},
},
},
{
id: 'Bozja South Castrum Albeleo Baleful Gaze',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Albeleo\'s Monstrosity', id: '5404', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Albeleos Biest', id: '5404', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Bête D\'Albeleo', id: '5404', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'アルビレオズ・ビースト', id: '5404', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '阿尔贝雷欧的巨兽', id: '5404', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '알비레오의 야수', id: '5404', capture: false }),
suppressSeconds: 3,
response: Responses.lookAway(),
},
{
id: 'Bozja South Castrum Albeleo Abyssal Cry',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Albeleo\'s Hrodvitnir', id: '5406' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Hrodvitnir', id: '5406' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Hródvitnir', id: '5406' }),
netRegexJa: NetRegexes.startsUsing({ source: 'アルビレオズ・フローズヴィトニル', id: '5406' }),
netRegexCn: NetRegexes.startsUsing({ source: '阿尔贝雷欧的恶狼', id: '5406' }),
netRegexKo: NetRegexes.startsUsing({ source: '알비레오의 흐로드비트니르', id: '5406' }),
condition: (data) => data.CanSilence(),
response: Responses.interrupt(),
},
{
id: 'Bozja South Castrum Adrammelech Holy IV',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F96', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F96', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F96', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'アドラメレク', id: '4F96', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '阿德拉梅里克', id: '4F96', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '아드람멜렉', id: '4F96', capture: false }),
response: Responses.aoe(),
},
{
id: 'Bozja South Castrum Adrammelech Flare',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F95' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F95' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F95' }),
netRegexJa: NetRegexes.startsUsing({ source: 'アドラメレク', id: '4F95' }),
netRegexCn: NetRegexes.startsUsing({ source: '阿德拉梅里克', id: '4F95' }),
netRegexKo: NetRegexes.startsUsing({ source: '아드람멜렉', id: '4F95' }),
// TODO: this is probably magical.
condition: tankBusterOnParty(),
response: Responses.tankBuster(),
},
{
id: 'Bozja South Castrum Adrammelech Meteor',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F92', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F92', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F92', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'アドラメレク', id: '4F92', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '阿德拉梅里克', id: '4F92', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '아드람멜렉', id: '4F92', capture: false }),
delaySeconds: 4.5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Kill Meteors',
de: 'Besiege die Meteore',
fr: 'Tuez les météores',
ja: 'メテオを撃破',
cn: '击杀陨石',
ko: '메테오 부수기',
},
},
},
{
id: 'Bozja South Castrum Adrammelech Orb Collector',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcNameId: '944[3-8]' }),
run: (data, matches) => {
data.orbs ??= {};
data.orbs[matches.id.toUpperCase()] = matches.npcNameId;
},
},
{
id: 'Bozja South Castrum Adrammelech Curse of the Fiend Orbs',
type: 'StartsUsing',
// TODO: We could probably move this right after the orbs appear?
netRegex: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'アドラメレク', id: '4F7B', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '阿德拉梅里克', id: '4F7B', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '아드람멜렉', id: '4F7B', capture: false }),
// Mini-timeline:
// 0.0: Adrammelech starts using Curse Of The Fiend
// 3.0: Adrammelech uses Curse Of The Fiend
// 4.0: orbs appear
// 6.2: Adrammelech starts using Accursed Becoming
// 7.1: orb tethers appear
// 10.1: Adrammelech uses Accursed Becoming
// 17.3: Adrammelech uses orb ability #1.
preRun: (data) => data.fiendCount = (data.fiendCount ?? 0) + 1,
durationSeconds: (data) => Object.keys(data.orbs ?? {}).length === 4 ? 23 : 14,
suppressSeconds: 20,
infoText: (data, _matches, output) => {
// Let your actor id memes be dreams!
// Orbs go off from highest actor id to lowest actor id, in pairs of two.
const sortedOrbs = Object.keys(data.orbs || {}).sort().reverse();
const orbIdToNameId = data.orbs;
delete data.orbs;
if (!orbIdToNameId || sortedOrbs.length === 0)
return output.unknown!();
const orbOutput = data.orbOutput = sortedOrbs.map((orbId) => {
const nameId = orbIdToNameId[orbId];
if (!nameId)
return 'unknown';
const output = orbNpcNameIdToOutputString[nameId];
return output ? output : 'unknown';
});
// If there is a pair of orbs, and they are the same type, then this is the mechanic
// introduction and only one orb goes off.
if (orbOutput.length === 2 && orbOutput[0] === orbOutput[1])
orbOutput.length = 1;
// Special case, fire + earth = stop far outside.
if (orbOutput.length >= 2) {
if (orbOutput[0] === 'stop' && orbOutput[1] === 'rings')
orbOutput[0] = 'stopOutside';
}
if (orbOutput.length === 4) {
if (orbOutput[2] === 'stop' && orbOutput[3] === 'rings')
orbOutput[2] = 'stopOutside';
}
// Don't bother outputting a single one, as it'll come up shortly.
// This could get confusing saying "knockback" far enough ahead
// that using knockback prevention would wear off before the mechanic.
if (orbOutput.length > 1)
return orbOutput.map((key) => output[key]!()).join(' => ');
},
outputStrings: orbOutputStrings,
},
{
id: 'Bozja South Castrum Adrammelech Accursed Becoming Orb 1',
type: 'Ability',
// This ability happens once per pair of orbs (with the same timings).
// So use these two triggers to handle the single, pair, and two pairs of orbs cases.
netRegex: NetRegexes.ability({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'アドラメレク', id: '4F7B', capture: false }),
netRegexCn: NetRegexes.ability({ source: '阿德拉梅里克', id: '4F7B', capture: false }),
netRegexKo: NetRegexes.ability({ source: '아드람멜렉', id: '4F7B', capture: false }),
// 5 seconds warning.
delaySeconds: 7.2 - 5,
durationSeconds: 4.5,
alertText: (data, _matches, output) => {
data.orbOutput ??= [];
const orb = data.orbOutput.shift();
if (!orb)
return;
return output[orb]!();
},
outputStrings: orbOutputStrings,
},
{
id: 'Bozja South Castrum Adrammelech Accursed Becoming Orb 2',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Adrammelech', id: '4F7B', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'アドラメレク', id: '4F7B', capture: false }),
netRegexCn: NetRegexes.ability({ source: '阿德拉梅里克', id: '4F7B', capture: false }),
netRegexKo: NetRegexes.ability({ source: '아드람멜렉', id: '4F7B', capture: false }),
// 2.5 seconds warning, as it's weird if this shows up way before the first orb.
delaySeconds: 9 - 2.5,
alertText: (data, _matches, output) => {
data.orbOutput ??= [];
const orb = data.orbOutput.shift();
if (!orb)
return;
return output[orb]!();
},
outputStrings: orbOutputStrings,
},
{
id: 'Bozja South Castrum Adrammelech Electric Charge Collector',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcNameId: '9449' }),
run: (data, matches) => {
data.warped ??= {};
data.warped[matches.id.toUpperCase()] = {
x: parseFloat(matches.x),
y: parseFloat(matches.y),
};
},
},
{
id: 'Bozja South Castrum Adrammelech Shock',
type: 'Tether',
// This is the first Electric Charge tether.
netRegex: NetRegexes.tether({ source: 'Adrammelech', target: 'Electric Charge' }),
netRegexDe: NetRegexes.tether({ source: 'Adrammelech', target: 'Blitz' }),
netRegexFr: NetRegexes.tether({ source: 'Adrammelech', target: 'Boule D\'Énergie' }),
netRegexJa: NetRegexes.tether({ source: 'アドラメレク', target: '雷気' }),
netRegexCn: NetRegexes.tether({ source: '阿德拉梅里克', target: '雷气' }),
netRegexKo: NetRegexes.tether({ source: '아드람멜렉', target: '번개기운' }),
alertText: (data, matches, output) => {
if (!data.warped)
return output.unknown!();
const loc = data.warped[matches.targetId.toUpperCase()];
delete data.warped;
if (!loc)
return output.unknown!();
// Four inner orb locations:
// 85, -614.6 (NE)
// 88.6, -601.1 (SE)
// 75.1, -597.5 (SW)
// 71.5, -611 (NW)
const adrammelechCenterX = 80;
const adrammelechCenterY = -605;
// North is negative y.
if (loc.x > adrammelechCenterX) {
if (loc.y < adrammelechCenterY)
return output.southwest!();
return output.northwest!();
}
if (loc.y < adrammelechCenterY)
return output.southeast!();
return output.northeast!();
},
outputStrings: {
unknown: {
// "Follow Other People ;)"
en: 'Go ???',
de: 'Gehe nach ???',
fr: 'Allez au ???',
ja: '??? へ',
cn: '去 ???',
ko: '???쪽으로',
},
northeast: {
en: 'Go northeast',
de: 'Gehe nach Nordosten',
fr: 'Allez au nord-est',
ja: '北東へ',
cn: '去右上(东北)',
ko: '북동쪽으로',
},
southeast: {
en: 'Go southeast',
de: 'Gehe nach Südosten',
fr: 'Allez au sud-est',
ja: '南東へ',
cn: '去右下(东南)',
ko: '남동쪽으로',
},
southwest: {
en: 'Go southwest',
de: 'Gehe nach Südwesten',
fr: 'Allez au sud-ouest',
ja: '南西へ',
cn: '去左下(西南)',
ko: '남서쪽으로',
},
northwest: {
en: 'Go northwest',
de: 'Gehe nach Nordwesten',
fr: 'Allez au nord-ouest',
ja: '北西へ',
cn: '去左上(西北)',
ko: '북서쪽으로',
},
},
},
{
id: 'Bozja South Castrum Dawon Molting Plumage',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Dawon', id: '517A', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Dawon', id: '517A', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Dawon', id: '517A', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'ドゥン', id: '517A', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '达温', id: '517A', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '다우언', id: '517A', capture: false }),
response: Responses.aoe(),
},
{
id: 'Bozja South Castrum Dawon Molting Plumage Orbs',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Dawon', id: '517A', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Dawon', id: '517A', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Dawon', id: '517A', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'ドゥン', id: '517A', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '达温', id: '517A', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '다우언', id: '517A', capture: false }),
delaySeconds: 5,
alertText: (data, _matches, output) => {
// Only the first plumage orbs have no wind.
// If we needed to this dynamically, look for Call Beast (5192) from Lyon before this.
const text = data.haveSeenMoltingPlumage ? output.orbWithFlutter!() : output.justOrb!();
data.haveSeenMoltingPlumage = true;
return text;
},
outputStrings: {
justOrb: {
en: 'Get Under Light Orb',
de: 'Unter einem Lichtorb stellen',
fr: 'Allez sous un Orbe lumineux',
ja: '白玉へ',
cn: '靠近白球',
ko: '하얀 구슬 안으로',
},
orbWithFlutter: {
en: 'Get Under Blown Light Orb',
de: 'Zu einem weggeschleuderten Lichtorb gehen',
fr: 'Allez sous un Orbe lumineux soufflé',
ja: '赤玉へ',
cn: '靠近火球',
ko: '하얀 구슬이 이동할 위치로',
},
},
},
{
id: 'Bozja South Castrum Dawon Scratch',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Dawon', id: '517B' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Dawon', id: '517B' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Dawon', id: '517B' }),
netRegexJa: NetRegexes.startsUsing({ source: 'ドゥン', id: '517B' }),
netRegexCn: NetRegexes.startsUsing({ source: '达温', id: '517B' }),
netRegexKo: NetRegexes.startsUsing({ source: '다우언', id: '517B' }),
condition: tankBusterOnParty(),
response: Responses.tankBuster(),
},
{
id: 'Bozja South Castrum Dawon Swooping Frenzy',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Dawon', id: '5175', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Dawon', id: '5175', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Dawon', id: '5175', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: 'ドゥン', id: '5175', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '达温', id: '5175', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '다우언', id: '5175', capture: false }),
suppressSeconds: 9999,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Follow Boss',
de: 'Folge dem Boss',
fr: 'Suivez le Boss',
ja: 'ボスの後ろに追う',
cn: '跟紧在Boss身后',
ko: '보스 따라가기',
},
},
},
{
id: 'Bozja South Castrum Lyon Passage',
type: 'GameLog',
netRegex: NetRegexes.gameLog({ line: 'Lyon the Beast King would do battle at Majesty\'s Place.*?', capture: false }),
netRegexDe: NetRegexes.gameLog({ line: 'Der Bestienkönig will einen Kampf auf seinem Podest.*?', capture: false }),
netRegexFr: NetRegexes.gameLog({ line: 'Lyon attend des adversaires à sa taille sur la tribune des Souverains.*?', capture: false }),
netRegexJa: NetRegexes.gameLog({ line: '獣王ライアンは、王者の円壇での戦いを望んでいるようだ.*?', capture: false }),
netRegexCn: NetRegexes.gameLog({ line: '兽王莱昂似乎很期待在王者圆坛战斗!.*?', capture: false }),
netRegexKo: NetRegexes.gameLog({ line: '마수왕 라이언이 왕의 단상에서 싸우려고 합니다!.*?', capture: false }),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Lyon Passage Open',
de: 'Lyon Zugang offen',
fr: 'Passage du Lyon ouvert',
ja: '獣王ライオンフェイス開始',
cn: '挑战兽王莱昂',
ko: '라이언 포탈 개방',
},
},
},
{
id: 'Bozja South Castrum Lyon Twin Agonies',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Lyon The Beast King', id: '5174' }),
netRegexDe: NetRegexes.startsUsing({ source: 'Lyon (?:der|die|das) Bestienkönig', id: '5174' }),
netRegexFr: NetRegexes.startsUsing({ source: 'Lyon Le Roi Bestial', id: '5174' }),
netRegexJa: NetRegexes.startsUsing({ source: '獣王ライアン', id: '5174' }),
netRegexCn: NetRegexes.startsUsing({ source: '兽王 莱昂', id: '5174' }),
netRegexKo: NetRegexes.startsUsing({ source: '마수왕 라이언', id: '5174' }),
condition: tankBusterOnParty(),
response: Responses.tankBuster(),
},
{
id: 'Bozja South Castrum Lyon King\'s Notice',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Lyon The Beast King', id: '516E', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Lyon (?:der|die|das) Bestienkönig', id: '516E', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Lyon Le Roi Bestial', id: '516E', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: '獣王ライアン', id: '516E', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '兽王 莱昂', id: '516E', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '마수왕 라이언', id: '516E', capture: false }),
response: Responses.lookAway(),
},
{
id: 'Bozja South Castrum Lyon Taste of Blood',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ source: 'Lyon The Beast King', id: '5173', capture: false }),
netRegexDe: NetRegexes.startsUsing({ source: 'Lyon (?:der|die|das) Bestienkönig', id: '5173', capture: false }),
netRegexFr: NetRegexes.startsUsing({ source: 'Lyon Le Roi Bestial', id: '5173', capture: false }),
netRegexJa: NetRegexes.startsUsing({ source: '獣王ライアン', id: '5173', capture: false }),
netRegexCn: NetRegexes.startsUsing({ source: '兽王 莱昂', id: '5173', capture: false }),
netRegexKo: NetRegexes.startsUsing({ source: '마수왕 라이언', id: '5173', capture: false }),
response: Responses.getBehind(),
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Lyon the Beast King would do battle at Majesty\'s Place': 'Der Bestienkönig will einen Kampf auf seinem Podest',
'Red Comet': 'Rot(?:e|er|es|en) Meteor',
'Albeleo\'s Monstrosity': 'Albeleos Biest',
'Albeleo\'s Hrodvitnir': 'Hrodvitnir',
'Electric Charge': 'Blitz',
'7 minutes have elapsed since your last activity..*?': 'Seit deiner letzten Aktivität sind 7 Minuten vergangen.',
'4Th Legion Helldiver': 'Höllentaucher der IV\\. Legion',
'Adrammelech': 'Adrammelech',
'Bladesmeet': 'Hauptplatz der Wachen',
'Brionac': 'Brionac',
'Dawon': 'Dawon',
'Eaglesight': 'Platz des Kämpferischen Adlers',
'Lightsphere': 'Lichtkugel',
'Lyon The Beast King(?! would)': 'Lyon (?:der|die|das) Bestienkönig',
'Majesty\'s Auspice': 'Halle des Bestienkönigs',
'Shadowsphere': 'Schattensphäre',
'The airship landing': 'Flugplatz',
'The grand gates': 'Haupttor',
'Verdant Plume': 'blau(?:e|er|es|en) Feder',
},
'replaceText': {
'(?<!Command: )Chain Cannon': 'Kettenkanone',
'(?<!Command: )Dive Formation': 'Simultanattacke',
'(?<!Command: )Infrared Blast': 'Hitzestrahlung',
'(?<!Command: )Lateral Dive': 'Frontalangriff',
'--Lyon Passage--': '--Lyon Zugang--',
'Accursed Becoming': 'Zaubersynthese',
'Aero IV': 'Windka',
'Anti-Warmachina Weaponry': 'Anti-Magitek-Attacke',
'Blizzard IV': 'Eiska',
'Burst II': 'Knall',
'Call Beast': 'Ruppiges Rufen',
'Command: Chain Cannon': 'Befehl: Kettenkanonensalve',
'Command: Dive Formation': 'Befehl: Simultanattacke',
'Command: Infrared Blast': 'Befehl: Hitzestrahlung',
'Command: Joint Attack': 'Befehl: Antiobjektattacke',
'Command: Lateral Dive': 'Befehl: Frontalangriff',
'Command: Suppressive Formation': 'Antipersonenangriff',
'Curse Of The Fiend': 'Zaubersiegel',
'Electric Anvil': 'Elektroamboss',
'Energy Generation': 'Energiegenerierung',
'Explosion': 'Explosion',
'False Thunder': 'Störsender',
'Fervid Pulse': 'Flammenstoß',
'Fire IV': 'Feuka',
'Flare': 'Flare',
'Frigid Pulse': 'Froststoß',
'Frigid/': 'Frost/',
'Heart Of Nature': 'Puls der Erde',
'Holy IV': 'Giga-Sanctus',
'Lightburst': 'Lichtstoß',
'Lightning Shower': 'Blitzregen',
'Magitek Magnetism': 'Magimagnetismus',
'Magitek Missiles': 'Magitek-Rakete',
'Magnetic Jolt': 'Magnetische Interferenz',
'Meteor': 'Meteor',
'Molting Plumage': 'Federsturm',
'Mrv Missile': 'Multisprengkopf-Rakete',
'Nature\'s Blood': 'Erdschneider',
'Nature\'s Pulse': 'Erdrutsch',
'Obey': 'Gehorchen',
'Orb': 'Orb',
'Pentagust': 'Pentagast',
'Polar Magnetism': 'Konvertermagnet',
'Pole Shift': 'Umpolung',
'Raging Winds': 'Sturmflügel',
'Ready': 'Bellendes Befehlen',
'Scratch': 'Kräftiges Kratzen',
'Shadow Burst': 'Schattenstoß',
'Shock': 'Energetisierung',
'Stone IV': 'Steinka',
'Surface Missile': 'Antipersonenrakete',
'Swooping Frenzy': 'Heftiges Schütteln',
'Taste Of Blood': 'Blutiges Wehklagen',
'The King\'s Notice': 'Herrschender Blick',
'Thunder IV': 'Blitzka',
'Tornado': 'Tornado',
'Twin Agonies': 'Doppelter Tod',
'Voltstream': 'Voltstrom',
'Warped Light': 'Blitzartillerie',
'Water IV': 'Giga-Aqua',
'Winds\' Peak': 'Katastrophale Windstärke',
},
},
{
'locale': 'fr',
'replaceSync': {
'Lyon the Beast King would do battle at Majesty\'s Place': 'Lyon attend des adversaires à sa taille sur la tribune des Souverains',
'Red Comet': 'Comète Rouge',
'Albeleo\'s Monstrosity': 'Bête D\'Albeleo',
'Albeleo\'s Hrodvitnir': 'Hródvitnir',
'Electric Charge': 'Boule D\'Énergie',
'7 minutes have elapsed since your last activity..*?': 'Votre personnage est inactif depuis 7 minutes.*?',
'4Th Legion Helldiver': 'plongeur infernal de la 4e légion',
'Adrammelech': 'Adrammelech',
'Bladesmeet': 'Hall des Lames',
'Brionac': 'Brionac',
'Dawon': 'Dawon',
'Eaglesight': 'Perchoir des Aigles',
'Lightsphere': 'sphère de lumière',
'Lyon The Beast King(?! would)': 'Lyon le Roi bestial',
'Majesty\'s Auspice': 'Auditorium',
'Shadowsphere': 'sphère ombrale',
'The airship landing': 'Aire d\'atterrissage',
'The grand gates': 'Porte du castrum',
'Verdant Plume': 'plume de sinople',
},
'replaceText': {
'--Lyon Passage--': '--Passage du Lyon --',
'(?<!Command: )Chain Cannon': 'Canon automatique',
'(?<!Command: )Dive Formation': 'Attaque groupée',
'(?<!Command: )Infrared Blast': 'Rayonnement thermique',
'(?<!Command: )Lateral Dive': 'Attaque frontale',
'Accursed Becoming': 'Combinaison de sortilège',
'Aero IV': 'Giga Vent',
'Anti-Warmachina Weaponry': 'Attaque antimagitek',
'Blizzard IV': 'Giga Glace',
'Burst II': 'Bouillonnement',
'Call Beast': 'Appel familier',
'Command: Chain Cannon': 'Directive : Salve de canons automatiques',
'Command: Dive Formation': 'Nouvelle directive : Attaque groupée antimatériel',
'Command: Infrared Blast': 'Nouvelle directive : Rayonnement thermique antimatériel',
'Command: Joint Attack': 'Nouvelle directive : Attaque ciblée antimatériel',
'Command: Lateral Dive': 'Nouvelle directive : Attaque frontale antimatériel',
'Command: Suppressive Formation': 'Neutralisation',
'Curse Of The Fiend': 'Sceau magique',
'Electric Anvil': 'Enclume électrique',
'Energy Generation': 'Condensateur d\'énergie',
'Explosion': 'Explosion',
'False Thunder': 'Foudre artificielle',
'(?<!Frigid/)Fervid Pulse': 'Pulsation ardente',
'Fire IV': 'Giga Feu',
'Flare': 'Brasier',
'Frigid/Fervid Pulse': 'Pulsation glacial/ardente',
'Frigid Pulse': 'Pulsation glaciale',
'Heart Of Nature': 'Pulsation sismique',
'Holy IV': 'Giga Miracle',
'Lightburst': 'Éclat de lumière',
'Lightning Shower': 'Averse d\'éclairs',
'Magitek Magnetism': 'Électroaimant magitek',
'Magitek Missiles': 'Missiles magitek',
'Magnetic Jolt': 'Interférences magnétiques',
'Meteor': 'Météore',
'Molting Plumage': 'Mue de plumage',
'Mrv Missile': 'Missile à tête multiple',
'Nature\'s Blood': 'Onde fracturante',
'Nature\'s Pulse': 'Onde brise-terre',
'Obey': 'À l\'écoute du maître',
'Orb': 'Orbe',
'Pentagust': 'Pentasouffle',
'Polar Magnetism': 'Aimant à polarité inversée',
'Pole Shift': 'Inversion des pôles',
'Raging Winds': 'Rafales stagnantes',
'Ready': 'Obéis !',
'Scratch': 'Griffade',
'Shadow Burst': 'Salve ténébreuse',
'Shock': 'Décharge électrostatique',
'Stone IV': 'Giga Terre',
'Surface Missile': 'Missiles sol-sol',
'Swooping Frenzy': 'Plongeon frénétique',
'Taste Of Blood': 'Lamentation sanglante',
'The King\'s Notice': 'Œil torve des conquérants',
'Thunder IV': 'Giga Foudre',
'Tornado': 'Tornade',
'Twin Agonies': 'Double fracassage',
'Voltstream': 'Flux voltaïque',
'Warped Light': 'Artillerie éclair',
'Water IV': 'Giga Eau',
'Winds\' Peak': 'Rafales furieuses',
},
},
{
'locale': 'ja',
'replaceSync': {
'Lyon the Beast King would do battle at Majesty\'s Place': '獣王ライアンは、王者の円壇での戦いを望んでいるようだ',
'Red Comet': 'レッドコメット',
'Albeleo\'s Monstrosity': 'アルビレオズ・ビースト',
'Albeleo\'s Hrodvitnir': 'アルビレオズ・フローズヴィトニル',
'Electric Charge': '雷気',
'7 minutes have elapsed since your last activity..*?': '操作がない状態になってから7分が経過しました。.*?',
'4Th Legion Helldiver': 'IVレギオン・ヘルダイバー',
'Adrammelech': 'アドラメレク',
'Bladesmeet': '剣たちの大広間',
'Brionac': 'ブリューナク',
'Dawon': 'ドゥン',
'Eaglesight': '荒鷲の広場',
'Lightsphere': 'ライトスフィア',
'Lyon The Beast King(?! would)': '獣王ライアン',
'Majesty\'s Auspice': '円壇の間',
'Shadowsphere': 'シャドウスフィア',
'The airship landing': '飛空戦艦発着場',
'The grand gates': '城門',
'Verdant Plume': '濃緑の羽根',
},
'replaceText': {
'--Lyon Passage--': '--ライオンへ行きましょう--',
'(?<!Command: )Chain Cannon': 'チェーンガン',
'(?<!Command: )Dive Formation': '一斉突撃',
'(?<!Command: )Infrared Blast': '熱線照射',
'(?<!Command: )Lateral Dive': '突進攻撃',
'Accursed Becoming': '魔法合成',
'Aero IV': 'エアロジャ',
'Anti-Warmachina Weaponry': '対魔導兵器攻撃',
'Blizzard IV': 'ブリザジャ',
'Burst II': 'バースト',
'Call Beast': 'よびだす',
'Command: Chain Cannon': '発令:チェーンガン斉射',
'Command: Dive Formation': '発令:対物一斉突撃',
'Command: Infrared Blast': '発令:対物熱線照射',
'Command: Joint Attack': '発令:対物集中攻撃',
'Command: Lateral Dive': '発令:対物突進攻撃',
'Command: Suppressive Formation': '制圧突撃',
'Curse Of The Fiend': '魔法印',
'Electric Anvil': 'エレクトリックアンビル',
'Energy Generation': 'エネルギー体生成',
'Explosion': '爆散',
'False Thunder': 'フォルスサンダー',
'(?<!/)Fervid Pulse': 'ファーヴィッドパルス',
'Fire IV': 'ファイジャ',
'Flare': 'フレア',
'Frigid Pulse': 'フリジッドパルス',
'Frigid/Fervid Pulse': 'フリジッドパルス/ファーヴィッドパルス',
'Heart Of Nature': '地霊脈',
'Holy IV': 'ホーリジャ',
'Lightburst': 'ライトバースト',
'Lightning Shower': 'ライトニングシャワー',
'Magitek Magnetism': '魔導マグネット',
'Magitek Missiles': '魔導ミサイル',
'Magnetic Jolt': '磁力干渉',
'Meteor': 'メテオ',
'Molting Plumage': 'モルトプルメイジ',
'Mrv Missile': '多弾頭ミサイル',
'Nature\'s Blood': '波導地霊斬',
'Nature\'s Pulse': '波導地霊衝',
'Obey': 'しじをきく',
'Orb': '玉',
'Pentagust': 'ペンタガスト',
'Polar Magnetism': '転換マグネット',
'Pole Shift': '磁場転換',
'Raging Winds': '風烈飛翔流',
'Ready': 'しじをさせろ',
'Scratch': 'スクラッチ',
'Shadow Burst': 'シャドウバースト',
'Shock': '放電',
'Stone IV': 'ストンジャ',
'Surface Missile': '対地ミサイル',
'Swooping Frenzy': 'スワープフレンジー',
'Taste Of Blood': '鬼哭血散斬',
'The King\'s Notice': '覇王邪視眼',
'Thunder IV': 'サンダジャ',
'Tornado': 'トルネド',
'Twin Agonies': '双魔邪王斬',
'Voltstream': 'ボルトストリーム',
'Warped Light': '閃光砲',
'Water IV': 'ウォタジャ',
'Winds\' Peak': '超級烈風波',
},
},
{
'locale': 'cn',
'replaceSync': {
'Lyon the Beast King would do battle at Majesty\'s Place': '兽王莱昂似乎很期待在王者圆坛战斗!',
'Red Comet': '红色彗星',
'Albeleo\'s Monstrosity': '阿尔贝雷欧的巨兽',
'Albeleo\'s Hrodvitnir': '阿尔贝雷欧的恶狼',
'Electric Charge': '雷气',
'7 minutes have elapsed since your last activity..*?': '已经7分钟没有进行任何操作',
'4Th Legion Helldiver': '第四军团地狱潜者',
'Adrammelech': '阿德拉梅里克',
'Bladesmeet': '群刃大厅',
'Brionac': '布里欧纳克',
'Dawon': '达温',
'Eaglesight': '苍鹰广场',
'Lightsphere': '光耀晶球',
'Lyon The Beast King(?! would)': '兽王 莱昂',
'Majesty\'s Auspice': '圆坛之间',
'Shadowsphere': '暗影晶球',
'The airship landing': '飞空战舰着陆台',
'The grand gates': '城门',
'Verdant Plume': '浓绿之羽',
},
'replaceText': {
'--Lyon Passage--': '--兽王通道开启--',
'(?<!Command: )Chain Cannon': '链式机关炮',
'(?<!Command: )Dive Formation': '一齐突击',
'(?<!Command: )Infrared Blast': '热线照射',
'(?<!Command: )Lateral Dive': '突进攻击',
'Accursed Becoming': '魔法合成',
'Aero IV': '飙风',
'Anti-Warmachina Weaponry': '对魔导兵器攻击',
'Blizzard IV': '冰澈',
'Burst II': '磁暴',
'Call Beast': '呼叫',
'Command: Chain Cannon': '下令:链式机关炮齐射',
'Command: Dive Formation': '下令:对物一齐突击',
'Command: Infrared Blast': '下令:对物热线照射',
'Command: Joint Attack': '下令:对物集中攻击',
'Command: Lateral Dive': '下令:对物突进攻击',
'Command: Suppressive Formation': '下令:对人压制突击',
'Curse Of The Fiend': '魔法印',
'Electric Anvil': '电砧',
'Energy Generation': '生成能源体',
'Explosion': '爆炸',
'False Thunder': '伪雷',
'(?<!/)Fervid Pulse': '炙热脉冲',
'Fire IV': '炽炎',
'Flare': '核爆',
'Frigid Pulse': '寒冷脉冲',
'Frigid/Fervid Pulse': '寒冷脉冲/炙热脉冲',
'Heart Of Nature': '地灵脉',
'Holy IV': '极圣',
'Lightburst': '光爆破',
'Lightning Shower': '雷光雨',
'Magitek Magnetism': '魔导磁石',
'Magitek Missiles': '魔导飞弹',
'Magnetic Jolt': '磁力干涉',
'Meteor': '陨石流星',
'Molting Plumage': '换羽',
'Mrv Missile': '多弹头飞弹',
'Nature\'s Blood': '波导地灵斩',
'Nature\'s Pulse': '波导地灵冲',
'Obey': '服从',
'Orb': '球',
'Pentagust': '五向突风',
'Polar Magnetism': '转换磁石',
'Pole Shift': '磁场转换',
'Raging Winds': '风烈飞翔流',
'Ready': '准备',
'Scratch': '抓击',
'Shadow Burst': '暗影爆',
'Shock': '放电',
'Stone IV': '崩石',
'Surface Missile': '对地导弹',
'Swooping Frenzy': '狂乱猛冲',
'Taste Of Blood': '鬼哭血散斩',
'The King\'s Notice': '霸王邪视眼',
'Thunder IV': '霹雷',
'Tornado': '龙卷',
'Twin Agonies': '双魔邪王斩',
'Voltstream': '电压流',
'Warped Light': '闪光炮',
'Water IV': '骇水',
'Winds\' Peak': '超级烈风波',
},
},
{
'locale': 'ko',
'replaceSync': {
'Lyon the Beast King would do battle at Majesty\'s Place': '마수왕 라이언이 왕의 단상에서 싸우려고 합니다!',
'Red Comet': '붉은 혜성',
'Albeleo\'s Monstrosity': '알비레오의 야수',
'Albeleo\'s Hrodvitnir': '알비레오의 흐로드비트니르',
'Electric Charge': '번개기운',
'7 minutes have elapsed since your last activity..*?': '7분 동안 아무 조작을 하지 않았습니다',
'4Th Legion Helldiver': 'IV군단 헬다이버',
'Adrammelech': '아드람멜렉',
'Bladesmeet': '검들의 대광장',
'Brionac': '브류나크',
'Dawon': '다우언',
'Eaglesight': '독수리 광장',
'Lightsphere': '빛 구체',
'Lyon The Beast King(?! would)': '마수왕 라이언',
'Majesty\'s Auspice': '단상',
'Shadowsphere': '그림자 구체',
'The airship landing': '골드 소서 비공정 승강장',
'The grand gates': '성문',
'Verdant Plume': '진녹색 날개',
},
'replaceText': {
'--Lyon Passage--': '--라이언 포탈 개방--',
'(?<!Command: )Chain Cannon': '기관총 일제 발사',
'(?<!Command: )Dive Formation': '대물 일제 돌격',
'(?<!Command: )Infrared Blast': '대물 열선',
'(?<!Command: )Lateral Dive': '대물 돌진 공격',
'Accursed Becoming': '마법 합성',
'Aero IV': '에어로쟈',
'Anti-Warmachina Weaponry': '마도 병기 대응 공격',
'Blizzard IV': '블리자쟈',
'Burst II': '버스트',
'Call Beast': '부르기',
'Command: Chain Cannon': '지령: 기관총 일제 발사',
'Command: Dive Formation': '지령: 대물 일제 돌격',
'Command: Infrared Blast': '지령: 대물 열선',
'Command: Joint Attack': '지령: 대물 집중 공격',
'Command: Lateral Dive': '지령: 대물 돌진 공격',
'Command: Suppressive Formation': '대인 제압 돌격',
'Curse Of The Fiend': '마법인',
'Electric Anvil': '전기 모루',
'Energy Generation': '에너지 구체 생성',
'Explosion': '폭산',
'False Thunder': '인공 번개',
'Frigid(?! )': '냉랭한',
'Fervid Pulse': '열렬한 고동',
'Fire IV': '파이쟈',
'Flare': '플레어',
'Frigid Pulse': '냉랭한 고동',
'Heart Of Nature': '지령맥',
'Holy IV': '홀리쟈',
'Lightburst': '빛 분출',
'Lightning Shower': '번개 세례',
'Magitek Magnetism': '마도 자석',
'Magitek Missiles': '마도 미사일',
'Magnetic Jolt': '자력 간섭',
'Meteor': '메테오',
'Molting Plumage': '털갈이',
'Mrv Missile': '다탄두 미사일',
'Nature\'s Blood': '파도지령참',
'Nature\'s Pulse': '파도지령충',
'Obey': '명령 따르기',
'Orb': '구슬',
'Pentagust': '다섯 갈래 돌풍',
'Polar Magnetism': '자석 변환',
'Pole Shift': '자기장 전환',
'Raging Winds': '풍렬비상류',
'Ready': '명령하기',
'Scratch': '생채기',
'Shadow Burst': '그림자 폭발',
'Shock': '방전',
'Stone IV': '스톤쟈',
'Surface Missile': '대지 미사일',
'Swooping Frenzy': '광란의 급강하',
'Taste Of Blood': '귀곡혈산참',
'The King\'s Notice': '패왕사시안',
'Thunder IV': '선더쟈',
'Tornado': '토네이도',
'Twin Agonies': '쌍마사왕참',
'Voltstream': '번개 급류',
'Warped Light': '섬광포',
'Water IV': '워터쟈',
'Winds\' Peak': '초급렬풍파',
},
},
],
};
export default triggerSet; | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class ConnectParticipant extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: ConnectParticipant.Types.ClientConfiguration)
config: Config & ConnectParticipant.Types.ClientConfiguration;
/**
* Creates the participant's connection. Note that ParticipantToken is used for invoking this API instead of ConnectionToken. The participant token is valid for the lifetime of the participant – until the they are part of a contact. The response URL for WEBSOCKET Type has a connect expiry timeout of 100s. Clients must manually connect to the returned websocket URL and subscribe to the desired topic. For chat, you need to publish the following on the established websocket connection: {"topic":"aws/subscribe","content":{"topics":["aws/chat"]}} Upon websocket URL expiry, as specified in the response ConnectionExpiry parameter, clients need to call this API again to obtain a new websocket URL and perform the same steps as before.
*/
createParticipantConnection(params: ConnectParticipant.Types.CreateParticipantConnectionRequest, callback?: (err: AWSError, data: ConnectParticipant.Types.CreateParticipantConnectionResponse) => void): Request<ConnectParticipant.Types.CreateParticipantConnectionResponse, AWSError>;
/**
* Creates the participant's connection. Note that ParticipantToken is used for invoking this API instead of ConnectionToken. The participant token is valid for the lifetime of the participant – until the they are part of a contact. The response URL for WEBSOCKET Type has a connect expiry timeout of 100s. Clients must manually connect to the returned websocket URL and subscribe to the desired topic. For chat, you need to publish the following on the established websocket connection: {"topic":"aws/subscribe","content":{"topics":["aws/chat"]}} Upon websocket URL expiry, as specified in the response ConnectionExpiry parameter, clients need to call this API again to obtain a new websocket URL and perform the same steps as before.
*/
createParticipantConnection(callback?: (err: AWSError, data: ConnectParticipant.Types.CreateParticipantConnectionResponse) => void): Request<ConnectParticipant.Types.CreateParticipantConnectionResponse, AWSError>;
/**
* Disconnects a participant. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
disconnectParticipant(params: ConnectParticipant.Types.DisconnectParticipantRequest, callback?: (err: AWSError, data: ConnectParticipant.Types.DisconnectParticipantResponse) => void): Request<ConnectParticipant.Types.DisconnectParticipantResponse, AWSError>;
/**
* Disconnects a participant. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
disconnectParticipant(callback?: (err: AWSError, data: ConnectParticipant.Types.DisconnectParticipantResponse) => void): Request<ConnectParticipant.Types.DisconnectParticipantResponse, AWSError>;
/**
* Retrieves a transcript of the session. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
getTranscript(params: ConnectParticipant.Types.GetTranscriptRequest, callback?: (err: AWSError, data: ConnectParticipant.Types.GetTranscriptResponse) => void): Request<ConnectParticipant.Types.GetTranscriptResponse, AWSError>;
/**
* Retrieves a transcript of the session. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
getTranscript(callback?: (err: AWSError, data: ConnectParticipant.Types.GetTranscriptResponse) => void): Request<ConnectParticipant.Types.GetTranscriptResponse, AWSError>;
/**
* Sends an event. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
sendEvent(params: ConnectParticipant.Types.SendEventRequest, callback?: (err: AWSError, data: ConnectParticipant.Types.SendEventResponse) => void): Request<ConnectParticipant.Types.SendEventResponse, AWSError>;
/**
* Sends an event. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
sendEvent(callback?: (err: AWSError, data: ConnectParticipant.Types.SendEventResponse) => void): Request<ConnectParticipant.Types.SendEventResponse, AWSError>;
/**
* Sends a message. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
sendMessage(params: ConnectParticipant.Types.SendMessageRequest, callback?: (err: AWSError, data: ConnectParticipant.Types.SendMessageResponse) => void): Request<ConnectParticipant.Types.SendMessageResponse, AWSError>;
/**
* Sends a message. Note that ConnectionToken is used for invoking this API instead of ParticipantToken.
*/
sendMessage(callback?: (err: AWSError, data: ConnectParticipant.Types.SendMessageResponse) => void): Request<ConnectParticipant.Types.SendMessageResponse, AWSError>;
}
declare namespace ConnectParticipant {
export type ChatContent = string;
export type ChatContentType = string;
export type ChatItemId = string;
export type ChatItemType = "MESSAGE"|"EVENT"|"CONNECTION_ACK"|string;
export type ClientToken = string;
export interface ConnectionCredentials {
/**
* The connection token.
*/
ConnectionToken?: ParticipantToken;
/**
* The expiration of the token. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
Expiry?: ISO8601Datetime;
}
export type ConnectionType = "WEBSOCKET"|"CONNECTION_CREDENTIALS"|string;
export type ConnectionTypeList = ConnectionType[];
export type ContactId = string;
export interface CreateParticipantConnectionRequest {
/**
* Type of connection information required.
*/
Type: ConnectionTypeList;
/**
* Participant Token as obtained from StartChatContact API response.
*/
ParticipantToken: ParticipantToken;
}
export interface CreateParticipantConnectionResponse {
/**
* Creates the participant's websocket connection.
*/
Websocket?: Websocket;
/**
* Creates the participant's connection credentials. The authentication token associated with the participant's connection.
*/
ConnectionCredentials?: ConnectionCredentials;
}
export interface DisconnectParticipantRequest {
/**
* A unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
*/
ClientToken?: ClientToken;
/**
* The authentication token associated with the participant's connection.
*/
ConnectionToken: ParticipantToken;
}
export interface DisconnectParticipantResponse {
}
export type DisplayName = string;
export interface GetTranscriptRequest {
/**
* The contactId from the current contact chain for which transcript is needed.
*/
ContactId?: ContactId;
/**
* The maximum number of results to return in the page. Default: 10.
*/
MaxResults?: MaxResults;
/**
* The pagination token. Use the value returned previously in the next subsequent request to retrieve the next set of results.
*/
NextToken?: NextToken;
/**
* The direction from StartPosition from which to retrieve message. Default: BACKWARD when no StartPosition is provided, FORWARD with StartPosition.
*/
ScanDirection?: ScanDirection;
/**
* The sort order for the records. Default: DESCENDING.
*/
SortOrder?: SortKey;
/**
* A filtering option for where to start.
*/
StartPosition?: StartPosition;
/**
* The authentication token associated with the participant's connection.
*/
ConnectionToken: ParticipantToken;
}
export interface GetTranscriptResponse {
/**
* The initial contact ID for the contact.
*/
InitialContactId?: ContactId;
/**
* The list of messages in the session.
*/
Transcript?: Transcript;
/**
* The pagination token. Use the value returned previously in the next subsequent request to retrieve the next set of results.
*/
NextToken?: NextToken;
}
export type ISO8601Datetime = string;
export type Instant = string;
export interface Item {
/**
* The time when the message or event was sent. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
AbsoluteTime?: Instant;
/**
* The content of the message or event.
*/
Content?: ChatContent;
/**
* The type of content of the item.
*/
ContentType?: ChatContentType;
/**
* The ID of the item.
*/
Id?: ChatItemId;
/**
* Type of the item: message or event.
*/
Type?: ChatItemType;
/**
* The ID of the sender in the session.
*/
ParticipantId?: ParticipantId;
/**
* The chat display name of the sender.
*/
DisplayName?: DisplayName;
/**
* The role of the sender. For example, is it a customer, agent, or system.
*/
ParticipantRole?: ParticipantRole;
}
export type MaxResults = number;
export type MostRecent = number;
export type NextToken = string;
export type ParticipantId = string;
export type ParticipantRole = "AGENT"|"CUSTOMER"|"SYSTEM"|string;
export type ParticipantToken = string;
export type PreSignedConnectionUrl = string;
export type ScanDirection = "FORWARD"|"BACKWARD"|string;
export interface SendEventRequest {
/**
* The content type of the request. Supported types are: application/vnd.amazonaws.connect.event.typing application/vnd.amazonaws.connect.event.connection.acknowledged
*/
ContentType: ChatContentType;
/**
* The content of the event to be sent (for example, message text). This is not yet supported.
*/
Content?: ChatContent;
/**
* A unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
*/
ClientToken?: ClientToken;
/**
* The authentication token associated with the participant's connection.
*/
ConnectionToken: ParticipantToken;
}
export interface SendEventResponse {
/**
* The ID of the response.
*/
Id?: ChatItemId;
/**
* The time when the event was sent. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
AbsoluteTime?: Instant;
}
export interface SendMessageRequest {
/**
* The type of the content. Supported types are text/plain.
*/
ContentType: ChatContentType;
/**
* The content of the message.
*/
Content: ChatContent;
/**
* A unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
*/
ClientToken?: ClientToken;
/**
* The authentication token associated with the connection.
*/
ConnectionToken: ParticipantToken;
}
export interface SendMessageResponse {
/**
* The ID of the message.
*/
Id?: ChatItemId;
/**
* The time when the message was sent. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
AbsoluteTime?: Instant;
}
export type SortKey = "DESCENDING"|"ASCENDING"|string;
export interface StartPosition {
/**
* The ID of the message or event where to start.
*/
Id?: ChatItemId;
/**
* The time in ISO format where to start. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
AbsoluteTime?: Instant;
/**
* The start position of the most recent message where you want to start.
*/
MostRecent?: MostRecent;
}
export type Transcript = Item[];
export interface Websocket {
/**
* The URL of the websocket.
*/
Url?: PreSignedConnectionUrl;
/**
* The URL expiration timestamp in ISO date format. It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
ConnectionExpiry?: ISO8601Datetime;
}
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2018-09-07"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the ConnectParticipant client.
*/
export import Types = ConnectParticipant;
}
export = ConnectParticipant; | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://androidmanagement.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Android Management API v1 */
function load(name: "androidmanagement", version: "v1"): PromiseLike<void>;
function load(name: "androidmanagement", version: "v1", callback: () => any): void;
const enterprises: androidmanagement.EnterprisesResource;
const signupUrls: androidmanagement.SignupUrlsResource;
namespace androidmanagement {
interface ApiLevelCondition {
/**
* The minimum desired Android Framework API level. If the device does not meet the minimum requirement, this condition is satisfied. Must be greater than
* zero.
*/
minApiLevel?: number;
}
interface Application {
/** The set of managed properties available to be pre-configured for the application. */
managedProperties?: ManagedProperty[];
/** The name of the application in the form enterprises/{enterpriseId}/applications/{package_name} */
name?: string;
/** The permissions required by the app. */
permissions?: ApplicationPermission[];
/** The title of the application. Localized. */
title?: string;
}
interface ApplicationPermission {
/** A longer description of the permission, giving more details of what it affects. Localized. */
description?: string;
/** The name of the permission. Localized. */
name?: string;
/** An opaque string uniquely identifying the permission. Not localized. */
permissionId?: string;
}
interface ApplicationPolicy {
/**
* The default policy for all permissions requested by the app. If specified, this overrides the policy-level default_permission_policy which applies to
* all apps.
*/
defaultPermissionPolicy?: string;
/** The type of installation to perform. */
installType?: string;
/** Whether the application is allowed to lock itself in full-screen mode. */
lockTaskAllowed?: boolean;
/**
* Managed configuration applied to the app. The format for the configuration is dictated by the ManagedProperty values supported by the app. Each field
* name in the managed configuration must match the key field of the ManagedProperty. The field value must be compatible with the type of the
* ManagedProperty: <table> <tr><td><i>type</i></td><td><i>JSON value</i></td></tr> <tr><td>BOOL</td><td>true or false</td></tr>
* <tr><td>STRING</td><td>string</td></tr> <tr><td>INTEGER</td><td>number</td></tr> <tr><td>CHOICE</td><td>string</td></tr>
* <tr><td>MULTISELECT</td><td>array of strings</td></tr> <tr><td>HIDDEN</td><td>string</td></tr> <tr><td>BUNDLE_ARRAY</td><td>array of objects</td></tr>
* </table>
*/
managedConfiguration?: Record<string, any>;
/** The package name of the app, e.g. com.google.android.youtube for the YouTube app. */
packageName?: string;
/** Explicit permission grants or denials for the app. These values override the default_permission_policy. */
permissionGrants?: PermissionGrant[];
}
interface Command {
/** The timestamp at which the command was created. The timestamp is automatically generated by the server. */
createTime?: string;
/**
* The duration for which the command is valid. The command will expire if not executed by the device during this time. The default duration if
* unspecified is ten minutes. There is no maximum duration.
*/
duration?: string;
/** For commands of type RESET_PASSWORD, optionally specifies the new password. */
newPassword?: string;
/** For commands of type RESET_PASSWORD, optionally specifies flags. */
resetPasswordFlags?: string[];
/** The type of the command. */
type?: string;
}
interface ComplianceRule {
/** A condition which is satisfied if the Android Framework API level on the device does not meet a minimum requirement. */
apiLevelCondition?: ApiLevelCondition;
/**
* If set to true, the rule includes a mitigating action to disable applications so that the device is effectively disabled, but application data is
* preserved. If the device is running an app in locked task mode, the app will be closed and a UI showing the reason for non-compliance will be
* displayed.
*/
disableApps?: boolean;
/** A condition which is satisfied if there exists any matching NonComplianceDetail for the device. */
nonComplianceDetailCondition?: NonComplianceDetailCondition;
}
interface Device {
/** The API level of the Android platform version running on the device. */
apiLevel?: number;
/** The name of the policy that is currently applied by the device. */
appliedPolicyName?: string;
/** The version of the policy that is currently applied by the device. */
appliedPolicyVersion?: string;
/** The state that is currently applied by the device. */
appliedState?: string;
/**
* If the device state is DISABLED, an optional message that is displayed on the device indicating the reason the device is disabled. This field may be
* modified by an update request.
*/
disabledReason?: UserFacingMessage;
/** Displays on the device. This information is only available when displayInfoEnabled is true in the device's policy. */
displays?: Display[];
/** The time of device enrollment. */
enrollmentTime?: string;
/** If this device was enrolled with an enrollment token with additional data provided, this field contains that data. */
enrollmentTokenData?: string;
/** If this device was enrolled with an enrollment token, this field contains the name of the token. */
enrollmentTokenName?: string;
/** Detailed information about the device hardware. */
hardwareInfo?: HardwareInfo;
/** Hardware status samples in chronological order. This information is only available when hardwareStatusEnabled is true in the device's policy. */
hardwareStatusSamples?: HardwareStatus[];
/** The last time the device sent a policy compliance report. */
lastPolicyComplianceReportTime?: string;
/** The last time the device fetched its policy. */
lastPolicySyncTime?: string;
/** The last time the device sent a status report. */
lastStatusReportTime?: string;
/**
* Events related to memory and storage measurements in chronological order. This information is only available when memoryInfoEnabled is true in the
* device's policy.
*/
memoryEvents?: MemoryEvent[];
/** Memory information. This information is only available when memoryInfoEnabled is true in the device's policy. */
memoryInfo?: MemoryInfo;
/** The name of the device in the form enterprises/{enterpriseId}/devices/{deviceId} */
name?: string;
/** Device network information. This information is only available when networkInfoEnabled is true in the device's policy. */
networkInfo?: NetworkInfo;
/** Details about policy settings for which the device is not in compliance. */
nonComplianceDetails?: NonComplianceDetail[];
/** Whether the device is compliant with its policy. */
policyCompliant?: boolean;
/**
* The name of the policy that is intended to be applied to the device. If empty, the policy with id default is applied. This field may be modified by an
* update request. The name of the policy is in the form enterprises/{enterpriseId}/policies/{policyId}. It is also permissible to only specify the
* policyId when updating this field as long as the policyId contains no slashes since the rest of the policy name can be inferred from context.
*/
policyName?: string;
/**
* Power management events on the device in chronological order. This information is only available when powerManagementEventsEnabled is true in the
* device's policy.
*/
powerManagementEvents?: PowerManagementEvent[];
/**
* The previous device names used for the same physical device when it has been enrolled multiple times. The serial number is used as the unique
* identifier to determine if the same physical device has enrolled previously. The names are in chronological order.
*/
previousDeviceNames?: string[];
/** Detailed information about the device software. This information is only available when softwareInfoEnabled is true in the device's policy. */
softwareInfo?: SoftwareInfo;
/**
* The state that is intended to be applied to the device. This field may be modified by an update request. Note that UpdateDevice only handles toggling
* between ACTIVE and DISABLED states. Use the delete device method to cause the device to enter the DELETED state.
*/
state?: string;
/**
* The resource name of the user of the device in the form enterprises/{enterpriseId}/users/{userId}. This is the name of the device account automatically
* created for this device.
*/
userName?: string;
}
interface Display {
/** Display density expressed as dots-per-inch. */
density?: number;
/** Unique display id. */
displayId?: number;
/** Display height in pixels. */
height?: number;
/** Name of the display. */
name?: string;
/** Refresh rate of the display in frames per second. */
refreshRate?: number;
/** State of the display. */
state?: string;
/** Display width in pixels. */
width?: number;
}
interface EnrollmentToken {
/**
* Optional, arbitrary data associated with the enrollment token. This could contain, for example, the id of an org unit to which the device is assigned
* after enrollment. After a device enrolls with the token, this data will be exposed in the enrollment_token_data field of the Device resource. The data
* must be 1024 characters or less; otherwise, the creation request will fail.
*/
additionalData?: string;
/** The duration of the token. If not specified, the duration will be 1 hour. The allowed range is 1 minute to 30 days. */
duration?: string;
/** The expiration time of the token. This is a read-only field generated by the server. */
expirationTimestamp?: string;
/**
* The name of the enrollment token, which is generated by the server during creation, in the form
* enterprises/{enterpriseId}/enrollmentTokens/{enrollmentTokenId}
*/
name?: string;
/**
* The name of the policy that will be initially applied to the enrolled device in the form enterprises/{enterpriseId}/policies/{policyId}. If not
* specified, the policy with id default is applied. It is permissible to only specify the policyId when updating this field as long as the policyId
* contains no slashes since the rest of the policy name can be inferred from context.
*/
policyName?: string;
/**
* A JSON string whose UTF-8 representation can be used to generate a QR code to enroll a device with this enrollment token. To enroll a device using NFC,
* the NFC record must contain a serialized java.util.Properties representation of the properties in the JSON.
*/
qrCode?: string;
/** The token value which is passed to the device and authorizes the device to enroll. This is a read-only field generated by the server. */
value?: string;
}
interface Enterprise {
/**
* Whether app auto-approval is enabled. When enabled, apps installed via policy for this enterprise have all permissions automatically approved. When
* enabled, it is the caller's responsibility to display the permissions required by an app to the enterprise admin before setting the app to be installed
* in a policy.
*/
appAutoApprovalEnabled?: boolean;
/** The notification types to enable via Google Cloud Pub/Sub. */
enabledNotificationTypes?: string[];
/** The name of the enterprise as it will appear to users. */
enterpriseDisplayName?: string;
/**
* An image displayed as a logo during device provisioning. Supported types are: image/bmp, image/gif, image/x-ico, image/jpeg, image/png, image/webp,
* image/vnd.wap.wbmp, image/x-adobe-dng.
*/
logo?: ExternalData;
/** The name of the enterprise which is generated by the server during creation, in the form enterprises/{enterpriseId} */
name?: string;
/**
* A color in RGB format indicating the predominant color to display in the device management app UI. The color components are stored as follows: (red <<
* 16) | (green << 8) | blue, where each component may take a value between 0 and 255 inclusive.
*/
primaryColor?: number;
/**
* When Cloud Pub/Sub notifications are enabled, this field is required to indicate the topic to which the notifications will be published. The format of
* this field is projects/{project}/topics/{topic}. You must have granted the publish permission on this topic to
* android-cloud-policy@system.gserviceaccount.com
*/
pubsubTopic?: string;
}
interface ExternalData {
/** The base-64 encoded SHA-256 hash of the content hosted at url. If the content does not match this hash, Android Device Policy will not use the data. */
sha256Hash?: string;
/**
* The absolute URL to the data, which must use either the http or https scheme. Android Device Policy does not provide any credentials in the GET
* request, so the URL must be publicly accessible. Including a long, random component in the URL may be used to prevent attackers from discovering the
* URL.
*/
url?: string;
}
interface HardwareInfo {
/** Battery shutdown temperature thresholds in Celsius for each battery on the device. */
batteryShutdownTemperatures?: number[];
/** Battery throttling temperature thresholds in Celsius for each battery on the device. */
batteryThrottlingTemperatures?: number[];
/** Brand of the device, e.g. Google. */
brand?: string;
/** CPU shutdown temperature thresholds in Celsius for each CPU on the device. */
cpuShutdownTemperatures?: number[];
/** CPU throttling temperature thresholds in Celsius for each CPU on the device. */
cpuThrottlingTemperatures?: number[];
/** Baseband version, e.g. MDM9625_104662.22.05.34p. */
deviceBasebandVersion?: string;
/** GPU shutdown temperature thresholds in Celsius for each GPU on the device. */
gpuShutdownTemperatures?: number[];
/** GPU throttling temperature thresholds in Celsius for each GPU on the device. */
gpuThrottlingTemperatures?: number[];
/** Name of the hardware, e.g. Angler. */
hardware?: string;
/** Manufacturer, e.g. Motorola. */
manufacturer?: string;
/** The model of the device, e.g. Asus Nexus 7. */
model?: string;
/** The device serial number. */
serialNumber?: string;
/** Device skin shutdown temperature thresholds in Celsius. */
skinShutdownTemperatures?: number[];
/** Device skin throttling temperature thresholds in Celsius. */
skinThrottlingTemperatures?: number[];
}
interface HardwareStatus {
/** Current battery temperatures in Celsius for each battery on the device. */
batteryTemperatures?: number[];
/** Current CPU temperatures in Celsius for each CPU on the device. */
cpuTemperatures?: number[];
/**
* CPU usages in percentage for each core available on the device. Usage is 0 for each unplugged core. Empty array implies that CPU usage is not supported
* in the system.
*/
cpuUsages?: number[];
/** The time the measurements were taken. */
createTime?: string;
/** Fan speeds in RPM for each fan on the device. Empty array means that there are no fans or fan speed is not supported on the system. */
fanSpeeds?: number[];
/** Current GPU temperatures in Celsius for each GPU on the device. */
gpuTemperatures?: number[];
/** Current device skin temperatures in Celsius. */
skinTemperatures?: number[];
}
interface ListDevicesResponse {
/** The list of devices. */
devices?: Device[];
/** If there are more results, a token to retrieve next page of results. */
nextPageToken?: string;
}
interface ListOperationsResponse {
/** The standard List next-page token. */
nextPageToken?: string;
/** A list of operations that matches the specified filter in the request. */
operations?: Operation[];
}
interface ListPoliciesResponse {
/** If there are more results, a token to retrieve next page of results. */
nextPageToken?: string;
/** The list of policies. */
policies?: Policy[];
}
interface ManagedProperty {
/** The default value of the properties. BUNDLE_ARRAY properties never have a default value. */
defaultValue?: any;
/** A longer description of the property, giving more detail of what it affects. Localized. */
description?: string;
/** For CHOICE or MULTISELECT properties, the list of possible entries. */
entries?: ManagedPropertyEntry[];
/** The unique key that the application uses to identify the property, e.g. "com.google.android.gm.fieldname". */
key?: string;
/** For BUNDLE_ARRAY properties, the list of nested properties. A BUNDLE_ARRAY property is at most two levels deep. */
nestedProperties?: ManagedProperty[];
/** The name of the property. Localized. */
title?: string;
/** The type of the property. */
type?: string;
}
interface ManagedPropertyEntry {
/** The human-readable name of the value. Localized. */
name?: string;
/** The machine-readable value of the entry, which should be used in the configuration. Not localized. */
value?: string;
}
interface MemoryEvent {
/** The number of free bytes in the medium, or for EXTERNAL_STORAGE_DETECTED, the total capacity in bytes of the storage medium. */
byteCount?: string;
/** The creation time of the event. */
createTime?: string;
/** Event type. */
eventType?: string;
}
interface MemoryInfo {
/** Total internal storage on device in bytes. */
totalInternalStorage?: string;
/** Total RAM on device in bytes. */
totalRam?: string;
}
interface NetworkInfo {
/** IMEI number of the GSM device, e.g. A1000031212. */
imei?: string;
/** MEID number of the CDMA device, e.g. A00000292788E1. */
meid?: string;
/** WiFi MAC address of the device, e.g. 7c:11:11:11:11:11. */
wifiMacAddress?: string;
}
interface NonComplianceDetail {
/** If the policy setting could not be applied, the current value of the setting on the device. */
currentValue?: any;
/**
* For settings with nested fields, if a particular nested field is out of compliance, this specifies the full path to the offending field. The path is
* formatted in the same way the policy JSON field would be referenced in JavaScript, that is: 1) For object-typed fields, the field name is followed by a
* dot then by a subfield name. 2) For array-typed fields, the field name is followed by the array index enclosed in brackets. For example, to indicate
* a problem with the url field in the externalData field in the 3rd application, the path would be applications[2].externalData.url
*/
fieldPath?: string;
/**
* If package_name is set and the non-compliance reason is APP_NOT_INSTALLED or APP_NOT_UPDATED, the detailed reason the app cannot be installed or
* updated.
*/
installationFailureReason?: string;
/** The reason the device is not in compliance with the setting. */
nonComplianceReason?: string;
/** The package name indicating which application is out of compliance, if applicable. */
packageName?: string;
/** The name of the policy setting. This is the JSON field name of a top-level Policy field. */
settingName?: string;
}
interface NonComplianceDetailCondition {
/** The reason the device is not in compliance with the setting. If not set, then this condition matches any reason. */
nonComplianceReason?: string;
/** The package name indicating which application is out of compliance. If not set, then this condition matches any package name. */
packageName?: string;
/** The name of the policy setting. This is the JSON field name of a top-level Policy field. If not set, then this condition matches any setting name. */
settingName?: string;
}
interface Operation {
/** If the value is false, it means the operation is still in progress. If true, the operation is completed, and either error or response is available. */
done?: boolean;
/** The error result of the operation in case of failure or cancellation. */
error?: Status;
/**
* Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some
* services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
*/
metadata?: Record<string, any>;
/**
* The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the name should
* have the format of operations/some/unique/name.
*/
name?: string;
/**
* The normal response of the operation in case of success. If the original method returns no data on success, such as Delete, the response is
* google.protobuf.Empty. If the original method is standard Get/Create/Update, the response should be the resource. For other methods, the response
* should have the type XxxResponse, where Xxx is the original method name. For example, if the original method name is TakeSnapshot(), the inferred
* response type is TakeSnapshotResponse.
*/
response?: Record<string, any>;
}
interface PasswordRequirements {
/** A device will be wiped after too many incorrect device-unlock passwords have been entered. A value of 0 means there is no restriction. */
maximumFailedPasswordsForWipe?: number;
/** Password expiration timeout. */
passwordExpirationTimeout?: string;
/**
* The length of the password history. After setting this, the user will not be able to enter a new password that is the same as any password in the
* history. A value of 0 means there is no restriction.
*/
passwordHistoryLength?: number;
/**
* The minimum allowed password length. A value of 0 means there is no restriction. Only enforced when password_quality is NUMERIC, NUMERIC_COMPLEX,
* ALPHABETIC, ALPHANUMERIC, or COMPLEX.
*/
passwordMinimumLength?: number;
/** Minimum number of letters required in the password. Only enforced when password_quality is COMPLEX. */
passwordMinimumLetters?: number;
/** Minimum number of lower case letters required in the password. Only enforced when password_quality is COMPLEX. */
passwordMinimumLowerCase?: number;
/** Minimum number of non-letter characters (numerical digits or symbols) required in the password. Only enforced when password_quality is COMPLEX. */
passwordMinimumNonLetter?: number;
/** Minimum number of numerical digits required in the password. Only enforced when password_quality is COMPLEX. */
passwordMinimumNumeric?: number;
/** Minimum number of symbols required in the password. Only enforced when password_quality is COMPLEX. */
passwordMinimumSymbols?: number;
/** Minimum number of upper case letters required in the password. Only enforced when password_quality is COMPLEX. */
passwordMinimumUpperCase?: number;
/** The required password quality. */
passwordQuality?: string;
}
interface PermissionGrant {
/** The android permission, e.g. android.permission.READ_CALENDAR. */
permission?: string;
/** The policy for granting the permission. */
policy?: string;
}
interface PersistentPreferredActivity {
/**
* The intent actions to match in the filter. If any actions are included in the filter, then an intent's action must be one of those values for it to
* match. If no actions are included, the intent action is ignored.
*/
actions?: string[];
/**
* The intent categories to match in the filter. An intent includes the categories that it requires, all of which must be included in the filter in order
* to match. In other words, adding a category to the filter has no impact on matching unless that category is specified in the intent.
*/
categories?: string[];
/**
* The activity that should be the default intent handler. This should be an Android component name, e.g. com.android.enterprise.app/.MainActivity.
* Alternatively, the value may be the package name of an app, which causes Android Device Policy to choose an appropriate activity from the app to handle
* the intent.
*/
receiverActivity?: string;
}
interface Policy {
/** Whether adding new users and profiles is disabled. */
addUserDisabled?: boolean;
/** Whether adjusting the master volume is disabled. */
adjustVolumeDisabled?: boolean;
/** Policy applied to apps. */
applications?: ApplicationPolicy[];
/** Whether auto time is required, which prevents the user from manually setting the date and time. */
autoTimeRequired?: boolean;
/**
* Whether applications other than the ones configured in applications are blocked from being installed. When set, applications that were installed under
* a previous policy but no longer appear in the policy are automatically uninstalled.
*/
blockApplicationsEnabled?: boolean;
/** Whether all cameras on the device are disabled. */
cameraDisabled?: boolean;
/**
* Rules declaring which mitigating actions to take when a device is not compliant with its policy. When the conditions for multiple rules are satisfied,
* all of the mitigating actions for the rules are taken. There is a maximum limit of 100 rules.
*/
complianceRules?: ComplianceRule[];
/** Whether the user is allowed to enable debugging features. */
debuggingFeaturesAllowed?: boolean;
/** The default permission policy for requests for runtime permissions. */
defaultPermissionPolicy?: string;
/** Whether factory resetting from settings is disabled. */
factoryResetDisabled?: boolean;
/**
* Email addresses of device administrators for factory reset protection. When the device is factory reset, it will require one of these admins to log in
* with the Google account email and password to unlock the device. If no admins are specified, the device will not provide factory reset protection.
*/
frpAdminEmails?: string[];
/** Whether the user is allowed to have fun. Controls whether the Easter egg game in Settings is disabled. */
funDisabled?: boolean;
/** Whether the user is allowed to enable the "Unknown Sources" setting, which allows installation of apps from unknown sources. */
installUnknownSourcesAllowed?: boolean;
/** Whether the keyguard is disabled. */
keyguardDisabled?: boolean;
/** Maximum time in milliseconds for user activity until the device will lock. A value of 0 means there is no restriction. */
maximumTimeToLock?: string;
/** Whether adding or removing accounts is disabled. */
modifyAccountsDisabled?: boolean;
/** The name of the policy in the form enterprises/{enterpriseId}/policies/{policyId} */
name?: string;
/**
* Whether the network escape hatch is enabled. If a network connection can't be made at boot time, the escape hatch prompts the user to temporarily
* connect to a network in order to refresh the device policy. After applying policy, the temporary network will be forgotten and the device will continue
* booting. This prevents being unable to connect to a network if there is no suitable network in the last policy and the device boots into an app in lock
* task mode, or the user is otherwise unable to reach device settings.
*/
networkEscapeHatchEnabled?: boolean;
/** Network configuration for the device. See configure networks for more information. */
openNetworkConfiguration?: Record<string, any>;
/** Password requirements. */
passwordRequirements?: PasswordRequirements;
/** Default intent handler activities. */
persistentPreferredActivities?: PersistentPreferredActivity[];
/** Whether removing other users is disabled. */
removeUserDisabled?: boolean;
/** Whether rebooting the device into safe boot is disabled. */
safeBootDisabled?: boolean;
/** Whether screen capture is disabled. */
screenCaptureDisabled?: boolean;
/** Whether the status bar is disabled. This disables notifications, quick settings and other screen overlays that allow escape from full-screen mode. */
statusBarDisabled?: boolean;
/** Status reporting settings */
statusReportingSettings?: StatusReportingSettings;
/**
* The battery plugged in modes for which the device stays on. When using this setting, it is recommended to clear maximum_time_to_lock so that the device
* doesn't lock itself while it stays on.
*/
stayOnPluggedModes?: string[];
/**
* The system update policy, which controls how OS updates are applied. If the update type is WINDOWED and the device has a device account, the update
* window will automatically apply to Play app updates as well.
*/
systemUpdate?: SystemUpdate;
/** Whether the microphone is muted and adjusting microphone volume is disabled. */
unmuteMicrophoneDisabled?: boolean;
/** The version of the policy. This is a read-only field. The version is incremented each time the policy is updated. */
version?: string;
/** Whether configuring WiFi access points is disabled. */
wifiConfigDisabled?: boolean;
/** Whether WiFi networks defined in Open Network Configuration are locked so they cannot be edited by the user. */
wifiConfigsLockdownEnabled?: boolean;
}
interface PowerManagementEvent {
/** For BATTERY_LEVEL_COLLECTED events, the battery level as a percentage. */
batteryLevel?: number;
/** The creation time of the event. */
createTime?: string;
/** Event type. */
eventType?: string;
}
interface SignupUrl {
/** The name of the resource. This must be included in the create enterprise request at the end of the signup flow. */
name?: string;
/** A URL under which the Admin can sign up for an enterprise. The page pointed to cannot be rendered in an iframe. */
url?: string;
}
interface SoftwareInfo {
/** Android build Id string meant for displaying to the user, e.g. shamu-userdebug 6.0.1 MOB30I 2756745 dev-keys. */
androidBuildNumber?: string;
/** Build time. */
androidBuildTime?: string;
/** The user visible Android version string, e.g. 6.0.1. */
androidVersion?: string;
/** The system bootloader version number, e.g. 0.6.7. */
bootloaderVersion?: string;
/** Kernel version, e.g. 2.6.32.9-g103d848. */
deviceKernelVersion?: string;
/** Security patch level, e.g. 2016-05-01. */
securityPatchLevel?: string;
}
interface Status {
/** The status code, which should be an enum value of google.rpc.Code. */
code?: number;
/** A list of messages that carry the error details. There is a common set of message types for APIs to use. */
details?: Array<Record<string, any>>;
/**
* A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized by the client.
*/
message?: string;
}
interface StatusReportingSettings {
/** Whether displays reporting is enabled. */
displayInfoEnabled?: boolean;
/** Whether hardware status reporting is enabled. */
hardwareStatusEnabled?: boolean;
/** Whether memory info reporting is enabled. */
memoryInfoEnabled?: boolean;
/** Whether network info reporting is enabled. */
networkInfoEnabled?: boolean;
/** Whether power management event reporting is enabled. */
powerManagementEventsEnabled?: boolean;
/** Whether software info reporting is enabled. */
softwareInfoEnabled?: boolean;
}
interface SystemUpdate {
/**
* If the type is WINDOWED, the end of the maintenance window, measured as the number of minutes after midnight in device local time. This value must be
* between 0 and 1439, inclusive. If this value is less than start_minutes, then the maintenance window spans midnight. If the maintenance window
* specified is smaller than 30 minutes, the actual window is extended to 30 minutes beyond the start time.
*/
endMinutes?: number;
/**
* If the type is WINDOWED, the start of the maintenance window, measured as the number of minutes after midnight in device local time. This value must be
* between 0 and 1439, inclusive.
*/
startMinutes?: number;
/** The type of system update to configure. */
type?: string;
}
interface UserFacingMessage {
/**
* The default message that gets displayed if no localized message is specified, or the user's locale does not match with any of the localized messages. A
* default message must be provided if any localized messages are provided.
*/
defaultMessage?: string;
/** A map which contains <locale, message> pairs. The locale is a BCP 47 language code, e.g. en-US, es-ES, fr. */
localizedMessages?: Record<string, string>;
}
interface WebToken {
/** The name of the web token, which is generated by the server during creation, in the form enterprises/{enterpriseId}/webTokens/{webTokenId}. */
name?: string;
/**
* The URL of the parent frame hosting the iframe with the embedded UI. To prevent XSS, the iframe may not be hosted at other URLs. The URL must use the
* https scheme.
*/
parentFrameUrl?: string;
/** Permissions the admin may exercise in the embedded UI. The admin must have all of these permissions in order to view the UI. */
permissions?: string[];
/** The token value which is used in the hosting page to generate the iframe with the embedded UI. This is a read-only field generated by the server. */
value?: string;
}
interface ApplicationsResource {
/** Gets info about an application. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The preferred language for localized application info, as a BCP47 tag (e.g. "en-US", "de"). If not specified the default language of the application
* will be used.
*/
languageCode?: string;
/** The name of the application in the form enterprises/{enterpriseId}/applications/{package_name} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Application>;
}
interface OperationsResource {
/**
* Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If
* the server doesn't support this method, it returns google.rpc.Code.UNIMPLEMENTED. Clients can use Operations.GetOperation or other methods to check
* whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted;
* instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to Code.CANCELLED.
*/
cancel(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be cancelled. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the
* operation. If the server doesn't support this method, it returns google.rpc.Code.UNIMPLEMENTED.
*/
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be deleted. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API
* service.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/**
* Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns UNIMPLEMENTED.NOTE: the name
* binding allows API services to override the binding to use different resource name schemes, such as users/*/operations. To override the binding, API
* services can add a binding such as "/v1/{name=users/*}/operations" to their service configuration. For backwards compatibility, the default name
* includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection
* id.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The standard list filter. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation's parent resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The standard list page size. */
pageSize?: number;
/** The standard list page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListOperationsResponse>;
}
interface DevicesResource {
/** Deletes a device, which causes the device to be wiped. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the device in the form enterprises/{enterpriseId}/devices/{deviceId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Gets a device. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the device in the form enterprises/{enterpriseId}/devices/{deviceId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Device>;
/**
* Issues a command to a device. The Operation resource returned contains a Command in its metadata field. Use the get operation method to get the status
* of the command.
*/
issueCommand(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the device in the form enterprises/{enterpriseId}/devices/{deviceId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/** Lists devices for a given enterprise. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The requested page size. The actual page size may be fixed to a min or max value. */
pageSize?: number;
/** A token identifying a page of results the server should return. */
pageToken?: string;
/** The name of the enterprise in the form enterprises/{enterpriseId} */
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListDevicesResponse>;
/** Updates a device. */
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the device in the form enterprises/{enterpriseId}/devices/{deviceId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** The field mask indicating the fields to update. If not set, all modifiable fields will be modified. */
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Device>;
operations: OperationsResource;
}
interface EnrollmentTokensResource {
/** Creates an enrollment token for a given enterprise. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The name of the enterprise in the form enterprises/{enterpriseId} */
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<EnrollmentToken>;
/** Deletes an enrollment token, which prevents future use of the token. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the enrollment token in the form enterprises/{enterpriseId}/enrollmentTokens/{enrollmentTokenId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
}
interface PoliciesResource {
/** Deletes a policy. This operation is only permitted if no devices are currently referencing the policy. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the policy in the form enterprises/{enterpriseId}/policies/{policyId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Gets a policy. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the policy in the form enterprises/{enterpriseId}/policies/{policyId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/** Lists policies for a given enterprise. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The requested page size. The actual page size may be fixed to a min or max value. */
pageSize?: number;
/** A token identifying a page of results the server should return. */
pageToken?: string;
/** The name of the enterprise in the form enterprises/{enterpriseId} */
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListPoliciesResponse>;
/** Updates or creates a policy. */
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the policy in the form enterprises/{enterpriseId}/policies/{policyId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** The field mask indicating the fields to update. If not set, all modifiable fields will be modified. */
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
}
interface WebTokensResource {
/** Creates a web token to access an embeddable managed Google Play web UI for a given enterprise. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The name of the enterprise in the form enterprises/{enterpriseId} */
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<WebToken>;
}
interface EnterprisesResource {
/** Creates an enterprise by completing the enterprise signup flow. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** The enterprise token appended to the callback URL. */
enterpriseToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The id of the Google Cloud Platform project which will own the enterprise. */
projectId?: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** The name of the SignupUrl used to sign up for the enterprise. */
signupUrlName?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Enterprise>;
/** Gets an enterprise. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the enterprise in the form enterprises/{enterpriseId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Enterprise>;
/** Updates an enterprise. */
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the enterprise in the form enterprises/{enterpriseId} */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** The field mask indicating the fields to update. If not set, all modifiable fields will be modified. */
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Enterprise>;
applications: ApplicationsResource;
devices: DevicesResource;
enrollmentTokens: EnrollmentTokensResource;
policies: PoliciesResource;
webTokens: WebTokensResource;
}
interface SignupUrlsResource {
/** Creates an enterprise signup URL. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The callback URL to which the admin will be redirected after successfully creating an enterprise. Before redirecting there the system will add a query
* parameter to this URL named enterpriseToken which will contain an opaque token to be used for the create enterprise request. The URL will be parsed
* then reformatted in order to add the enterpriseToken parameter, so there may be some minor formatting changes.
*/
callbackUrl?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The id of the Google Cloud Platform project which will own the enterprise. */
projectId?: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<SignupUrl>;
}
}
} | the_stack |
import {FieldStats, getAllKeys, getStats, isInteger} from '../stats';
const {expect} = chai;
describe('getAllKeys', () => {
it('should return an empty array for null input', () => {
const ret = getAllKeys(null);
expect(ret).to.deep.equal([]);
});
it('should return an empty array for an empty array input', () => {
const ret = getAllKeys([]);
expect(ret).to.deep.equal([]);
});
it('should return all keys from a single object', () => {
const ret = getAllKeys([{red: 255, blue: 0, green: 0}]);
expect(ret).to.deep.equal(['red', 'blue', 'green']);
});
it('should return all keys from multiple objects', () => {
const ret = getAllKeys([{red: 255, blue: 0}, {blue: 255, green: 0}]);
expect(ret).to.deep.equal(['red', 'blue', 'green']);
});
it('should ignore null objects in the list', () => {
const ret = getAllKeys([{red: 255}, null, {blue: 0}, null, {green: 0}]);
expect(ret).to.deep.equal(['red', 'blue', 'green']);
});
});
describe('isInteger', () => {
it('should detect integer values as integers', () => {
expect(isInteger(-10000)).to.equal(true);
expect(isInteger(-1)).to.equal(true);
expect(isInteger(0)).to.equal(true);
expect(isInteger(1)).to.equal(true);
expect(isInteger(10000)).to.equal(true);
});
it('should detect fractional number values as non-integers', () => {
expect(isInteger(0.01)).to.equal(false);
expect(isInteger(-2.5)).to.equal(false);
expect(isInteger(Math.PI)).to.equal(false);
});
it('should detect NaN values as non-integers', () => {
expect(isInteger(NaN)).to.equal(false);
});
it('should detect infinite values as non-integers', () => {
expect(isInteger(Infinity)).to.equal(false);
expect(isInteger(-Infinity)).to.equal(false);
});
it('should detect NaN values as non-integers', () => {
expect(isInteger(null)).to.equal(false);
expect(isInteger(undefined)).to.equal(false);
});
it('should detect string values as non-integers', () => {
expect(isInteger('' as any)).to.equal(false);
expect(isInteger('foo' as any)).to.equal(false);
expect(isInteger('200000' as any)).to.equal(false);
expect(isInteger('-300000' as any)).to.equal(false);
});
it('should detect array and object values as non-integers', () => {
expect(isInteger([-1] as any)).to.equal(false);
expect(isInteger(new Number(42) as any)).to.equal(false);
expect(isInteger({valueOf: () => 2} as any)).to.equal(false);
});
});
describe('FieldStats', () => {
describe('numberMin', () => {
it('should contain null to start', () => {
const stats = new FieldStats();
expect(stats.numberMin).to.equal(null);
});
});
describe('numberMax', () => {
it('should contain null to start', () => {
const stats = new FieldStats();
expect(stats.numberMax).to.equal(null);
});
});
describe('isNumeric', () => {
it('should identify numeric fields', () => {
const stats = new FieldStats();
stats.totalCount = 2;
stats.numberCount = 2;
stats.stringCount = 0;
stats.otherCount = 0;
stats.numberMin = -100;
stats.numberMax = 100;
expect(stats.isNumeric()).to.equal(true);
});
it('should identify non-numeric fields', () => {
const stats = new FieldStats();
stats.totalCount = 2;
stats.numberCount = 0;
stats.stringCount = 2;
stats.otherCount = 0;
stats.numberMin = null;
stats.numberMax = null;
expect(stats.isNumeric()).to.equal(false);
});
});
describe('isInteger', () => {
it('should return true for integer-only fields', () => {
const stats = new FieldStats();
stats.totalCount = 2;
stats.numberCount = 2;
stats.integerCount = 2;
stats.stringCount = 0;
stats.otherCount = 0;
stats.numberMin = -100;
stats.numberMax = 100;
expect(stats.isInteger()).to.equal(true);
});
it('should return true for integer + non-numeric fields', () => {
const stats = new FieldStats();
stats.totalCount = 4;
stats.numberCount = 2;
stats.integerCount = 2;
stats.stringCount = 2;
stats.otherCount = 0;
stats.numberMin = -100;
stats.numberMax = 100;
expect(stats.isInteger()).to.equal(true);
});
it('should return false for non-integer numeric fields', () => {
const stats = new FieldStats();
stats.totalCount = 2;
stats.numberCount = 2;
stats.integerCount = 0;
stats.otherCount = 0;
stats.numberMin = 0.1;
stats.numberMax = 0.9;
expect(stats.isInteger()).to.equal(false);
});
it('should return false for non-integer non-numeric fields', () => {
const stats = new FieldStats();
stats.totalCount = 2;
stats.numberCount = 0;
stats.integerCount = 0;
stats.otherCount = 0;
stats.numberMin = null;
stats.numberMax = null;
expect(stats.isInteger()).to.equal(false);
});
});
});
describe('getStats', () => {
it('should return an empty object for null or empty input', () => {
expect(getStats(null)).to.deep.equal({});
expect(getStats([])).to.deep.equal({});
});
it('should return an empty object for array of empty objects', () => {
expect(getStats([null, null])).to.deep.equal({});
expect(getStats([{}, {}])).to.deep.equal({});
});
it('should describe objects with numeric values', () => {
let stats: {[field: string]: FieldStats};
stats = getStats([{red: 255}]);
expect(stats['red'].totalCount).to.equal(1);
expect(stats['red'].uniqueCount).to.equal(1);
expect(stats['red'].numberCount).to.equal(1);
expect(stats['red'].stringCount).to.equal(0);
expect(stats['red'].otherCount).to.equal(0);
expect(stats['red'].numberMin).to.equal(255);
expect(stats['red'].numberMax).to.equal(255);
stats = getStats([{red: NaN}]);
expect(stats['red'].totalCount).to.equal(1);
expect(stats['red'].uniqueCount).to.equal(1);
expect(stats['red'].numberCount).to.equal(1);
expect(stats['red'].stringCount).to.equal(0);
expect(stats['red'].otherCount).to.equal(0);
expect(stats['red'].numberMin).to.equal(null);
expect(stats['red'].numberMax).to.equal(null);
stats = getStats([{red: 255, green: 255, blue: 0}]);
expect(stats['red'].totalCount).to.equal(1);
expect(stats['red'].uniqueCount).to.equal(1);
expect(stats['red'].numberCount).to.equal(1);
expect(stats['red'].stringCount).to.equal(0);
expect(stats['red'].otherCount).to.equal(0);
expect(stats['red'].numberMin).to.equal(255);
expect(stats['red'].numberMax).to.equal(255);
expect(stats['green'].totalCount).to.equal(1);
expect(stats['green'].uniqueCount).to.equal(1);
expect(stats['green'].numberCount).to.equal(1);
expect(stats['green'].stringCount).to.equal(0);
expect(stats['green'].otherCount).to.equal(0);
expect(stats['green'].numberMin).to.equal(255);
expect(stats['green'].numberMax).to.equal(255);
expect(stats['blue'].totalCount).to.equal(1);
expect(stats['blue'].uniqueCount).to.equal(1);
expect(stats['blue'].numberCount).to.equal(1);
expect(stats['blue'].stringCount).to.equal(0);
expect(stats['blue'].otherCount).to.equal(0);
expect(stats['blue'].numberMin).to.equal(0);
expect(stats['blue'].numberMax).to.equal(0);
stats = getStats([{red: 255}, {green: 255}, {blue: 0}]);
expect(stats['red'].totalCount).to.equal(1);
expect(stats['red'].uniqueCount).to.equal(1);
expect(stats['red'].numberCount).to.equal(1);
expect(stats['red'].stringCount).to.equal(0);
expect(stats['red'].otherCount).to.equal(0);
expect(stats['red'].numberMin).to.equal(255);
expect(stats['red'].numberMax).to.equal(255);
expect(stats['green'].totalCount).to.equal(1);
expect(stats['green'].uniqueCount).to.equal(1);
expect(stats['green'].numberCount).to.equal(1);
expect(stats['green'].stringCount).to.equal(0);
expect(stats['green'].otherCount).to.equal(0);
expect(stats['green'].numberMin).to.equal(255);
expect(stats['green'].numberMax).to.equal(255);
expect(stats['blue'].totalCount).to.equal(1);
expect(stats['blue'].uniqueCount).to.equal(1);
expect(stats['blue'].numberCount).to.equal(1);
expect(stats['blue'].stringCount).to.equal(0);
expect(stats['blue'].otherCount).to.equal(0);
expect(stats['blue'].numberMin).to.equal(0);
expect(stats['blue'].numberMax).to.equal(0);
stats = getStats([{red: 0}, {green: 255}, {red: 255}]);
expect(stats['red'].totalCount).to.equal(2);
expect(stats['red'].uniqueCount).to.equal(2);
expect(stats['red'].numberCount).to.equal(2);
expect(stats['red'].stringCount).to.equal(0);
expect(stats['red'].otherCount).to.equal(0);
expect(stats['red'].numberMin).to.equal(0);
expect(stats['red'].numberMax).to.equal(255);
expect(stats['green'].totalCount).to.equal(1);
expect(stats['green'].uniqueCount).to.equal(1);
expect(stats['green'].numberCount).to.equal(1);
expect(stats['green'].stringCount).to.equal(0);
expect(stats['green'].otherCount).to.equal(0);
expect(stats['green'].numberMin).to.equal(255);
expect(stats['green'].numberMax).to.equal(255);
});
it('should count unique values', () => {
const stats =
getStats([{fruit: 'apple'}, {fruit: 'apple'}, {fruit: 'banana'}]);
expect(stats['fruit'].totalCount).to.equal(3);
expect(stats['fruit'].uniqueCount).to.equal(2);
expect(stats['fruit'].numberCount).to.equal(0);
expect(stats['fruit'].stringCount).to.equal(3);
expect(stats['fruit'].otherCount).to.equal(0);
});
it('should describe objects with string values', () => {
let stats: {[field: string]: FieldStats};
stats = getStats([{fruit: 'banana'}]);
expect(stats['fruit'].totalCount).to.equal(1);
expect(stats['fruit'].uniqueCount).to.equal(1);
expect(stats['fruit'].numberCount).to.equal(0);
expect(stats['fruit'].stringCount).to.equal(1);
expect(stats['fruit'].otherCount).to.equal(0);
expect(stats['fruit'].stringMinLength).to.equal(6);
expect(stats['fruit'].stringMaxLength).to.equal(6);
expect(stats['fruit'].stringMeanLength).to.equal(6);
expect(stats['fruit'].stringLengthsCount).to.equal(1);
expect(stats['fruit'].stringLengthsHash).to.deep.equal({6: 1});
stats = getStats([{fruit: 'apple'}, {fruit: 'banana'}]);
expect(stats['fruit'].totalCount).to.equal(2);
expect(stats['fruit'].uniqueCount).to.equal(2);
expect(stats['fruit'].numberCount).to.equal(0);
expect(stats['fruit'].stringCount).to.equal(2);
expect(stats['fruit'].otherCount).to.equal(0);
expect(stats['fruit'].stringMinLength).to.equal(5);
expect(stats['fruit'].stringMaxLength).to.equal(6);
expect(stats['fruit'].stringMeanLength).to.equal(5.5);
expect(stats['fruit'].stringLengthsCount).to.equal(2);
expect(stats['fruit'].stringLengthsHash).to.deep.equal({5: 1, 6: 1});
});
it('should describe objects with other values', () => {
const stats = getStats([{obj: {}, array: [], missing: null}]);
expect(stats['obj'].totalCount).to.equal(1);
expect(stats['obj'].uniqueCount).to.equal(1);
expect(stats['obj'].numberCount).to.equal(0);
expect(stats['obj'].stringCount).to.equal(0);
expect(stats['obj'].otherCount).to.equal(1);
expect(stats['obj'].stringMinLength).to.equal(null);
expect(stats['obj'].stringMaxLength).to.equal(null);
expect(stats['obj'].stringMeanLength).to.equal(null);
expect(stats['array'].totalCount).to.equal(1);
expect(stats['array'].uniqueCount).to.equal(1);
expect(stats['array'].numberCount).to.equal(0);
expect(stats['array'].stringCount).to.equal(0);
expect(stats['array'].otherCount).to.equal(1);
expect(stats['array'].stringMinLength).to.equal(null);
expect(stats['array'].stringMaxLength).to.equal(null);
expect(stats['array'].stringMeanLength).to.equal(null);
expect(stats['missing'].totalCount).to.equal(1);
expect(stats['missing'].uniqueCount).to.equal(1);
expect(stats['missing'].numberCount).to.equal(0);
expect(stats['missing'].stringCount).to.equal(0);
expect(stats['missing'].otherCount).to.equal(1);
expect(stats['missing'].stringMinLength).to.equal(null);
expect(stats['missing'].stringMaxLength).to.equal(null);
expect(stats['missing'].stringMeanLength).to.equal(null);
});
it('should describe objects with mixed values', () => {
const stats = getStats([{mixed: 200}, {mixed: 'apple'}, {mixed: null}]);
expect(stats['mixed'].totalCount).to.equal(3);
expect(stats['mixed'].uniqueCount).to.equal(3);
expect(stats['mixed'].numberCount).to.equal(1);
expect(stats['mixed'].stringCount).to.equal(1);
expect(stats['mixed'].otherCount).to.equal(1);
expect(stats['mixed'].numberMin).to.equal(200);
expect(stats['mixed'].numberMax).to.equal(200);
expect(stats['mixed'].stringMinLength).to.equal(5);
expect(stats['mixed'].stringMaxLength).to.equal(5);
expect(stats['mixed'].stringMeanLength).to.equal(5);
});
}); | the_stack |
import * as React from "react";
import { isMouseEnabled } from "./mouse-enabled";
/**
* The responder takes its inspiration from react-native's
* pan-responder. Learn more about react-native's
* system here:
*
* https://facebook.github.io/react-native/docs/gesture-responder-system.html
*
* Basic usage:
*
* const bind = useGestureResponder({
* onStartShouldSet: () => true,
* onGrant: () => highlight(),
* onMove: () => updatePosition(),
* onRelease: () => unhighlight(),
* onTerminate: () => unhighlight()
* })
*
* The main benefit this provides is the ability to reconcile
* multiple gestures, and give priority to one.
*
* You can use a combination of useStartShouldSet, useStartShouldSetCapture,
* onMoveShouldSetCapture, and onMoveShouldSet to dictate
* which gets priority.
*
* Typically you'd want to avoid capture since it's generally
* preferable to have child elements gain touch access.
*/
export type ResponderEvent = React.TouchEvent | React.MouseEvent | Event;
export type CallbackQueryType = (
state: StateType,
e: ResponderEvent
) => boolean;
export type CallbackType = (state: StateType, e: ResponderEvent) => void;
export interface Callbacks {
onStartShouldSetCapture?: CallbackQueryType;
onStartShouldSet?: CallbackQueryType;
onMoveShouldSetCapture?: CallbackQueryType;
onMoveShouldSet?: CallbackQueryType;
onGrant?: CallbackType;
onMove?: CallbackType;
onRelease?: CallbackType;
onTerminate?: (state: StateType, e?: ResponderEvent) => void;
onTerminationRequest?: (state: StateType, e?: ResponderEvent) => boolean;
}
const initialState: StateType = {
time: Date.now(),
xy: [0, 0],
delta: [0, 0],
initial: [0, 0],
previous: [0, 0],
direction: [0, 0],
initialDirection: [0, 0],
local: [0, 0],
lastLocal: [0, 0],
velocity: 0,
distance: 0
};
export interface StateType {
time: number;
xy: [number, number];
delta: [number, number];
initial: [number, number];
previous: [number, number];
direction: [number, number];
initialDirection: [number, number];
local: [number, number];
lastLocal: [number, number];
velocity: number;
distance: number;
}
interface Config {
uid?: string;
enableMouse?: boolean;
}
const defaultConfig: Config = {
enableMouse: true
};
export interface GrantedTouch {
id: string | number;
onTerminationRequest: (e?: ResponderEvent) => void;
onTerminate: (e?: ResponderEvent) => void;
}
let grantedTouch: GrantedTouch | null = null;
export function useGestureResponder(
options: Callbacks = {},
config: Config = {}
) {
const state = React.useRef(initialState);
const { uid, enableMouse } = {
...defaultConfig,
...config
};
const id = React.useRef(uid || Math.random());
const pressed = React.useRef(false);
// update our callbacks when they change
const callbackRefs = React.useRef(options);
React.useEffect(() => {
callbackRefs.current = options;
}, [options]);
/**
* Attempt to claim the active touch
*/
function claimTouch(e: ResponderEvent) {
if (grantedTouch && grantedTouch.onTerminationRequest(e)) {
grantedTouch.onTerminate(e);
grantedTouch = null;
}
attemptGrant(e);
}
/**
* Attempt to claim the active touch
* @param e
*/
function attemptGrant(e: ResponderEvent) {
// if a touch is already active we won't register
if (grantedTouch) {
return;
}
grantedTouch = {
id: id.current,
onTerminate,
onTerminationRequest
};
onGrant(e);
}
function bindGlobalMouseEvents() {
window.addEventListener("mousemove", handleMoveMouse, false);
window.addEventListener("mousemove", handleMoveMouseCapture, true);
window.addEventListener("mouseup", handleEndMouse);
}
function unbindGlobalMouseEvents() {
window.removeEventListener("mousemove", handleMoveMouse, false);
window.removeEventListener("mousemove", handleMoveMouseCapture, true);
window.removeEventListener("mouseup", handleEndMouse);
}
function handleStartCapture(e: ResponderEvent) {
updateStartState(e);
pressed.current = true;
const granted = onStartShouldSetCapture(e);
if (granted) {
attemptGrant(e);
}
}
function handleStart(e: ResponderEvent) {
updateStartState(e);
pressed.current = true;
bindGlobalMouseEvents();
const granted = onStartShouldSet(e);
if (granted) {
attemptGrant(e);
}
}
function isGrantedTouch() {
return grantedTouch && grantedTouch.id === id.current;
}
/**
* Handle touchend / mouseup events
* @param e
*/
function handleEnd(e: ResponderEvent) {
pressed.current = false;
unbindGlobalMouseEvents();
if (!isGrantedTouch()) {
return;
}
// remove touch
grantedTouch = null;
onRelease(e);
}
/**
* Handle touchmove / mousemove capture events
* @param e
*/
function handleMoveCapture(e: ResponderEvent) {
updateMoveState(e);
if (isGrantedTouch()) {
return;
}
if (onMoveShouldSetCapture(e)) {
claimTouch(e);
}
}
/**
* Handle touchmove / mousemove events
* @param e
*/
function handleMove(e: ResponderEvent) {
if (isGrantedTouch()) {
onMove(e);
return;
}
if (onMoveShouldSet(e)) {
claimTouch(e);
}
}
/**
* When our gesture starts, should we become the responder?
*/
function onStartShouldSet(e: ResponderEvent) {
return callbackRefs.current.onStartShouldSet
? callbackRefs.current.onStartShouldSet(state.current, e)
: false;
}
/**
* Same as onStartShouldSet, except using capture.
*/
function onStartShouldSetCapture(e: ResponderEvent) {
return callbackRefs.current.onStartShouldSetCapture
? callbackRefs.current.onStartShouldSetCapture(state.current, e)
: false;
}
/**
* When our gesture moves, should we become the responder?
*/
function onMoveShouldSet(e: ResponderEvent) {
return callbackRefs.current.onMoveShouldSet
? callbackRefs.current.onMoveShouldSet(state.current, e)
: false;
}
/**
* Same as onMoveShouldSet, but using capture instead
* of bubbling.
*/
function onMoveShouldSetCapture(e: ResponderEvent) {
return callbackRefs.current.onMoveShouldSetCapture
? callbackRefs.current.onMoveShouldSetCapture(state.current, e)
: false;
}
/**
* The view is responding to gestures. Typically corresponds
* with mousedown or touchstart.
* @param e
*/
function onGrant(e: any) {
if (callbackRefs.current.onGrant) {
callbackRefs.current.onGrant(state.current, e);
}
}
/**
* Update our kinematics for start events
* @param e
*/
function updateStartState(e: any) {
const { pageX, pageY } = e.touches && e.touches[0] ? e.touches[0] : e;
const s = state.current;
state.current = {
...initialState,
lastLocal: s.lastLocal || initialState.lastLocal,
xy: [pageX, pageY],
initial: [pageX, pageY],
previous: [pageX, pageY],
time: Date.now()
};
}
/**
* Update our kinematics when moving
* @param e
*/
function updateMoveState(e: any) {
const { pageX, pageY } = e.touches && e.touches[0] ? e.touches[0] : e;
const s = state.current;
const time = Date.now();
const x_dist = pageX - s.xy[0];
const y_dist = pageY - s.xy[1];
const delta_x = pageX - s.initial[0];
const delta_y = pageY - s.initial[1];
const distance = Math.sqrt(delta_x * delta_x + delta_y * delta_y);
const len = Math.sqrt(x_dist * x_dist + y_dist * y_dist);
const scaler = 1 / (len || 1);
const velocity = len / (time - s.time);
const initialDirection =
s.initialDirection[0] !== 0 || s.initialDirection[1] !== 0
? s.initialDirection
: ([delta_x * scaler, delta_y * scaler] as [number, number]);
state.current = {
...state.current,
time,
xy: [pageX, pageY],
initialDirection,
delta: [delta_x, delta_y],
local: [
s.lastLocal[0] + pageX - s.initial[0],
s.lastLocal[1] + pageY - s.initial[1]
],
velocity: time - s.time === 0 ? s.velocity : velocity,
distance,
direction: [x_dist * scaler, y_dist * scaler],
previous: s.xy
};
}
/**
* The user is moving their touch / mouse.
* @param e
*/
function onMove(e: any) {
if (pressed.current && callbackRefs.current.onMove) {
callbackRefs.current.onMove(state.current, e);
}
}
/**
* The responder has been released. Typically mouse-up or
* touchend events.
* @param e
*/
function onRelease(e: ResponderEvent) {
const s = state.current;
state.current = {
...state.current,
lastLocal: s.local
};
if (callbackRefs.current.onRelease) {
callbackRefs.current.onRelease(state.current, e);
}
grantedTouch = null;
}
/**
* Check with the current responder to see if it can
* be terminated. This is currently only triggered when returns true
* from onMoveShouldSet. I can't really envision much of a
* use-case for doing this with a standard onStartShouldSet.
*
* By default, returns true.
*/
function onTerminationRequest(e?: ResponderEvent) {
return callbackRefs.current.onTerminationRequest
? callbackRefs.current.onTerminationRequest(state.current, e)
: true;
}
/**
* The responder has been taken by another view
*/
function onTerminate(e?: ResponderEvent) {
const s = state.current;
state.current = {
...state.current,
lastLocal: s.local
};
if (callbackRefs.current.onTerminate) {
callbackRefs.current.onTerminate(state.current, e);
}
}
/**
* Use window mousemove events instead of binding to the
* element itself to better emulate how touchmove works.
*/
function handleMoveMouse(e: Event) {
if (isMouseEnabled()) {
handleMove(e);
}
}
function handleMoveMouseCapture(e: Event) {
if (isMouseEnabled()) {
handleMoveCapture(e);
}
}
function handleEndMouse(e: Event) {
if (isMouseEnabled()) {
handleEnd(e);
}
}
React.useEffect(() => unbindGlobalMouseEvents, []);
/**
* Imperatively terminate the current responder
*/
function terminateCurrentResponder() {
if (grantedTouch) {
grantedTouch.onTerminate();
grantedTouch = null;
}
}
/**
* A getter for returning the current
* responder, if it exists
*/
function getCurrentResponder() {
return grantedTouch;
}
/**
* Required touch / mouse events
*/
const touchEvents = {
onTouchStart: handleStart,
onTouchEnd: handleEnd,
onTouchMove: handleMove,
onTouchStartCapture: handleStartCapture,
onTouchMoveCapture: handleMoveCapture
};
const mouseEvents = enableMouse
? {
onMouseDown: (e: React.MouseEvent) => {
if (isMouseEnabled()) {
handleStart(e);
}
},
onMouseDownCapture: (e: React.MouseEvent) => {
if (isMouseEnabled()) {
handleStartCapture(e);
}
}
}
: {};
return {
bind: {
...touchEvents,
...mouseEvents
},
terminateCurrentResponder,
getCurrentResponder
};
} | the_stack |
/// <reference path="../metricsPlugin.ts"/>
/// <reference path="../services/alertsManager.ts"/>
/// <reference path="../services/errorsManager.ts"/>
module HawkularMetrics {
export interface IServerLabel {
key: string;
value: string;
}
export class ServerLabel implements IServerLabel {
public key: string;
public value: string;
public type: string;
constructor(key, value, type?) {
this.key = key;
this.value = value;
this.type = type || 'userDefined';
}
}
export class AlertChartDataPoint implements IChartDataPoint {
public start: any;
public date: Date;
public min: any;
public max: any;
public percentiles: IPercentile[];
public median: any;
public timestamp: number;
public value: any;
public avg: any;
public empty: boolean;
constructor(value, timestamp) {
this.start = timestamp;
this.timestamp = timestamp;
this.min = value;
this.max = value;
this.percentiles = []; // FIXME: this should be revisited
this.median = value;
this.date = new Date(timestamp);
this.value = value;
this.avg = value;
this.empty = false;
}
}
export class AppServerOverviewDetailsController implements IRefreshable {
private static ALL_STATUSES = 'OPEN,ACKNOWLEDGED,RESOLVED';
private static ALERTS_PER_PAGE = 20;
private autoRefreshPromise: ng.IPromise<number>;
public startTimeStamp: HawkularMetrics.TimestampInMillis;
public endTimeStamp: HawkularMetrics.TimestampInMillis;
public alertList: any[] = [];
public alertInfo: any = {};
public datasourceInfo: any;
public serverInfo: any = {};
public overviewInfo: any;
public alertRound: number;
private feedId: FeedId;
private resourceId: ResourceId;
constructor(private $scope,
private $rootScope: IHawkularRootScope,
private $routeParams: any,
private $interval: ng.IIntervalService,
private HawkularAlertRouterManager: IHawkularAlertRouterManager,
private HawkularAlertsManager: IHawkularAlertsManager,
private HawkularInventory: any,
private HawkularMetric: any,
private $q: ng.IQService,
private MetricsService: IMetricsService) {
this.feedId = this.$routeParams.feedId;
this.resourceId = this.$routeParams.resourceId + '~~';
let selectedTime = $routeParams.timeOffset || 3600000;
this.endTimeStamp = $routeParams.hasOwnProperty('endTime') ? parseInt($routeParams.endTime, 10) : +moment();
this.alertRound = selectedTime / AppServerOverviewDetailsController.ALERTS_PER_PAGE;
this.startTimeStamp = +moment(this.endTimeStamp).subtract(selectedTime, 'milliseconds');
$scope.vm = this;
this.HawkularAlertRouterManager.registerForAlerts(
this.$routeParams.feedId + '/' + this.$routeParams.resourceId,
'overview',
_.bind(this.filterAlerts, this)
);
if (this.$rootScope.currentPersona) {
this.refresh();
} else {
$rootScope.$watch('currentPersona',
(currentPersona) => currentPersona && this.refresh());
}
this.autoRefresh(20);
}
public refresh(): void {
this.alertList = [];
this.getAlerts();
this.getOverviewInfo();
this.getServerInfo();
this.getDatasourceInfo();
this.alertInfo.graphData = [];
this.alertInfo.allAlerts = [];
this.alertInfo.alertCount = 0;
this.getAlertsInfo(this.feedId, this.$routeParams.resourceId);
this.$rootScope.lastUpdateTimestamp = new Date();
}
private getAlerts(res?: IResource): void {
let resourceId = (res) ? res.id : this.$routeParams.resourceId;
this.HawkularAlertRouterManager.getAlertsForResourceId(
this.$routeParams.feedId + '/' + resourceId,
this.startTimeStamp,
this.endTimeStamp
);
}
public filterAlerts(alertData: IHawkularAlertQueryResult) {
let deploymentAlerts = alertData.alertList;
angular.forEach(deploymentAlerts, (item) => {
item['alertType'] = item.context.alertType;
});
this.alertList = this.alertList.concat(deploymentAlerts);
}
private initGraphAlertData(): {} {
let timeStep = (this.endTimeStamp - this.startTimeStamp) / AppServerOverviewDetailsController.ALERTS_PER_PAGE;
let filledArray = {};
for (let step = 0; step < AppServerOverviewDetailsController.ALERTS_PER_PAGE; step++) {
let currentStep = Math.round((this.startTimeStamp + (timeStep * step)) / this.alertRound);
filledArray[currentStep] = {};
filledArray[currentStep].length = 'NaN';
}
return filledArray;
}
private getOverviewInfo() {
let promises = [];
let resourceData: any = {};
this.HawkularInventory.ResourceOfTypeUnderFeed.query({
feedId: this.$routeParams.feedId,
resourceTypeId: 'Deployment'
}, (aResourceList: IResource[], getResponseHeaders) => {
_.forEach(aResourceList, (res: IResource) => {
res.feedId = this.$routeParams.feedId;
promises.push(this.HawkularMetric.AvailabilityMetricData(this.$rootScope.currentPersona.id).query({
tenantId: this.$rootScope.currentPersona.id,
availabilityId: MetricsService.getMetricId('A', res.feedId, res.id,
'Deployment Status~Deployment Status'),
distinct: true
}, (availResource: IAvailResource[]) => {
let latestData = _.first(availResource);
if (latestData) {
res.state = latestData.value;
res.updateTimestamp = latestData.timestamp;
}
}).$promise);
});
this.$q.all(promises).then(() => {
resourceData.deployments = aResourceList;
this.overviewInfo = resourceData;
});
});
//Web session data
promises.push(this.getActiveWebSession().then(
(resource) => {
if (resource.length) {
resourceData['activeWebSessions'] = [];
_.forEach(resource, (item) => {
item['value'] = item['avg'];
});
let latestData: any = _.last(resource);
resourceData['activeWebSessions']['graph'] =
MetricsService.formatBucketedChartOutput(resource, AppServerJvmDetailsController.BYTES2MB);
if (latestData.avg !== 'NaN') {
resourceData['activeWebSessions']['last'] = +latestData.avg.toFixed(2);
}
}
})
);
//JVM data
promises.push(this.getJvmHeapUsage().then(
(resource) => {
if (resource.length) {
resourceData['heapUsage'] = [];
_.forEach(resource, (item) => {
item['value'] = item['avg'];
});
let latestData = _.last(resource);
resourceData['heapUsage']['graph'] =
MetricsService.formatBucketedChartOutput(resource, AppServerJvmDetailsController.BYTES2MB);
resourceData['heapUsage']['last'] = latestData['avg'];
}
})
);
}
private getActiveWebSession() {
return this.MetricsService.retrieveGaugeMetrics(
this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId,
'WildFly Aggregated Web Metrics~Aggregated Active Web Sessions'),
this.startTimeStamp,
this.endTimeStamp,
60
);
}
private getJvmHeapUsage() {
return this.MetricsService.retrieveGaugeMetrics(
this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.resourceId, 'WildFly Memory Metrics~Heap Used'),
this.startTimeStamp,
this.endTimeStamp,
60
);
}
private getAlertsInfo(feedId, resourceId) {
this.HawkularAlertsManager.queryAlerts({
statuses: AppServerOverviewDetailsController.ALL_STATUSES,
tags: 'resourceId|' + feedId + '/' + resourceId,
startTime: this.startTimeStamp,
endTime: this.endTimeStamp
}).then((alertData: IHawkularAlertQueryResult) => {
this.alertInfo.allAlerts = this.alertInfo.allAlerts.concat(alertData.alertList);
let alertInfo = [];
//Let's group alerts by time, number of ticks is defined in this.alertRound
let sortedData = _.groupBy(this.alertInfo.allAlerts, (item) => {
if (item.hasOwnProperty('ctime')) {
return Math.round(item['ctime'] / this.alertRound);
}
}, this);
let graphData = _.merge(this.initGraphAlertData(), sortedData);
//Parse all alerts into points for graph
_.forEach(graphData, (item, key) => {
if (item.hasOwnProperty('length')) {
//TODO: when proper graph used change this
let value = (!_.isNumber(item['length'])) ? 0 : item['length'];
alertInfo.push(new AlertChartDataPoint(value,
parseInt(key.toString(), 10) * this.alertRound
));
}
});
this.alertInfo.alertCount += alertData.alertList.length;
this.alertInfo.graphData = MetricsService.formatBucketedChartOutput(alertInfo);
});
}
private getDatasourceInfo() {
let xaDSsPromise = this.HawkularInventory.ResourceOfTypeUnderFeed.query({
feedId: this.feedId,
resourceTypeId: 'XA Datasource'
}).$promise;
let nonXaDSsPromise = this.HawkularInventory.ResourceOfTypeUnderFeed.query({
feedId: this.feedId,
resourceTypeId: 'Datasource'
}).$promise;
this.$q.all([xaDSsPromise, nonXaDSsPromise]).then((resourceLists) => {
this.getDSMetrics(resourceLists, this.$rootScope.currentPersona.id);
});
}
private getDSMetrics(resourceLists, tenantId) {
let tmpResourceList = [];
let promises = [];
let self_ = this;
angular.forEach(resourceLists, (aResourceList) => {
angular.forEach(aResourceList, (res: IResource) => {
res.feedId = this.feedId;
if (res.id.indexOf(this.$routeParams.resourceId + '~/') === 0) {
this.getAlertsInfo(res.feedId, res.id);
this.HawkularAlertRouterManager.registerForAlerts(
res.feedId + '/' + res.id,
'overview',
_.bind(self_.filterAlerts, this)
);
this.getAlerts(res);
tmpResourceList.push(res);
promises.push(this.HawkularMetric.GaugeMetricData(tenantId).queryMetrics({
gaugeId: MetricsService.getMetricId('M', this.feedId, res.id, 'Datasource Pool Metrics~Available Count'),
distinct: true
}, (data: number[]) => {
res.availableCount = data[0];
}).$promise);
promises.push(this.HawkularMetric.GaugeMetricData(tenantId).queryMetrics({
gaugeId: MetricsService.getMetricId('M', this.feedId, res.id, 'Datasource Pool Metrics~In Use Count'),
distinct: true
}, (data: number[]) => {
res.inUseCount = data[0];
}).$promise);
}
});
});
this.$q.all(promises).then(() => {
this.datasourceInfo = tmpResourceList;
});
}
private getServerInfo() {
let promises = [];
let tenantId = this.$rootScope.currentPersona.id;
promises.push(this.HawkularMetric.AvailabilityMetricData(tenantId).query({
availabilityId: MetricsService.getMetricId('A', this.feedId, this.resourceId, 'Server Availability~App Server'),
distinct: true
}, (resource) => {
let latestData = _.first(resource);
if (latestData) {
this.serverInfo['state'] = latestData['value'];
this.serverInfo['updateTimestamp'] = latestData['timestamp'];
}
}).$promise);
promises.push(this.HawkularInventory.ResourceUnderFeed.getData({
feedId: this.feedId,
resourcePath: this.resourceId
}, (resource) => {
if (resource['value']) {
this.serverInfo['configuration'] = resource['value'];
}
}).$promise);
promises.push(this.HawkularInventory.ResourceUnderFeed.get({
feedId: this.feedId,
resourcePath: this.resourceId
}, (resource: IResourcePath) => {
if (resource['type']) {
this.serverInfo['type'] = resource['type'];
}
if (resource['properties']) {
this.serverInfo['properties'] = resource['properties'];
}
}).$promise);
}
private autoRefresh(intervalInSeconds: number): void {
this.autoRefreshPromise = this.$interval(() => {
this.refresh();
}, intervalInSeconds * 1000);
this.$scope.$on('$destroy', () => {
this.$interval.cancel(this.autoRefreshPromise);
});
}
}
_module.controller('AppServerOverviewDetailsController', AppServerOverviewDetailsController);
} | the_stack |
import {
HydratedProviders,
ERC20Abi,
ChainInfo,
TransactionReason,
IVectorChainReader,
jsonifyError,
} from "@connext/vector-types";
import {
hydrateProviders,
getChainInfo,
getAssetName,
getMainnetEquivalent,
getExchangeRateInEth,
calculateExchangeWad,
} from "@connext/vector-utils";
import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { AddressZero } from "@ethersproject/constants";
import { Contract } from "@ethersproject/contracts";
import { formatEther, formatUnits } from "@ethersproject/units";
import { Wallet } from "@ethersproject/wallet";
import { getAddress } from "ethers/lib/utils";
import { BaseLogger } from "pino";
import { Counter, Gauge } from "prom-client";
import { getConfig } from "./config";
const config = getConfig();
//////////////////////////
///// Router Metrics /////
/////////////////////////
//////////////////////////
///// Helpers/Utils
export const wallet = Wallet.fromMnemonic(config.mnemonic);
export const signerAddress = wallet.address;
export const hydrated: HydratedProviders = hydrateProviders(config.chainProviders);
export const rebalancedTokens: {
[chainId: string]: {
[assetId: string]: {
contract: Contract;
decimals?: number;
};
};
} = {};
Object.entries(hydrated).forEach(async ([chainId, provider]) => {
rebalancedTokens[chainId] = {};
const assets = config.rebalanceProfiles
.filter((prof) => prof.chainId.toString() === chainId && prof.assetId !== AddressZero)
.map((p) => getAddress(p.assetId));
assets.forEach((asset) => {
rebalancedTokens[chainId][asset] = {
contract: new Contract(asset, ERC20Abi, provider),
decimals: undefined,
};
});
});
export const getDecimals = async (chainId: string, _assetId: string): Promise<number> => {
const assetId = getAddress(_assetId);
if (assetId === AddressZero) {
return 18;
}
const { decimals: _decimals, contract: _contract } = rebalancedTokens[chainId][assetId] ?? {};
if (_decimals) {
return _decimals;
}
if (!_contract && !hydrated[parseInt(chainId)]) {
// no provider for that chain, cannot retrieve decimals,
// use default of 18
return 18;
}
const contract = _contract ?? new Contract(assetId, ERC20Abi, hydrated[parseInt(chainId)]);
let decimals = 18;
try {
decimals = await contract.decimals();
} catch (e) {
// default to 18
}
rebalancedTokens[chainId][assetId] = { decimals, contract };
return decimals;
};
export const parseBalanceToNumber = async (
toFormat: BigNumberish,
chainId: string,
assetId: string,
): Promise<number> => {
if (assetId === AddressZero) {
return parseFloat(formatEther(toFormat));
}
const decimals = await getDecimals(chainId, assetId);
return parseFloat(formatUnits(toFormat, decimals));
};
export const incrementGasCosts = async (
gasUsed: string,
chainId: number,
reason: TransactionReason,
ethReader: IVectorChainReader,
logger: BaseLogger,
): Promise<void> => {
// Increment the gas cost without any normalizing
gasConsumed.inc({ chainId, reason }, await parseBalanceToNumber(gasUsed, chainId.toString(), AddressZero));
// Normalize the gas amounts to mainnet eth prices
const mainnetEquivalent = getMainnetEquivalent(chainId, AddressZero);
if (mainnetEquivalent.isError) {
logger.warn(
{ error: mainnetEquivalent.getError()!.message, chainId, assetId: AddressZero },
"No mainnet equivalent, cannot normalize",
);
return;
}
// Get exchange rate (token : eth)
const rate = await getExchangeRateInEth(mainnetEquivalent.getValue(), logger);
if (rate.isError) {
logger.warn({ error: rate.getError()?.message }, "Failed to get exchange rate");
return;
}
// Normalize to eth cost
const gasPrice = await ethReader.getGasPrice(chainId);
if (gasPrice.isError) {
logger.warn({ ...jsonifyError(gasPrice.getError()!), chainId }, "Failed to get gasPrice");
return;
}
const ethFee = calculateExchangeWad(
gasPrice.getValue().mul(gasUsed),
await getDecimals("1", mainnetEquivalent.getValue()),
rate.getValue().toString(),
18,
);
// Increment fees in eth
mainnetGasCost.inc({ chainId, reason }, await parseBalanceToNumber(ethFee, "1", AddressZero));
logger.debug(
{
gasUsed,
chainId,
reason,
mainnetEquivalent: mainnetEquivalent.getValue(),
gasPrice: gasPrice.getValue().toString(),
ethFee: ethFee.toString(),
},
"Incremented gas fees",
);
};
export const incrementFees = async (
feeAmount: string,
feeAssetId: string,
feeChainId: number,
logger: BaseLogger,
): Promise<void> => {
// First increment fees in native asset
feesCollected.inc(
{
chainId: feeChainId,
assetId: feeAssetId,
},
await parseBalanceToNumber(feeAmount, feeChainId.toString(), feeAssetId),
);
// Get the mainnet equivalent
const mainnetEquivalent = getMainnetEquivalent(feeChainId, feeAssetId);
if (mainnetEquivalent.isError) {
logger.warn(
{ error: mainnetEquivalent.getError()!.message, assetId: feeAssetId, chainId: feeChainId },
"No mainnet equivalent, cannot normalize",
);
return;
}
// Get exchange rate (token : eth)
const rate = await getExchangeRateInEth(mainnetEquivalent.getValue(), logger);
if (rate.isError) {
logger.warn({ error: rate.getError()?.message }, "Failed to get exchange rate");
return;
}
// Get equivalent eth amount
const ethFee = calculateExchangeWad(
BigNumber.from(feeAmount),
await getDecimals("1", mainnetEquivalent.getValue()),
rate.getValue().toString(),
18,
);
mainnetFeesCollectedInEth.inc(
{ chainId: feeChainId, assetId: feeAssetId },
await parseBalanceToNumber(ethFee, "1", AddressZero),
);
logger.debug(
{
feeAmount,
chainId: feeChainId,
assetId: feeAssetId,
mainnetEquivalent: mainnetEquivalent.getValue(),
ethFee: ethFee.toString(),
},
"Incremented collected fees",
);
};
//////////////////////////
///// Onchain liquidity
export const onchainLiquidity = new Gauge({
name: "router_onchain_liquidity",
help: "router_onchain_liquidity_help",
labelNames: ["chainName", "chainId", "assetName", "assetId"] as const,
async collect() {
await Promise.all(
Object.entries(hydrated).map(async ([chainId, provider]) => {
// base asset
const balance = await provider.getBalance(signerAddress);
const chainInfo: ChainInfo = await getChainInfo(Number(chainId));
const baseAssetName: string = getAssetName(Number(chainId), AddressZero);
this.set(
{ chainName: chainInfo?.name ?? chainId, chainId, assetName: baseAssetName, assetId: AddressZero },
parseFloat(formatEther(balance)),
);
// tokens
await Promise.all(
Object.entries(rebalancedTokens[chainId] ?? {}).map(async ([assetId, config]) => {
const balance = await config.contract.balanceOf(signerAddress);
const assetName: string = getAssetName(Number(chainId), assetId);
const toSet = await parseBalanceToNumber(balance, chainId, assetId);
this.set({ chainName: chainInfo?.name ?? chainId, chainId, assetName, assetId }, toSet);
}),
);
}),
);
},
});
//////////////////////////
///// Offchain liquidity
export const offchainLiquidity = new Gauge({
name: "router_offchain_liquidity",
help: "router_offchain_liquidity_help",
labelNames: ["assetId", "chainId"] as const,
});
//////////////////////////
///// Channel metrics
export const openChannels = new Counter({
name: "router_channels",
help: "router_channels_help",
labelNames: ["chainId"] as const,
});
//////////////////////////
///// Transfer metrics
// Track number of times a transfer attempt was made
export const attemptedTransfer = new Counter({
name: "router_transfer_attempt",
help: "router_transfer_attempt_help",
labelNames: ["assetId", "chainId"] as const,
});
// Track successful transfers
export const successfulTransfer = new Counter({
name: "router_transfer_successful",
help: "router_transfer_successful_help",
labelNames: ["assetId", "chainId"] as const,
});
// Track failing forwards
export const failedTransfer = new Counter({
name: "router_transfer_failed",
help: "router_transfer_failed_help",
labelNames: ["assetId", "chainId"] as const,
});
// Track volume from receiver side
export const forwardedTransferVolume = new Counter({
name: "router_transfer_volume",
help: "router_transfer_volume_help",
labelNames: ["assetId", "chainId"] as const,
});
// Track size of forwarded transfers
export const forwardedTransferSize = new Gauge({
name: "router_transfer_size",
help: "router_transfer_size_help",
labelNames: ["assetId", "chainId"] as const,
});
// Track fees charged on transfers
export const feesCollected = new Counter({
name: "router_fees",
help: "router_fees_help",
labelNames: ["assetId", "chainId"] as const,
});
// Track fees charged on transfers in eth where possible
// NOTE: it is only possible to calculate fees when one of
// the sides of the swap touches mainnet. Otherwise, we cannot
// get the token:eth exchange rate to normalize the fees.
export const mainnetFeesCollectedInEth = new Counter({
name: "router_mainnet_eth_fees",
help: "router_mainnet_eth_fees_help",
labelNames: ["assetId", "chainId"] as const,
});
//////////////////////////
///// Transaction metrics
// Track on chain transactions attempts
export const transactionAttempt = new Counter({
name: "router_transaction_attempt",
help: "router_transaction_attempt_help",
labelNames: ["reason", "chainId"] as const,
});
// Track successful on chain transactions
export const transactionSuccess = new Counter({
name: "router_transaction_success",
help: "router_transaction_success_help",
labelNames: ["reason", "chainId"] as const,
});
// Track failed on chain transactions
export const transactionFailed = new Counter({
name: "router_transaction_failed",
help: "router_transaction_failed_help",
labelNames: ["reason", "chainId"] as const,
});
// Track gas consumed
export const gasConsumed = new Counter({
name: "router_gas_consumed",
help: "router_gas_consumed_help",
labelNames: ["reason", "chainId"] as const,
});
// Track gas consumed on mainnet in eth
export const mainnetGasCost = new Counter({
name: "router_mainnet_gas_cost",
help: "router_mainnet_gas_cost_help",
labelNames: ["reason", "chainId"] as const,
}); | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* The resource model definition.
*/
export interface Resource extends BaseResource {
/**
* Resource ID
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location?: string;
/**
* Resource tags
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tags?: { [propertyName: string]: string };
}
/**
* Specifies the hardware settings for the HANA instance.
*/
export interface HardwareProfile {
/**
* Name of the hardware type (vendor and/or their product name). Possible values include:
* 'Cisco_UCS', 'HPE'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hardwareType?: HanaHardwareTypeNamesEnum;
/**
* Specifies the HANA instance SKU. Possible values include: 'S72m', 'S144m', 'S72', 'S144',
* 'S192', 'S192m', 'S192xm', 'S96', 'S112', 'S224', 'S224m', 'S224om', 'S224oo', 'S224oom',
* 'S224ooo', 'S384', 'S384m', 'S384xm', 'S384xxm', 'S576m', 'S576xm', 'S768', 'S768m', 'S768xm',
* 'S960m'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hanaInstanceSize?: HanaInstanceSizeNamesEnum;
}
/**
* Specifies the disk information fo the HANA instance
*/
export interface Disk {
/**
* The disk name.
*/
name?: string;
/**
* Specifies the size of an empty data disk in gigabytes.
*/
diskSizeGB?: number;
/**
* Specifies the logical unit number of the data disk. This value is used to identify data disks
* within the VM and therefore must be unique for each data disk attached to a VM.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lun?: number;
}
/**
* Specifies the storage settings for the HANA instance disks.
*/
export interface StorageProfile {
/**
* IP Address to connect to storage.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nfsIpAddress?: string;
/**
* Specifies information about the operating system disk used by the hana instance.
*/
osDisks?: Disk[];
}
/**
* Specifies the operating system settings for the HANA instance.
*/
export interface OSProfile {
/**
* Specifies the host OS name of the HANA instance.
*/
computerName?: string;
/**
* This property allows you to specify the type of the OS.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly osType?: string;
/**
* Specifies version of operating system.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly version?: string;
/**
* Specifies the SSH public key used to access the operating system.
*/
sshPublicKey?: string;
}
/**
* Specifies the IP address of the network interface.
*/
export interface IpAddress {
/**
* Specifies the IP address of the network interface.
*/
ipAddress?: string;
}
/**
* Specifies the network settings for the HANA instance disks.
*/
export interface NetworkProfile {
/**
* Specifies the network interfaces for the HANA instance.
*/
networkInterfaces?: IpAddress[];
/**
* Specifies the circuit id for connecting to express route.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly circuitId?: string;
}
/**
* HANA instance info on Azure (ARM properties and HANA properties)
*/
export interface HanaInstance extends Resource {
/**
* Specifies the hardware settings for the HANA instance.
*/
hardwareProfile?: HardwareProfile;
/**
* Specifies the storage settings for the HANA instance disks.
*/
storageProfile?: StorageProfile;
/**
* Specifies the operating system settings for the HANA instance.
*/
osProfile?: OSProfile;
/**
* Specifies the network settings for the HANA instance.
*/
networkProfile?: NetworkProfile;
/**
* Specifies the HANA instance unique ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hanaInstanceId?: string;
/**
* Resource power state. Possible values include: 'starting', 'started', 'stopping', 'stopped',
* 'restarting', 'unknown'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly powerState?: HanaInstancePowerStateEnum;
/**
* Resource proximity placement group
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly proximityPlacementGroup?: string;
/**
* Hardware revision of a HANA instance
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hwRevision?: string;
/**
* ARM ID of another HanaInstance that will share a network with this HanaInstance
*/
partnerNodeId?: string;
/**
* State of provisioning of the HanaInstance. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Failed', 'Succeeded', 'Deleting', 'Migrating'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: HanaProvisioningStatesEnum;
}
/**
* Detailed HANA operation information
*/
export interface Display {
/**
* The localized friendly form of the resource provider name. This form is also expected to
* include the publisher/company responsible. Use Title Casing. Begin with "Microsoft" for 1st
* party services.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: string;
/**
* The localized friendly form of the resource type related to this action/operation. This form
* should match the public documentation for the resource provider. Use Title Casing. For
* examples, refer to the “name” section.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resource?: string;
/**
* The localized friendly name for the operation as shown to the user. This name should be
* concise (to fit in drop downs), but clear (self-documenting). Use Title Casing and include the
* entity/resource to which it applies.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly operation?: string;
/**
* The localized friendly description for the operation as shown to the user. This description
* should be thorough, yet concise. It will be used in tool-tips and detailed views.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly description?: string;
/**
* The intended executor of the operation; governs the display of the operation in the RBAC UX
* and the audit logs UX. Default value is 'user,system'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly origin?: string;
}
/**
* HANA operation information
*/
export interface Operation {
/**
* The name of the operation being performed on this particular object. This name should match
* the action name that appears in RBAC / the event service.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Displayed HANA operation information
*/
display?: Display;
}
/**
* Describes the format of Error response.
*/
export interface ErrorResponse {
/**
* Error code
*/
code?: string;
/**
* Error message indicating why the operation failed.
*/
message?: string;
}
/**
* Tags field of the HANA instance.
*/
export interface Tags {
/**
* Tags field of the HANA instance.
*/
tags?: { [propertyName: string]: string };
}
/**
* Details needed to monitor a Hana Instance
*/
export interface MonitoringDetails {
/**
* ARM ID of an Azure Subnet with access to the HANA instance.
*/
hanaSubnet?: string;
/**
* Hostname of the HANA Instance blade.
*/
hanaHostname?: string;
/**
* Name of the database itself.
*/
hanaDbName?: string;
/**
* The port number of the tenant DB. Used to connect to the DB.
*/
hanaDbSqlPort?: number;
/**
* Username for the HANA database to login to for monitoring
*/
hanaDbUsername?: string;
/**
* Password for the HANA database to login for monitoring
*/
hanaDbPassword?: string;
}
/**
* SAP monitor info on Azure (ARM properties and SAP monitor properties)
*/
export interface SapMonitor extends Resource {
/**
* Specifies the SAP monitor unique ID.
*/
hanaSubnet?: string;
/**
* Hostname of the HANA instance.
*/
hanaHostname?: string;
/**
* Database name of the HANA instance.
*/
hanaDbName?: string;
/**
* Database port of the HANA instance.
*/
hanaDbSqlPort?: number;
/**
* Database username of the HANA instance.
*/
hanaDbUsername?: string;
/**
* Database password of the HANA instance.
*/
hanaDbPassword?: string;
/**
* KeyVault URL link to the password for the HANA database.
*/
hanaDbPasswordKeyVaultUrl?: string;
/**
* MSI ID passed by customer which has access to customer's KeyVault and to be assigned to the
* Collector VM.
*/
hanaDbCredentialsMsiId?: string;
/**
* Key Vault ID containing customer's HANA credentials.
*/
keyVaultId?: string;
/**
* State of provisioning of the HanaInstance. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Failed', 'Succeeded', 'Deleting', 'Migrating'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: HanaProvisioningStatesEnum;
/**
* The name of the resource group the SAP Monitor resources get deployed into.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly managedResourceGroupName?: string;
/**
* The ARM ID of the Log Analytics Workspace that is used for monitoring
*/
logAnalyticsWorkspaceArmId?: string;
/**
* The value indicating whether to send analytics to Microsoft
*/
enableCustomerAnalytics?: boolean;
/**
* The workspace ID of the log analytics workspace to be used for monitoring
*/
logAnalyticsWorkspaceId?: string;
/**
* The shared key of the log analytics workspace that is used for monitoring
*/
logAnalyticsWorkspaceSharedKey?: string;
}
/**
* An interface representing HanaManagementClientOptions.
*/
export interface HanaManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* List of HANA operations
* @extends Array<Operation>
*/
export interface OperationList extends Array<Operation> {
}
/**
* @interface
* The response from the List HANA Instances operation.
* @extends Array<HanaInstance>
*/
export interface HanaInstancesListResult extends Array<HanaInstance> {
/**
* The URL to get the next set of HANA instances.
*/
nextLink?: string;
}
/**
* @interface
* The response from the List SAP monitors operation.
* @extends Array<SapMonitor>
*/
export interface SapMonitorListResult extends Array<SapMonitor> {
/**
* The URL to get the next set of SAP monitors.
*/
nextLink?: string;
}
/**
* Defines values for HanaHardwareTypeNamesEnum.
* Possible values include: 'Cisco_UCS', 'HPE'
* @readonly
* @enum {string}
*/
export type HanaHardwareTypeNamesEnum = 'Cisco_UCS' | 'HPE';
/**
* Defines values for HanaInstanceSizeNamesEnum.
* Possible values include: 'S72m', 'S144m', 'S72', 'S144', 'S192', 'S192m', 'S192xm', 'S96',
* 'S112', 'S224', 'S224m', 'S224om', 'S224oo', 'S224oom', 'S224ooo', 'S384', 'S384m', 'S384xm',
* 'S384xxm', 'S576m', 'S576xm', 'S768', 'S768m', 'S768xm', 'S960m'
* @readonly
* @enum {string}
*/
export type HanaInstanceSizeNamesEnum = 'S72m' | 'S144m' | 'S72' | 'S144' | 'S192' | 'S192m' | 'S192xm' | 'S96' | 'S112' | 'S224' | 'S224m' | 'S224om' | 'S224oo' | 'S224oom' | 'S224ooo' | 'S384' | 'S384m' | 'S384xm' | 'S384xxm' | 'S576m' | 'S576xm' | 'S768' | 'S768m' | 'S768xm' | 'S960m';
/**
* Defines values for HanaInstancePowerStateEnum.
* Possible values include: 'starting', 'started', 'stopping', 'stopped', 'restarting', 'unknown'
* @readonly
* @enum {string}
*/
export type HanaInstancePowerStateEnum = 'starting' | 'started' | 'stopping' | 'stopped' | 'restarting' | 'unknown';
/**
* Defines values for HanaProvisioningStatesEnum.
* Possible values include: 'Accepted', 'Creating', 'Updating', 'Failed', 'Succeeded', 'Deleting',
* 'Migrating'
* @readonly
* @enum {string}
*/
export type HanaProvisioningStatesEnum = 'Accepted' | 'Creating' | 'Updating' | 'Failed' | 'Succeeded' | 'Deleting' | 'Migrating';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationList & {
/**
* 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: OperationList;
};
};
/**
* Contains response data for the list operation.
*/
export type HanaInstancesListResponse = HanaInstancesListResult & {
/**
* 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: HanaInstancesListResult;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type HanaInstancesListByResourceGroupResponse = HanaInstancesListResult & {
/**
* 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: HanaInstancesListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type HanaInstancesGetResponse = HanaInstance & {
/**
* 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: HanaInstance;
};
};
/**
* Contains response data for the create operation.
*/
export type HanaInstancesCreateResponse = HanaInstance & {
/**
* 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: HanaInstance;
};
};
/**
* Contains response data for the update operation.
*/
export type HanaInstancesUpdateResponse = HanaInstance & {
/**
* 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: HanaInstance;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type HanaInstancesBeginCreateResponse = HanaInstance & {
/**
* 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: HanaInstance;
};
};
/**
* Contains response data for the listNext operation.
*/
export type HanaInstancesListNextResponse = HanaInstancesListResult & {
/**
* 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: HanaInstancesListResult;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type HanaInstancesListByResourceGroupNextResponse = HanaInstancesListResult & {
/**
* 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: HanaInstancesListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type SapMonitorsListResponse = SapMonitorListResult & {
/**
* 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: SapMonitorListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type SapMonitorsGetResponse = SapMonitor & {
/**
* 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: SapMonitor;
};
};
/**
* Contains response data for the create operation.
*/
export type SapMonitorsCreateResponse = SapMonitor & {
/**
* 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: SapMonitor;
};
};
/**
* Contains response data for the update operation.
*/
export type SapMonitorsUpdateResponse = SapMonitor & {
/**
* 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: SapMonitor;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type SapMonitorsBeginCreateResponse = SapMonitor & {
/**
* 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: SapMonitor;
};
};
/**
* Contains response data for the listNext operation.
*/
export type SapMonitorsListNextResponse = SapMonitorListResult & {
/**
* 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: SapMonitorListResult;
};
}; | the_stack |
import * as d3 from 'd3';
import { ANIMATION_DURATION, DEFAULT_HEIGHT_DECREMENT, DEFAULT_LEVEL_HEIGHT, DEFAULT_NODE_HEIGHT, DEFAULT_NODE_WIDTH, MATCH_SCALE_REGEX, MATCH_TRANSLATE_REGEX } from './constant';
import { TreeDataset, Direction, TreeLinkStyle } from './tree-chart';
import { deepCopy, rotatePoint } from './util';
interface TreeConfig {
nodeWidth: number;
nodeHeight: number;
levelHeight: number;
}
interface TreeChartCoreParams {
treeConfig?: TreeConfig;
linkStyle?: TreeLinkStyle;
direction?: Direction;
collapseEnabled: boolean;
dataset: TreeDataset;
svgElement: SVGElement;
domElement: HTMLDivElement;
treeContainer: HTMLDivElement;
}
export default class TreeChartCore {
treeConfig: TreeConfig = {
nodeWidth: DEFAULT_NODE_WIDTH,
nodeHeight: DEFAULT_NODE_HEIGHT,
levelHeight: DEFAULT_LEVEL_HEIGHT,
};
linkStyle: TreeLinkStyle = TreeLinkStyle.CURVE;
direction: Direction = Direction.VERTICAL;
collapseEnabled: boolean = true
dataset: TreeDataset;
svgElement: SVGElement;
svgSelection: any;
domElement: HTMLDivElement;
treeContainer: HTMLDivElement;
nodeDataList: any[];
linkDataList: any[];
initTransformX: number;
initTransformY: number;
currentScale: number = 1;
constructor(params: TreeChartCoreParams) {
if (params.treeConfig) {
this.treeConfig = params.treeConfig;
}
this.collapseEnabled = params.collapseEnabled
this.svgElement = params.svgElement;
this.domElement = params.domElement;
this.treeContainer = params.treeContainer;
this.dataset = this.updatedInternalData(params.dataset);
if (params.direction) this.direction = params.direction;
}
init() {
this.draw();
this.enableDrag();
this.initTransform();
}
getNodeDataList() {
return this.nodeDataList;
}
getInitialTransformStyle(): Record<string, string> {
return {
transform: `scale(1) translate(${this.initTransformX}px, ${this.initTransformY}px)`,
transformOrigin: "center",
};
}
zoomIn() {
const originTransformStr = this.domElement.style.transform;
// 如果已有scale属性, 在原基础上修改
let targetScale = 1 * 1.2;
const scaleMatchResult = originTransformStr.match(MATCH_SCALE_REGEX);
if (scaleMatchResult && scaleMatchResult.length > 0) {
const originScale = parseFloat(scaleMatchResult[1]);
targetScale *= originScale;
}
this.setScale(targetScale);
}
zoomOut() {
const originTransformStr = this.domElement.style.transform;
// 如果已有scale属性, 在原基础上修改
let targetScale = 1 / 1.2;
const scaleMatchResult = originTransformStr.match(MATCH_SCALE_REGEX);
if (scaleMatchResult && scaleMatchResult.length > 0) {
const originScale = parseFloat(scaleMatchResult[1]);
targetScale = originScale / 1.2;
}
this.setScale(targetScale);
}
restoreScale() {
this.setScale(1);
}
setScale(scaleNum) {
if (typeof scaleNum !== "number") return;
let pos = this.getTranslate();
let translateString = `translate(${pos[0]}px, ${pos[1]}px)`;
this.svgElement.style.transform = `scale(${scaleNum}) ` + translateString;
this.domElement.style.transform =
`scale(${scaleNum}) ` + translateString;
this.currentScale = scaleNum;
}
getTranslate() {
let string = this.svgElement.style.transform;
let match = string.match(MATCH_TRANSLATE_REGEX);
if (match === null) {
return [null, null];
}
let x = parseInt(match[1]);
let y = parseInt(match[2]);
return [x, y];
}
isVertical() {
return this.direction === Direction.VERTICAL;
}
/**
* 根据link数据,生成svg path data
*/
private generateLinkPath(d) {
const self = this;
if (this.linkStyle === TreeLinkStyle.CURVE) {
return this.generateCurceLinkPath(self, d);
}
if (this.linkStyle === TreeLinkStyle.STRAIGHT) {
// the link path is: source -> secondPoint -> thirdPoint -> target
return this.generateStraightLinkPath(d);
}
}
private generateCurceLinkPath(self: this, d: any) {
const linkPath = this.isVertical()
? d3.linkVertical()
: d3.linkHorizontal();
linkPath
.x(function (d) {
return d.x;
})
.y(function (d) {
return d.y;
})
.source(function (d) {
const sourcePoint = {
x: d.source.x,
y: d.source.y,
};
return self.direction === Direction.VERTICAL
? sourcePoint
: rotatePoint(sourcePoint);
})
.target(function (d) {
const targetPoint = {
x: d.target.x,
y: d.target.y,
};
return self.direction === Direction.VERTICAL
? targetPoint
: rotatePoint(targetPoint);
});
return linkPath(d);
}
private generateStraightLinkPath(d: any) {
const linkPath = d3.path();
let sourcePoint = { x: d.source.x, y: d.source.y };
let targetPoint = { x: d.target.x, y: d.target.y };
if (!this.isVertical()) {
sourcePoint = rotatePoint(sourcePoint);
targetPoint = rotatePoint(targetPoint);
}
const xOffset = targetPoint.x - sourcePoint.x;
const yOffset = targetPoint.y - sourcePoint.y;
const secondPoint = this.isVertical()
? { x: sourcePoint.x, y: sourcePoint.y + yOffset / 2 }
: { x: sourcePoint.x + xOffset / 2, y: sourcePoint.y };
const thirdPoint = this.isVertical()
? { x: targetPoint.x, y: sourcePoint.y + yOffset / 2 }
: { x: sourcePoint.x + xOffset / 2, y: targetPoint.y };
linkPath.moveTo(sourcePoint.x, sourcePoint.y);
linkPath.lineTo(secondPoint.x, secondPoint.y);
linkPath.lineTo(thirdPoint.x, thirdPoint.y);
linkPath.lineTo(targetPoint.x, targetPoint.y);
return linkPath.toString();
}
updateDataList() {
let [nodeDataList, linkDataList] = this.buildTree()
nodeDataList.splice(0, 1);
linkDataList = linkDataList.filter(
(x) => x.source.data.name !== "__invisible_root"
);
this.linkDataList = linkDataList;
this.nodeDataList = nodeDataList;
}
private draw() {
this.updateDataList();
const identifier = this.dataset["identifier"];
const specialLinks = this.dataset["links"];
if (specialLinks && identifier) {
for (const link of specialLinks) {
let parent,
children = undefined;
if (identifier === "value") {
parent = this.nodeDataList.find((d) => {
return d[identifier] == link.parent;
});
children = this.nodeDataList.filter((d) => {
return d[identifier] == link.child;
});
} else {
parent = this.nodeDataList.find((d) => {
return d["data"][identifier] == link.parent;
});
children = this.nodeDataList.filter((d) => {
return d["data"][identifier] == link.child;
});
}
if (parent && children) {
for (const child of children) {
const new_link = {
source: parent,
target: child,
};
this.linkDataList.push(new_link);
}
}
}
}
this.svgSelection = d3.select(this.svgElement);
const self = this;
const links = this.svgSelection
.selectAll(".link")
.data(this.linkDataList, (d) => {
return `${d.source.data._key}-${d.target.data._key}`;
});
links
.enter()
.append("path")
.style("opacity", 0)
.transition()
.duration(ANIMATION_DURATION)
.ease(d3.easeCubicInOut)
.style("opacity", 1)
.attr("class", "link")
.attr("d", function (d) {
return self.generateLinkPath(d);
});
links
.transition()
.duration(ANIMATION_DURATION)
.ease(d3.easeCubicInOut)
.attr("d", function (d) {
return self.generateLinkPath(d);
});
links
.exit()
.transition()
.duration(ANIMATION_DURATION / 2)
.ease(d3.easeCubicInOut)
.style("opacity", 0)
.remove();
}
/**
* Returns updated dataset by deep copying every nodes from the externalData and adding unique '_key' attributes.
**/
private updatedInternalData(externalData) {
var data = { name: "__invisible_root", children: [] };
if (!externalData) return data;
if (Array.isArray(externalData)) {
for (var i = externalData.length - 1; i >= 0; i--) {
data.children.push(deepCopy(externalData[i]));
}
} else {
data.children.push(deepCopy(externalData));
}
return data;
}
private buildTree() {
const treeBuilder = d3
.tree()
.nodeSize([this.treeConfig.nodeWidth, this.treeConfig.levelHeight]);
const tree = treeBuilder(d3.hierarchy(this.dataset));
return [tree.descendants(), tree.links()];
}
private enableDrag() {
let startX = 0;
let startY = 0;
let isDrag = false;
// 保存鼠标点下时的位移
let mouseDownTransform = "";
this.treeContainer.onmousedown = (event) => {
mouseDownTransform = this.svgElement.style.transform;
startX = event.clientX;
startY = event.clientY;
isDrag = true;
};
this.treeContainer.onmousemove = (event) => {
if (!isDrag) return;
const originTransform = mouseDownTransform;
let originOffsetX = 0;
let originOffsetY = 0;
if (originTransform) {
const result = originTransform.match(MATCH_TRANSLATE_REGEX);
if (result !== null && result.length !== 0) {
const [offsetX, offsetY] = result.slice(1);
originOffsetX = parseInt(offsetX);
originOffsetY = parseInt(offsetY);
}
}
let newX =
Math.floor((event.clientX - startX) / this.currentScale) +
originOffsetX;
let newY =
Math.floor((event.clientY - startY) / this.currentScale) +
originOffsetY;
let transformStr = `translate(${newX}px, ${newY}px)`;
if (originTransform) {
transformStr = originTransform.replace(
MATCH_TRANSLATE_REGEX,
transformStr
);
}
this.svgElement.style.transform = transformStr;
this.domElement.style.transform = transformStr;
};
this.treeContainer.onmouseup = () => {
startX = 0;
startY = 0;
isDrag = false;
};
}
initTransform() {
const containerWidth = this.domElement.offsetWidth;
const containerHeight = this.domElement.offsetHeight;
if (this.isVertical()) {
this.initTransformX = Math.floor(containerWidth / 2);
this.initTransformY = Math.floor(
this.treeConfig.nodeHeight - DEFAULT_HEIGHT_DECREMENT
);
} else {
this.initTransformX = Math.floor(
this.treeConfig.nodeWidth - DEFAULT_HEIGHT_DECREMENT
);
this.initTransformY = Math.floor(containerHeight / 2);
}
}
onClickNode(index: number) {
if (this.collapseEnabled) {
const curNode = this.nodeDataList[index];
if (curNode.data.children) {
curNode.data._children = curNode.data.children;
curNode.data.children = null;
curNode.data._collapsed = true;
} else {
curNode.data.children = curNode.data._children;
curNode.data._children = null;
curNode.data._collapsed = false;
}
this.draw();
}
}
/**
* call this function to update dataset
* notice : you need to update the view rendered by `nodeDataList` too
* @param dataset the new dataset to show in chart
*/
updateDataset(dataset: TreeDataset) {
this.dataset = this.updatedInternalData(dataset);
this.draw();
}
/**
* release all dom reference
*/
destroy() {
this.svgElement = null;
this.domElement = null;
this.treeContainer = null;
}
} | the_stack |
import { Component, h, render } from "preact";
import {
StartJobResult,
PollJobResult,
JobState,
FieldValueCounts,
} from "../api/v1";
import { LogEvent } from "../models/Event";
import { Popover } from "../components/popover";
import { TopFieldValueInfo } from "../models/TopFieldValueInfo";
import { TimeSelection } from "../models/TimeSelection";
import { Pagination } from "../components/Pagination";
import { RecentSearch } from "../services/RecentSearches";
import {
startJob,
pollJob,
getResults,
abortJob,
getFieldValueCounts,
} from "../api/v1";
import { addRecentSearch, getRecentSearches } from "../services/RecentSearches";
import { Navbar } from "../components/Navbar";
import { SearchInput } from "../components/SearchInput";
import { FieldValueTable } from "../components/FieldValueTable";
import { EventTable } from "../components/EventTable";
import { FieldTable } from "../components/FieldTable";
import { createSearchQueryParams } from "../createSearchUrl";
import { validateIsoTimestamp } from "../validateIsoTimestamp";
const EVENTS_PER_PAGE = 25;
const TOP_FIELDS_COUNT = 15;
interface SearchProps {
startJob: (
searchString: string,
timeSelection: TimeSelection
) => Promise<StartJobResult>;
pollJob: (jobId: number) => Promise<PollJobResult>;
getResults: (
jobId: number,
skip: number,
take: number
) => Promise<LogEvent[]>;
abortJob: (jobId: number) => Promise<{}>;
getFieldValueCounts: (
jobId: number,
fieldName: string
) => Promise<FieldValueCounts>;
addRecentSearch: (search: RecentSearch) => Promise<void>;
getQueryParams: () => URLSearchParams;
setQueryParams: (params: URLSearchParams) => void;
}
export enum SearchState {
HAVENT_SEARCHED,
WAITING_FOR_SEARCH,
SEARCHED_ERROR,
SEARCHED_POLLING,
SEARCHED_POLLING_FINISHED,
}
interface SearchStateBase {
state: SearchState;
searchString: string;
selectedTime: TimeSelection;
}
export type SearchStateStruct =
| HaventSearched
| WaitingForSearch
| SearchedError
| SearchedPolling
| SearchedPollingFinished;
interface HaventSearched extends SearchStateBase {
state: SearchState.HAVENT_SEARCHED;
}
interface WaitingForSearch extends SearchStateBase {
state: SearchState.WAITING_FOR_SEARCH;
}
interface SearchedError extends SearchStateBase {
state: SearchState.SEARCHED_ERROR;
searchError: string;
}
interface SearchedPolling extends SearchStateBase {
state: SearchState.SEARCHED_POLLING;
jobId: number;
poller: number;
searchResult: LogEvent[];
numMatched: number;
currentPageIndex: number;
allFields: { [key: string]: number };
topFields: { [key: string]: number };
selectedField: SelectedField | null;
}
interface SearchedPollingFinished extends SearchStateBase {
state: SearchState.SEARCHED_POLLING_FINISHED;
jobId: number;
searchResult: LogEvent[];
numMatched: number;
currentPageIndex: number;
allFields: { [key: string]: number };
topFields: { [key: string]: number };
selectedField: SelectedField | null;
}
interface SelectedField {
name: string;
topValues: TopFieldValueInfo[];
}
export class SearchPageComponent extends Component<
SearchProps,
SearchStateStruct
> {
constructor(props: SearchProps) {
super(props);
this.state = {
state: SearchState.HAVENT_SEARCHED,
searchString: "",
selectedTime: {
relativeTime: "-15m",
},
};
}
componentDidMount() {
const queryParams = this.props.getQueryParams();
let doSearch = false;
let newState: Partial<SearchStateStruct> = {};
if (queryParams.has("query")) {
newState.searchString = decodeURIComponent(
queryParams.get("query") || ""
);
doSearch = true;
}
if (queryParams.has("relativeTime")) {
const relativeTime = queryParams.get("relativeTime");
if (relativeTime === "ALL") {
newState.selectedTime = {};
} else {
newState.selectedTime = {
relativeTime: relativeTime || undefined,
};
}
doSearch = true;
}
const hasStartTime = queryParams.has("startTime");
const hasEndTime = queryParams.has("endTime");
if (hasStartTime || hasEndTime) {
newState.selectedTime = {};
doSearch = true;
}
if (hasStartTime) {
const startTimeStr = queryParams.get("startTime") as string;
if (validateIsoTimestamp(startTimeStr)) {
newState.selectedTime!.startTime = startTimeStr;
}
}
if (hasEndTime) {
const endTimeStr = queryParams.get("endTime") as string;
if (validateIsoTimestamp(endTimeStr)) {
newState.selectedTime!.endTime = endTimeStr;
}
}
if (queryParams.has("jobId")) {
const jobIdString = queryParams.get("jobId") as string;
const jobId = parseInt(jobIdString, 10);
let currentPageIndex = 0;
if (queryParams.has("page")) {
const pageIndex = parseInt(queryParams.get("page") as string, 10);
if (!isNaN(pageIndex)) {
currentPageIndex = pageIndex;
}
}
if (!isNaN(jobId)) {
newState = {
...newState,
state: SearchState.SEARCHED_POLLING,
jobId: jobId,
poller: window.setTimeout(async () => this.poll(jobId), 0),
searchResult: [],
numMatched: 0,
currentPageIndex: currentPageIndex,
};
doSearch = false;
}
}
this.setState(newState, () => {
if (doSearch) {
this.onSearch();
}
});
}
render() {
return (
<div onClick={(evt) => this.onBodyClicked(evt)}>
<Navbar />
<main role="main" class="container-fluid">
<SearchInput
isButtonDisabled={
this.state.state === SearchState.WAITING_FOR_SEARCH
}
searchString={this.state.searchString}
setSearchString={(str) => this.setState({ searchString: str })}
selectedTime={this.state.selectedTime}
setSelectedTime={(ts) => this.setState({ selectedTime: ts })}
onSearch={() => this.onSearch()}
/>
<div class="result-container">
{this.state.state === SearchState.SEARCHED_ERROR && (
<div class="alert alert-danger">{this.state.searchError}</div>
)}
{(this.state.state === SearchState.WAITING_FOR_SEARCH ||
(this.state.state === SearchState.SEARCHED_POLLING &&
this.state.searchResult.length === 0)) && (
<div>Loading... There should be a spinner here!</div>
)}
{((this.state.state === SearchState.SEARCHED_POLLING &&
this.state.searchResult.length > 0) ||
this.state.state === SearchState.SEARCHED_POLLING_FINISHED) && (
<div>
{this.state.searchResult.length === 0 && (
<div class="alert alert-info">
No results found. Try a different search?
</div>
)}
{this.state.searchResult.length !== 0 && (
<div class="row">
<div class="col-xl-2">
<div class="card mb-3 mb-xl-0">
<div class="card-header">Fields</div>
<FieldTable
fields={this.state.topFields}
onFieldClicked={(str) => this.onFieldClicked(str)}
/>
{
<Popover
direction="right"
isOpen={!!this.state.selectedField}
heading={this.state.selectedField?.name || ""}
widthPx={300}
>
<FieldValueTable
values={this.state.selectedField?.topValues || []}
onFieldValueClicked={(str) =>
this.onFieldValueClicked(str)
}
/>
</Popover>
}
</div>
</div>
<div class="col-xl-10">
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
}}
>
<Pagination
currentPageIndex={this.state.currentPageIndex}
numberOfPages={Math.ceil(
this.state.numMatched / EVENTS_PER_PAGE
)}
onPageChanged={(n) => this.onPageChanged(n)}
></Pagination>
<div
style={{
display: "flex",
flexDirection: "row",
alignItems: "center",
}}
>
{this.state.state ===
SearchState.SEARCHED_POLLING && (
<button
type="button"
class="btn btn-link"
onClick={() => this.onCancel()}
>
Cancel
</button>
)}
<span>{this.state.numMatched} events matched</span>
</div>
</div>
<div class="card">
<EventTable events={this.state.searchResult} />
</div>
</div>
</div>
)}
</div>
)}
</div>
</main>
</div>
);
}
private onBodyClicked(evt: any) {
if (
(this.state.state === SearchState.SEARCHED_POLLING ||
this.state.state === SearchState.SEARCHED_POLLING_FINISHED) &&
this.state.selectedField
) {
if (!(evt.target as HTMLDivElement).matches(".popover *")) {
this.setState({
...this.state,
selectedField: null,
});
}
}
}
private async onFieldClicked(fieldName: string) {
if (
this.state.state !== SearchState.SEARCHED_POLLING &&
this.state.state !== SearchState.SEARCHED_POLLING_FINISHED
) {
// Really weird state. Maybe throw error?
return;
}
if (this.state.selectedField?.name === fieldName) {
this.setState({
...this.state,
selectedField: null,
});
} else {
const fieldValues = await this.props.getFieldValueCounts(
this.state.jobId,
fieldName
);
const keys = Object.keys(fieldValues);
const totalCount = keys.reduce((acc, k) => acc + fieldValues[k], 0);
const topValues = keys
.sort((a, b) => fieldValues[b] - fieldValues[a])
.slice(0, TOP_FIELDS_COUNT)
.map((k) => ({
value: k,
count: fieldValues[k],
percentage: fieldValues[k] / totalCount,
}));
console.log(topValues);
this.setState({
...this.state,
selectedField: {
name: fieldName,
topValues: topValues,
},
});
}
}
private onFieldValueClicked(value: string) {
if (
(this.state.state !== SearchState.SEARCHED_POLLING &&
this.state.state !== SearchState.SEARCHED_POLLING_FINISHED) ||
this.state.selectedField === null
) {
return;
}
this.addFieldQueryAndSearch(this.state.selectedField.name, value);
}
private addFieldQueryAndSearch(key: string, value: string) {
this.setState(
{
searchString: `${key}=${value} ` + this.state.searchString,
selectedField: null,
},
() => this.onSearch()
);
}
private async onPageChanged(newPageIndex: number) {
if (
this.state.state !== SearchState.SEARCHED_POLLING &&
this.state.state !== SearchState.SEARCHED_POLLING_FINISHED
) {
throw new Error(
"Weird state, state=" +
this.state.state +
", but attempted to change page"
);
}
try {
const newEvents = await this.props.getResults(
this.state.jobId,
newPageIndex * EVENTS_PER_PAGE,
EVENTS_PER_PAGE
);
this.setState({
searchResult: newEvents,
currentPageIndex: newPageIndex,
});
this.setQueryParams({
page: newPageIndex.toString(),
});
} catch (e) {
console.log(e);
}
}
private async onCancel() {
if (this.state.state === SearchState.SEARCHED_POLLING_FINISHED) {
// Polling already finished so there is nothing to cancel, but it's not an error
return;
}
if (this.state.state !== SearchState.SEARCHED_POLLING) {
throw new Error("Weird state");
}
await this.props.abortJob(this.state.jobId);
window.clearTimeout(this.state.poller);
this.setState({
...this.state,
state: SearchState.SEARCHED_POLLING_FINISHED,
});
}
private async onSearch() {
if (this.state.state === SearchState.SEARCHED_POLLING) {
try {
window.clearTimeout(this.state.poller);
await this.props.abortJob(this.state.jobId);
} catch (e) {
console.warn(
`failed to abort previous jobId=${this.state.jobId}, will continue with new search`
);
}
}
this.setState({
state: SearchState.WAITING_FOR_SEARCH,
});
try {
const qp = createSearchQueryParams(
this.state.searchString,
this.state.selectedTime
);
this.clearQueryParams();
this.setQueryParams(qp);
} catch (e) {
console.warn("failed to set new query params when starting search", e);
}
try {
const startJobResult = await this.props.startJob(
this.state.searchString,
this.state.selectedTime
);
this.setState({
...this.state,
state: SearchState.SEARCHED_POLLING,
jobId: startJobResult.id,
poller: window.setTimeout(
async () => this.poll(startJobResult.id),
500
),
searchResult: [],
numMatched: 0,
currentPageIndex: 0,
});
this.setQueryParams({ jobId: startJobResult.id.toString() });
} catch (e) {
console.log(e);
this.setState({
...this.state,
state: SearchState.SEARCHED_ERROR,
searchError: "Something went wrong.",
});
}
this.props.addRecentSearch({
searchString: this.state.searchString,
timeSelection: this.state.selectedTime,
searchTime: new Date(),
});
}
private clearQueryParams() {
this.props.setQueryParams(new URLSearchParams());
}
private setQueryParams(qp: { [key: string]: string }) {
const queryParams = this.props.getQueryParams();
for (const k of Object.keys(qp)) {
queryParams.set(k, qp[k]);
}
this.props.setQueryParams(queryParams);
}
private async poll(id: number) {
if (this.state.state !== SearchState.SEARCHED_POLLING) {
throw new Error(
"Really weird state! In poller but state != SEARCHED_POLLING"
);
}
if (id !== this.state.jobId) {
return;
}
try {
const pollResult = await this.props.pollJob(id);
if (id !== this.state.jobId) {
return;
}
const topFields = Object.keys(pollResult.stats.fieldCount)
.sort(
(a, b) =>
pollResult.stats.fieldCount[b] - pollResult.stats.fieldCount[a]
)
.slice(0, TOP_FIELDS_COUNT)
.reduce((prev, k) => {
prev[k] = pollResult.stats.fieldCount[k];
return prev;
}, {} as any);
const nextState: any = {
...this.state,
numMatched: pollResult.stats.numMatchedEvents,
allFields: pollResult.stats.fieldCount,
topFields: topFields,
};
if (
pollResult.state == JobState.ABORTED ||
pollResult.state == JobState.FINISHED
) {
window.clearTimeout(this.state.poller);
nextState.state = SearchState.SEARCHED_POLLING_FINISHED;
} else {
nextState.poller = window.setTimeout(() => this.poll(id), 500);
}
if (
this.state.searchResult.length < EVENTS_PER_PAGE &&
pollResult.stats.numMatchedEvents > this.state.searchResult.length
) {
nextState.searchResult = await this.props.getResults(
id,
this.state.currentPageIndex * EVENTS_PER_PAGE,
EVENTS_PER_PAGE
);
if (id !== this.state.jobId) {
return;
}
}
this.setState(nextState);
} catch (e) {
console.log(e);
}
}
} | the_stack |
import { DEFAULT_FONT, DEFAULT_TEXT_MAX_WIDTH, SEGMENT_NUMBER } from '@/constant/tool';
import { IPolygonPoint } from '@/types/tool/polygon';
import { createSmoothCurvePointsFromPointList } from './tool/polygonTool';
import Vector from './VectorUtils';
/**
* 基础的三角运算
*/
export class Trigonometric {
public static tanAPlusB(tanA: number, tanB: number) {
return (tanA + tanB) / (1 - tanA * tanB);
}
public static sinAPlusB(sinA: number, cosA: number, sinB: number, cosB: number) {
return cosB * sinA + cosA * sinB;
}
public static cosAPlusB(sinA: number, cosA: number, sinB: number, cosB: number) {
return cosA * cosB - sinA * sinB;
}
}
export default class MathUtils {
/**
* 是否在指定范围内
* @param value 需要判断的值
* @param range 范围
* @returns {boolean} 是否在范围内
*/
public static isInRange = (value: number | number[], range: number[]) => {
const min = Math.min(...range);
const max = Math.max(...range);
const inRange = (v: number) => v <= max && v >= min;
const values = Array.isArray(value) ? value : [value];
return values.every((v: number) => inRange(v));
};
/**
* 限制点在范围,返回
* @param value
* @param range
* @returns {ICoordinate} 在范围内的点
*/
public static withinRange = (value: number, range: number[]) => {
const min = Math.min(...range);
const max = Math.max(...range);
if (value > max) {
return max;
}
if (value < min) {
return min;
}
return value;
};
// 获取下一次旋转的角度
public static getRotate(rotate: number) {
if (rotate + 90 >= 360) {
return rotate + 90 - 360;
}
return rotate + 90;
}
public static getLineLength(point1: ICoordinate, point2: ICoordinate) {
return Math.sqrt(Math.pow(point2.y - point1.y, 2) + Math.pow(point2.x - point1.x, 2));
}
/**
* 计算坐标点的视窗范围
* @param array 坐标值数组
* @returns 视窗范围 { top, left, right, bottom }
*/
public static calcViewportBoundaries = (
array: ICoordinate[] | undefined,
isCurve: boolean = false,
numberOfSegments: number = SEGMENT_NUMBER,
zoom: number = 1,
) => {
if (!array) {
return {
top: 0,
bottom: 0,
left: 0,
right: 0,
};
}
const MIN_LENGTH = 20 / zoom;
const xAxis: number[] = [];
const yAxis: number[] = [];
let points = array;
if (isCurve) {
points = createSmoothCurvePointsFromPointList(array, numberOfSegments);
}
points.forEach(({ x, y }: ICoordinate) => {
xAxis.push(x);
yAxis.push(y);
});
let minX = Math.min(...xAxis);
let maxX = Math.max(...xAxis);
let minY = Math.min(...yAxis);
let maxY = Math.max(...yAxis);
const diffX = maxX - minX;
const diffY = maxY - minY;
if (diffX < MIN_LENGTH) {
const addLen = (MIN_LENGTH - diffX) / 2;
minX -= addLen;
maxX += addLen;
}
if (diffY < MIN_LENGTH) {
const addLen = (MIN_LENGTH - diffY) / 2;
minY -= addLen;
maxY += addLen;
}
return {
top: minY,
bottom: maxY,
left: minX,
right: maxX,
};
};
/**
* 获取当前左边举例线段的最短路径,建议配合 isHoverLine 使用
*
* @export
* @param {ICoordinate} pt
* @param {ICoordinate} begin
* @param {ICoordinate} end
* @param {boolean} ignoreRatio
* @returns
*/
public static getFootOfPerpendicular = (
pt: ICoordinate, // 直线外一点
begin: ICoordinate, // 直线开始点
end: ICoordinate,
/* 使用坐标范围 */
useAxisRange = false,
) => {
// 直线结束点
let retVal: any = { x: 0, y: 0 };
const dx = begin.x - end.x;
const dy = begin.y - end.y;
if (Math.abs(dx) < 0.00000001 && Math.abs(dy) < 0.00000001) {
retVal = begin;
return retVal;
}
let u = (pt.x - begin.x) * (begin.x - end.x) + (pt.y - begin.y) * (begin.y - end.y);
u /= dx * dx + dy * dy;
retVal.x = begin.x + u * dx;
retVal.y = begin.y + u * dy;
const length = this.getLineLength(pt, retVal);
const ratio = 2;
const fromX = Math.min(begin.x, end.x);
const toX = Math.max(begin.x, end.x);
const fromY = Math.min(begin.y, end.y);
const toY = Math.max(begin.y, end.y);
/** x和y坐标都超出范围内 */
const allAxisOverRange = !(this.isInRange(pt.x, [fromX, toX]) || this.isInRange(pt.y, [fromY, toY]));
/** x或y坐标超出范围 */
const someAxisOverRange = pt.x > toX + ratio || pt.x < fromX - ratio || pt.y > toY + ratio || pt.y < fromY - ratio;
const isOverRange = useAxisRange ? allAxisOverRange : someAxisOverRange;
if (isOverRange) {
return {
footPoint: retVal,
length: Infinity,
};
}
return {
footPoint: retVal,
length,
};
};
/**
* 获取当前文本的背景面积
* @param canvas
* @param text
* @param maxWidth
* @param lineHeight
* @returns
*/
public static getTextArea(
canvas: HTMLCanvasElement,
text: string,
maxWidth: number = DEFAULT_TEXT_MAX_WIDTH,
font = DEFAULT_FONT,
lineHeight?: number,
) {
if (typeof text !== 'string') {
return {
width: 0,
height: 0,
};
}
const context: CanvasRenderingContext2D = canvas.getContext('2d')!;
context.font = font;
let height = 0;
if (typeof lineHeight === 'undefined') {
lineHeight =
(canvas && parseInt(window.getComputedStyle(canvas).lineHeight, 10)) ||
parseInt(window.getComputedStyle(document.body).lineHeight, 10);
}
const fontHeight: number =
(canvas && parseInt(window.getComputedStyle(canvas).fontSize, 10)) ||
parseInt(window.getComputedStyle(document.body).fontSize, 10) ||
0;
const arrParagraph = text.split('\n');
let lineWidth = 0; // 最大长度定位
for (let i = 0; i < arrParagraph.length; i++) {
// 字符分隔为数组
const arrText = arrParagraph[i].split('');
let line = '';
for (let n = 0; n < arrText.length; n++) {
const testLine = line + arrText[n];
const metrics = context.measureText(testLine);
const textWidth = metrics.width;
if (textWidth > maxWidth && n > 0) {
line = arrText[n];
height += lineHeight;
lineWidth = maxWidth;
} else {
line = testLine;
if (textWidth > lineWidth) {
lineWidth = textWidth;
}
}
}
if (i !== arrParagraph.length - 1) {
height += lineHeight;
}
}
return {
width: lineWidth,
height: height + fontHeight,
lineHeight,
fontHeight,
};
}
/**
* 获取线条中心点
* @param line
* @returns
*/
public static getLineCenterPoint(line: [ICoordinate, ICoordinate]) {
const [p1, p2] = line;
const vector = Vector.getVector(p1, p2);
return {
x: p1.x + vector.x / 2,
y: p1.y + vector.y / 2,
};
}
/**
* 获取线条的垂线
* @param line
* @returns
*/
public static getPerpendicularLine(line: ICoordinate[]) {
if (line.length !== 2) {
return undefined;
}
const [p1, p2] = line;
const p3 = {
x: p2.x + p2.y - p1.y,
y: p2.y - (p2.x - p1.x),
};
return [p2, p3];
}
/**
* 获取当前垂直于直线的最后一个点的垂线点
* @param line
* @param coordinate
* @returns
*/
public static getPerpendicularFootOfLine(line: ICoordinate[], coordinate: ICoordinate) {
if (line.length !== 2) {
return line;
}
const perpendicularLine = this.getPerpendicularLine(line);
if (!perpendicularLine) {
return line;
}
const [begin, end] = perpendicularLine;
return this.getFootOfPerpendicular(coordinate, begin, end).footPoint;
}
/**
* 从正三角形获取正四边形
* @param triangle
* @returns
*/
public static getQuadrangleFromTriangle(triangle: ICoordinate[]) {
if (triangle.length !== 3) {
return triangle;
}
const [p1, p2, p3] = triangle;
const p4 = {
x: p3.x + p1.x - p2.x,
y: p3.y + p1.y - p2.y,
};
return [p1, p2, p3, p4];
}
/**
* 矩形拖动线,实现横向的扩大缩小
* @param dragStartCoord
* @param currentCoord
* @param basicLine
* @returns
*/
public static getRectPerpendicularOffset(
dragStartCoord: ICoordinate,
currentCoord: ICoordinate,
basicLine: [ICoordinate, ICoordinate],
) {
const [p1, p2] = basicLine;
const footer1 = this.getFootOfPerpendicular(dragStartCoord, p1, p2).footPoint;
const footer2 = this.getFootOfPerpendicular(currentCoord, p1, p2).footPoint;
// 数值计算
const offset = {
x: footer1.x - footer2.x,
y: footer1.y - footer2.y,
};
const newPoint = Vector.add(currentCoord, offset);
const vector3 = Vector.getVector(dragStartCoord, newPoint);
return vector3;
}
/**
* 获取当前真实 Index
* @param index
* @param len
* @returns
*/
public static getArrayIndex(index: number, len: number) {
if (index < 0) {
return len + index;
}
if (index >= len) {
return index - len;
}
return index;
}
/**
* 在矩形点集拖动一个点时,需要进行一直维持矩形
* @param pointList
* @param changePointIndex
* @param offset
* @returns
*/
public static getPointListFromPointOffset(
pointList: [ICoordinate, ICoordinate, ICoordinate, ICoordinate],
changePointIndex: number,
offset: ICoordinate,
) {
const prePointIndex = this.getArrayIndex(changePointIndex - 1, pointList.length);
const nextPointIndex = this.getArrayIndex(changePointIndex + 1, pointList.length);
const originIndex = this.getArrayIndex(changePointIndex - 2, pointList.length);
const newPointList = [...pointList];
newPointList[changePointIndex] = Vector.add(newPointList[changePointIndex], offset);
const newFooter1 = this.getFootOfPerpendicular(
newPointList[changePointIndex],
newPointList[originIndex],
newPointList[prePointIndex],
).footPoint;
const newFooter2 = this.getFootOfPerpendicular(
newPointList[changePointIndex],
newPointList[nextPointIndex],
newPointList[originIndex],
).footPoint;
newPointList[prePointIndex] = newFooter1;
newPointList[nextPointIndex] = newFooter2;
return newPointList;
}
/**
* 获取矩形框旋转中心
* @param rectPointList
* @returns
*/
public static getRectCenterPoint(rectPointList: [ICoordinate, ICoordinate, ICoordinate, ICoordinate]) {
const [p1, , p3] = rectPointList;
return {
x: (p1.x + p3.x) / 2,
y: (p1.y + p3.y) / 2,
};
}
/**
* 获取按指定的 angle 旋转的角度后的矩形
* @param rotate
* @param rectPointList
* @returns
*/
public static rotateRectPointList(angle = 5, rectPointList: [ICoordinate, ICoordinate, ICoordinate, ICoordinate]) {
const centerPoint = this.getRectCenterPoint(rectPointList);
const { PI } = Math;
const sinB = Math.sin((angle * PI) / 180);
const cosB = Math.cos((angle * PI) / 180);
return rectPointList.map((point) => {
const vector = Vector.getVector(centerPoint, point);
const len = Vector.len(vector);
const sinA = vector.y / len;
const cosA = vector.x / len;
return {
x: len * Trigonometric.cosAPlusB(sinA, cosA, sinB, cosB) + centerPoint.x,
y: len * Trigonometric.sinAPlusB(sinA, cosA, sinB, cosB) + centerPoint.y,
};
});
}
/**
* 通过当前坐标 + 已知两点获取正多边形
* @param coordinate
* @param pointList
* @returns
*/
public static getRectangleByRightAngle(coordinate: ICoordinate, pointList: IPolygonPoint[]) {
if (pointList.length !== 2) {
return pointList;
}
const newPoint = MathUtils.getPerpendicularFootOfLine(pointList, coordinate);
return MathUtils.getQuadrangleFromTriangle([...pointList, newPoint]);
}
} | the_stack |
import { ok, err, okAsync, errAsync, Result, ResultAsync } from '../src'
(function describe(_ = 'Result') {
(function describe(_ = 'andThen') {
(function it(_ = 'Combines two equal error types (native scalar types)') {
type Expectation = Result<unknown, string>
const result: Expectation = ok<number, string>(123)
.andThen((val) => err('yoooooo dude' + val))
});
(function it(_ = 'Combines two equal error types (custom types)') {
interface MyError {
stack: string
code: number
}
type Expectation = Result<string, MyError>
const result: Expectation = ok<number, MyError>(123)
.andThen((val) => err<string, MyError>({ stack: '/blah', code: 500 }))
});
(function it(_ = 'Creates a union of error types for disjoint types') {
interface MyError {
stack: string
code: number
}
type Expectation = Result<string, MyError | string[]>
const result: Expectation = ok<number, MyError>(123)
.andThen((val) => err<string, string[]>(['oh nooooo']))
});
(function it(_ = 'Infers error type when returning disjoint types (native scalar types)') {
type Expectation = Result<unknown, string | number | boolean>
const result: Expectation = ok<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
case 2:
return err(123)
default:
return err(false)
}
})
});
(function it(_ = 'Infers error type when returning disjoint types (custom types)') {
interface MyError {
stack: string
code: number
}
type Expectation = Result<unknown, string | number | MyError>
const result: Expectation = ok<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
case 2:
return err(123)
default:
return err({ stack: '/blah', code: 500 })
}
})
});
(function it(_ = 'Infers new ok type when returning both Ok and Err (same as initial)') {
type Expectation = Result<number, unknown>
const result: Expectation = ok<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
default:
return ok(val + 456)
}
})
});
(function it(_ = 'Infers new ok type when returning both Ok and Err (different from initial)') {
const initial = ok<number, string>(123)
type Expectation = Result<string, unknown>
const result: Expectation = initial
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
default:
return ok(val + ' string')
}
})
});
(function it(_ = 'Infers new err type when returning both Ok and Err') {
interface MyError {
stack: string
code: number
}
type Expectation = Result<unknown, string | number | MyError>
const result: Expectation = ok<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
case 2:
return ok(123)
default:
return err({ stack: '/blah', code: 500 })
}
})
});
(function it(_ = 'allows specifying the E and T types explicitly') {
type Expectation = Result<'yo', number>
const result: Expectation = ok(123).andThen<'yo', number>(val => {
return ok('yo')
})
});
});
(function describe(_ = 'orElse') {
(function it(_ = 'the type of the argument is the error type of the result') {
type Expectation = string
const result = ok<number, string>(123)
.orElse((val: Expectation) => {
switch (val) {
case '2':
return err(1)
default:
return err(1)
}
})
});
(function it(_ = 'infers the err return type with multiple returns (same type) ') {
type Expectation = Result<number, number>
const result: Expectation = ok<number, string>(123)
.orElse((val) => {
switch (val) {
case '2':
return err(1)
default:
return err(1)
}
})
});
(function it(_ = 'infers the err return type with multiple returns (different type) ') {
type Expectation = Result<number, number | string>
const result: Expectation = ok<number, string>(123)
.orElse((val) => {
switch (val) {
case '2':
return err(1)
default:
return err('1')
}
})
});
(function it(_ = 'infers ok and err return types with multiple returns ') {
type Expectation = Result<number, number | string>
const result: Expectation = ok<number, string>(123)
.orElse((val) => {
switch (val) {
case '1':
return ok(1)
case '2':
return err(1)
default:
return err('1')
}
})
});
(function it(_ = 'allows specifying the E and T types explicitly') {
type Expectation = Result<'yo', string>
const result: Expectation = ok<'yo', number>('yo').orElse<string>(val => {
return err('yo')
})
});
});
(function describe(_ = 'asyncAndThen') {
(function it(_ = 'Combines two equal error types (native scalar types)') {
type Expectation = ResultAsync<unknown, string>
const result: Expectation = ok<number, string>(123)
.asyncAndThen((val) => errAsync('yoooooo dude' + val))
});
(function it(_ = 'Combines two equal error types (custom types)') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<string, MyError>
const result: Expectation = ok<number, MyError>(123)
.asyncAndThen((val) => errAsync<string, MyError>({ stack: '/blah', code: 500 }))
});
(function it(_ = 'Creates a union of error types for disjoint types') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<string, MyError | string[]>
const result: Expectation = ok<number, MyError>(123)
.asyncAndThen((val) => errAsync<string, string[]>(['oh nooooo']))
});
});
});
(function describe(_ = 'ResultAsync') {
(function describe(_ = 'andThen') {
(function it(_ = 'Combines two equal error types (native scalar types)') {
type Expectation = ResultAsync<unknown, string>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => err('yoooooo dude' + val))
});
(function it(_ = 'Combines two equal error types (custom types)') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<string, MyError>
const result: Expectation = okAsync<number, MyError>(123)
.andThen((val) => err<string, MyError>({ stack: '/blah', code: 500 }))
});
(function it(_ = 'Creates a union of error types for disjoint types') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<string, MyError | string[]>
const result: Expectation = okAsync<number, MyError>(123)
.andThen((val) => err<string, string[]>(['oh nooooo']))
});
(function describe(_ = 'when returning Result types') {
(function it(_ = 'Infers error type when returning disjoint types (native scalar types)') {
type Expectation = ResultAsync<unknown, string | number | boolean>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
case 2:
return err(123)
default:
return err(false)
}
})
});
(function it(_ = 'Infers error type when returning disjoint types (custom types)') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<unknown, string | number | MyError>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
case 2:
return err(123)
default:
return err({ stack: '/blah', code: 500 })
}
})
});
(function it(_ = 'Infers new ok type when returning both Ok and Err (same as initial)') {
type Expectation = ResultAsync<number, unknown>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
default:
return ok(val + 456)
}
})
});
(function it(_ = 'Infers new ok type when returning both Ok and Err (different from initial)') {
const initial = okAsync<number, string>(123)
type Expectation = ResultAsync<string, unknown>
const result: Expectation = initial
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
default:
return ok(val + ' string')
}
})
});
(function it(_ = 'Infers new err type when returning both Ok and Err') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<unknown, string | number | MyError>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return err('yoooooo dude' + val)
case 2:
return ok(123)
default:
return err({ stack: '/blah', code: 500 })
}
})
});
});
(function describe(_ = 'when returning ResultAsync types') {
(function it(_ = 'Infers error type when returning disjoint types (native scalar types)') {
type Expectation = ResultAsync<unknown, string | number | boolean>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return errAsync('yoooooo dude' + val)
case 2:
return errAsync(123)
default:
return errAsync(false)
}
})
});
(function it(_ = 'Infers error type when returning disjoint types (custom types)') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<unknown, string | number | MyError>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return errAsync('yoooooo dude' + val)
case 2:
return errAsync(123)
default:
return errAsync({ stack: '/blah', code: 500 })
}
})
});
(function it(_ = 'Infers new ok type when returning both Ok and Err (same as initial)') {
type Expectation = ResultAsync<number, unknown>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return errAsync('yoooooo dude' + val)
default:
return okAsync(val + 456)
}
})
});
(function it(_ = 'Infers new ok type when returning both Ok and Err (different from initial)') {
const initial = okAsync<number, string>(123)
type Expectation = ResultAsync<string, unknown>
const result: Expectation = initial
.andThen((val) => {
switch (val) {
case 1:
return errAsync('yoooooo dude' + val)
default:
return okAsync(val + ' string')
}
})
});
(function it(_ = 'Infers new err type when returning both Ok and Err') {
interface MyError {
stack: string
code: number
}
type Expectation = ResultAsync<unknown, string | number | MyError>
const result: Expectation = okAsync<number, string>(123)
.andThen((val) => {
switch (val) {
case 1:
return errAsync('yoooooo dude' + val)
case 2:
return okAsync(123)
default:
return errAsync({ stack: '/blah', code: 500 })
}
})
});
});
(function describe(_ = 'when returning a mix of Result and ResultAsync types') {
(function it(_ = 'allows for explicitly specifying the Ok and Err types when inference fails') {
type Expectation = ResultAsync<number | boolean, string | number | boolean>
const result: Expectation = okAsync<number, string>(123)
.andThen<number | boolean, string | number | boolean>((val) => {
switch (val) {
case 1:
return errAsync('yoooooo dude' + val)
case 2:
return err(123)
default:
return okAsync(false)
}
})
});
});
});
(function describe(_ = 'orElse') {
(function it(_ = 'the type of the argument is the error type of the result') {
type Expectation = string
const result = okAsync<number, string>(123)
.orElse((val: Expectation) => {
switch (val) {
case '2':
return errAsync(1)
default:
return errAsync(1)
}
})
});
(function it(_ = 'infers the err return type with multiple returns (same type) ') {
type Expectation = ResultAsync<number, number>
const result: Expectation = okAsync<number, string>(123)
.orElse((val) => {
switch (val) {
case '2':
return errAsync(1)
default:
return errAsync(1)
}
})
});
(function it(_ = 'infers the err return type with multiple returns (different type) ') {
type Expectation = ResultAsync<number, number | string>
const result: Expectation = okAsync<number, string>(123)
.orElse((val) => {
switch (val) {
case '2':
return errAsync(1)
default:
return errAsync('1')
}
})
});
(function it(_ = 'infers ok and err return types with multiple returns ') {
type Expectation = ResultAsync<number, number | string>
const result: Expectation = okAsync<number, string>(123)
.orElse((val) => {
switch (val) {
case '1':
return okAsync(1)
case '2':
return errAsync(1)
default:
return errAsync('1')
}
})
});
(function it(_ = 'allows specifying ok and err return types when mixing Result and ResultAsync in returns ') {
type Expectation = ResultAsync<number, number | string>
const result: Expectation = okAsync<number, string>(123)
.orElse<number | string>((val) => {
switch (val) {
case '1':
return ok(1)
case '2':
return errAsync(1)
default:
return errAsync('1')
}
})
});
});
});
(function describe(_ = 'Combine on Unbounded lists') {
// TODO:
// https://github.com/supermacro/neverthrow/issues/226
})(); | the_stack |
import {Device} from '../Device';
import Dimensions = Utils.Measurements.Dimensions;
import DisplayObject = etch.drawing.DisplayObject;
import Size = minerva.Size;
import {IApp} from '../IApp';
import {Block} from './../Blocks/Block';
import {ToneSource} from './../Blocks/Sources/ToneSource';
import {ComputerKeyboard} from './../Blocks/Interaction/ComputerKeyboard';
import {Chopper} from './../Blocks/Effects/Post/Chopper';
import {Power} from './../Blocks/Power/Power';
import {ParticleEmitter} from './../Blocks/Power/ParticleEmitter';
//import Point = minerva.Point;
import Point = etch.primitives.Point;
declare var App: IApp;
export class Tutorial extends DisplayObject{
public Debug: boolean = true;
public Open: boolean;
public SplashOpen: boolean;
public Hover: boolean = false;
public HotSpots: Point[];
public CurrentScene: number;
public TotalScenes: number;
public IntroLines: number;
public TaskLines: number;
public TextWidth: number;
private _LineHeight: number;
private _SkipBtnWidth: number;
private _DoneBtnWidth: number;
private _TutKeys: boolean = false;
public Text: any;
public Offset: Point;
public Offset2: Point;
private _RollOvers: boolean[] = [];
public WatchedBlocks: Block[] = [];
private _AnimateCount: number;
public AnimatePolarity: number;
public OptionsInteract: boolean = false;
Init(drawTo: IDisplayContext): void {
super.Init(drawTo);
this.Open = false;
this.HotSpots = [];
this.IntroLines = 0;
this.TaskLines = 0;
this.TextWidth = 190;
this._LineHeight = 14;
this.Offset = new Point(-20,0);
this.Offset2 = new Point(-1,0);
this._AnimateCount = 0;
this.AnimatePolarity = 1;
this.Text = App.L10n.UI.Tutorial;
this.CurrentScene = 1;
this.TotalScenes = this.Text.Scenes.length;
}
CheckLaunch() {
if (this.Debug) {
this.OpenSplash();
} else {
if (!App.SkipTutorial) {
this.OpenSplash();
}
}
}
//-------------------------------------------------------------------------------------------
// CHECK TUTORIAL TASK COMPLETION
//-------------------------------------------------------------------------------------------
CheckTask() {
if (this.Open) {
var check = false;
this.WatchedBlocks = [];
var i, tone, toneConnections, controller, controllerUnplugged, effect, effectUnplugged, particle, power, powerConnections, particleConnected;
// GET OUR TONE BLOCK //
for (i=0; i<App.Blocks.length; i++) {
if (App.Blocks[i] instanceof ToneSource && !tone) {
tone = App.Blocks[i];
this.WatchedBlocks[0] = tone;
}
if (App.Blocks[i] instanceof ComputerKeyboard && !controllerUnplugged) {
controllerUnplugged = App.Blocks[i];
this.WatchedBlocks[1] = controllerUnplugged;
}
if (App.Blocks[i] instanceof Chopper && !effectUnplugged) {
effectUnplugged = App.Blocks[i];
this.WatchedBlocks[4] = effectUnplugged;
}
if (App.Blocks[i] instanceof ParticleEmitter && !particle) {
particle = App.Blocks[i];
this.WatchedBlocks[5] = particle;
}
if (App.Blocks[i] instanceof Power && !power) {
power = App.Blocks[i];
this.WatchedBlocks[6] = power;
}
}
// GET TONE'S RELEVANT CONNECTIONS //
if (tone && tone.Connections.Count) {
toneConnections = tone.Connections.ToArray();
for (i=0; i<toneConnections.length; i++) {
if (toneConnections[i] instanceof ComputerKeyboard && !controller) {
controller = toneConnections[i];
this.WatchedBlocks[2] = controller;
}
if (toneConnections[i] instanceof Chopper && !effect) {
effect = toneConnections[i];
this.WatchedBlocks[3] = effect;
}
}
}
// GET POWER'S RELEVANT CONNECTIONS //
if (power && power.Connections.Count) {
powerConnections = power.Connections.ToArray();
for (i=0; i<powerConnections.length; i++) {
if (powerConnections[i] instanceof ParticleEmitter && !particleConnected) {
particleConnected = powerConnections[i];
this.WatchedBlocks[7] = particleConnected;
}
}
}
var cx = 0.5;
if (App.Metrics.Device === Device.mobile) {
cx = 0.35;
}
// IF KEYBOARD TUTORIAL //
if (this._TutKeys) {
switch (this.CurrentScene) {
case 1:
if (tone && !App.MainScene.IsDraggingABlock) { // TONE CREATED
check = true;
App.MainScene.MainSceneDragger.Jump(tone.Position,new Point(cx,0.5),1000);
}
break;
case 2:
if (controller && !App.MainScene.IsDraggingABlock) { // KEYBOARD CONNECTED TO TONE
check = true;
}
break;
case 3:
if (effect && !App.MainScene.IsDraggingABlock) { // CHOPPER CONNECTED TO TONE
check = true;
}
break;
case 4:
if (this.OptionsInteract && App.MainScene.SelectedBlock==effect) { // CHOPPER OPTIONS
check = true;
App.MainScene.MainSceneDragger.Jump(tone.Position,new Point(cx,0.5),1000);
}
break;
case 5:
if (!controller && !controllerUnplugged && !App.MainScene.IsDraggingABlock) { // KEYBOARD TRASHED (this one could be more rigid)
check = true;
App.MainScene.MainSceneDragger.Jump(tone.Position,new Point(cx,0.35),1000);
}
break;
case 6:
if (particle && !App.MainScene.IsDraggingABlock) { // PARTICLE EMITTER CREATED
check = true;
}
break;
case 7:
if (particleConnected && !App.MainScene.IsDraggingABlock) { // PARTICLE CONNECTED
check = true;
}
break;
default:
break;
}
}
// IF TOUCHSCREEN TUTORIAL //
else {
switch (this.CurrentScene) {
case 1:
if (tone && !App.MainScene.IsDraggingABlock) { // TONE CREATED
check = true;
App.MainScene.MainSceneDragger.Jump(tone.Position,new Point(cx,0.5),1000);
}
break;
case 2:
if (particle && !App.MainScene.IsDraggingABlock) { // PARTICLE EMITTER CREATED
check = true;
}
break;
case 3:
if (particleConnected && !App.MainScene.IsDraggingABlock) { // PARTICLE CONNECTED
check = true;
}
break;
case 4:
if (effect && !App.MainScene.IsDraggingABlock) { // CHOPPER CONNECTED TO TONE
check = true;
}
break;
case 5:
if (this.OptionsInteract && App.MainScene.SelectedBlock==effect) { // CHOPPER OPTIONS
check = true;
App.MainScene.MainSceneDragger.Jump(tone.Position,new Point(cx,0.5),1000);
}
break;
default:
break;
}
}
if (check) {
this.NextScene();
}
}
}
//-------------------------------------------------------------------------------------------
// UPDATE
//-------------------------------------------------------------------------------------------
Update() {
if (this.Open) {
this.UpdateHotspots();
}
if (this.SplashOpen) {
//this.AnimateButton();
}
}
//-------------------------------------------------------------------------------------------
// DRAW
//-------------------------------------------------------------------------------------------
Draw() {
var ctx = this.Ctx;
var units = App.Unit;
var midType = App.Metrics.TxtMid;
var italicType = App.Metrics.TxtItalic3;
var headerType = App.Metrics.TxtHeader;
var x = App.Width - (this.Offset.x*units);
var y = (App.Height *0.5) + (this.Offset.y*units) - (20*units);
var lineHeight = this._LineHeight*units;
var introOffset = (this.IntroLines+2) * lineHeight;
var taskOffset = (this.TaskLines) * lineHeight;
var splashOffset = App.Width * this.Offset2.x;
ctx.globalAlpha = 1;
ctx.textAlign = "center";
App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]);
// SPLASH //
if (this.Offset2.x > -1) { // draw if on screen
var mes = this.Text.Splash1.Message;
var yes = this.Text.Splash1.Y.toUpperCase();
var no = this.Text.Splash1.N.toUpperCase();
if (App.Blocks.length) {
mes = this.Text.Splash2.Message;
yes = this.Text.Splash2.Y.toUpperCase();
no = this.Text.Splash2.N.toUpperCase();
// BG //
App.FillColor(ctx,App.Palette[2]);
ctx.globalAlpha = 0.16;
ctx.fillRect((App.Width*0.5) + splashOffset - (140*units), (App.Height*0.5) - (55*units), (280*units),(140*units));
ctx.globalAlpha = 0.9;
ctx.fillRect((App.Width*0.5) + splashOffset - (140*units), (App.Height*0.5) - (60*units), (280*units),(140*units));
ctx.globalAlpha = 1;
App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]);
}
ctx.font = headerType;
ctx.fillText(mes, (App.Width*0.5) + splashOffset, (App.Height*0.5) - (10*units));
var padding = 60*units;
var iconY = (App.Height*0.5) + (20*units);
ctx.font = midType;
ctx.fillText(yes, (App.Width*0.5) - padding + splashOffset, iconY + (30*units));
ctx.fillText(no, (App.Width*0.5) + padding + splashOffset, iconY + (30*units));
var ym = 1;
var nm = 1;
if (this._RollOvers[0]) {
ym = 1.2;
}
if (this._RollOvers[1]) {
nm = 1.2;
}
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
ctx.lineWidth = 2;
// TOUR //
ctx.beginPath();
// DOUBLE //
ctx.moveTo((App.Width*0.5) - padding + splashOffset - ((16*ym)*units), iconY + (((4*ym)*units)*this.AnimatePolarity));
ctx.lineTo((App.Width*0.5) - padding + splashOffset - ((14*ym)*units), iconY + (((6*ym)*units)*this.AnimatePolarity));
ctx.moveTo((App.Width*0.5) - padding + splashOffset - ((12*ym)*units), iconY + (((8*ym)*units)*this.AnimatePolarity));
ctx.lineTo((App.Width*0.5) - padding + splashOffset - ((8*ym)*units), iconY + (((12*ym)*units)*this.AnimatePolarity));
ctx.lineTo((App.Width*0.5) - padding + splashOffset + ((8*ym)*units), iconY - (((4*ym)*units)*this.AnimatePolarity));
ctx.lineTo((App.Width*0.5) - padding + splashOffset + ((12*ym)*units), iconY);
//
ctx.moveTo((App.Width*0.5) - padding + splashOffset - ((12*ym)*units), iconY);
ctx.lineTo((App.Width*0.5) - padding + splashOffset - ((8*ym)*units), iconY + (((4*ym)*units)*this.AnimatePolarity));
ctx.lineTo((App.Width*0.5) - padding + splashOffset + ((8*ym)*units), iconY - (((12*ym)*units)*this.AnimatePolarity));
ctx.lineTo((App.Width*0.5) - padding + splashOffset + ((12*ym)*units), iconY - (((8*ym)*units)*this.AnimatePolarity));
ctx.moveTo((App.Width*0.5) - padding + splashOffset + ((14*ym)*units), iconY - (((6*ym)*units)*this.AnimatePolarity));
ctx.lineTo((App.Width*0.5) - padding + splashOffset + ((16*ym)*units), iconY - (((4*ym)*units)*this.AnimatePolarity));
// SKIP //
ctx.moveTo((App.Width*0.5) + padding + splashOffset - ((8*nm)*units), iconY - ((8*nm)*units));
ctx.lineTo((App.Width*0.5) + padding + splashOffset, iconY);
ctx.lineTo((App.Width*0.5) + padding + splashOffset - ((8*nm)*units), iconY + ((8*nm)*units));
ctx.moveTo((App.Width*0.5) + padding + splashOffset, iconY - ((8*nm)*units));
ctx.lineTo((App.Width*0.5) + padding + splashOffset + ((8*nm)*units), iconY);
ctx.lineTo((App.Width*0.5) + padding + splashOffset, iconY + ((8*nm)*units));
ctx.stroke();
App.StrokeColor(ctx,App.Palette[1]);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo((App.Width*0.5) + splashOffset, (App.Height*0.5) + (5*units));
ctx.lineTo((App.Width*0.5) + splashOffset, (App.Height*0.5) + (55*units));
ctx.stroke();
}
// SIDEBAR //
if (this.Offset.x > -20) { //draw if on screen
// TASK NUMBER //
ctx.textAlign = "left";
ctx.font = headerType;
var numberText = "0"+this.CurrentScene+"/0"+(this.TotalScenes);
var numberWidth = ctx.measureText(numberText).width;
ctx.fillText(numberText, x, y - (20*units));
// UNDERLINE //
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + (this.TextWidth*units), y);
ctx.stroke();
// SMALL SKIP BUTTON //
var btnY = 50*units;
ctx.font = midType;
var btnTxt = "";
var roll = 0;
if (this._RollOvers[2]) {
roll = units;
}
if (this.CurrentScene < this.TotalScenes) {
btnTxt = this.Text.SkipButton.toUpperCase();
ctx.fillText(btnTxt, x + (10*units), y + btnY + (14*units) + introOffset + taskOffset);
ctx.beginPath();
ctx.moveTo(x - roll, y + btnY + introOffset + taskOffset - roll);
ctx.lineTo(x + (20*units) + this._SkipBtnWidth + roll, y + btnY + introOffset + taskOffset - roll);
ctx.lineTo(x + (20*units) + this._SkipBtnWidth + roll, y + btnY + (20*units) + introOffset + taskOffset + roll);
ctx.lineTo(x - roll, y + btnY + (20*units) + introOffset + taskOffset + roll);
ctx.closePath();
ctx.stroke();
} else {
taskOffset = (this.TaskLines-2) * lineHeight;
btnTxt = this.Text.DoneButton.toUpperCase();
ctx.fillText(btnTxt, x + (10*units), y + btnY + (14*units) + introOffset + taskOffset);
ctx.beginPath();
ctx.moveTo(x - roll, y + btnY + introOffset + taskOffset - roll);
ctx.lineTo(x + (20*units) + this._DoneBtnWidth + roll, y + btnY + introOffset + taskOffset - roll);
ctx.lineTo(x + (20*units) + this._DoneBtnWidth + roll, y + btnY + (20*units) + introOffset + taskOffset + roll);
ctx.lineTo(x - roll, y + btnY + (20*units) + introOffset + taskOffset + roll);
ctx.closePath();
ctx.stroke();
// TOUR COMPLETE //
//ctx.fillText(this.Text.TourComplete, x + numberWidth + (10*units), y - (20*units));
// TICK //
var yx = x + numberWidth + (20*units);
var yy = y - (28*units);
ctx.beginPath();
ctx.moveTo(yx - (12*units), yy);
ctx.lineTo(yx - (4*units), yy + (8*units));
ctx.lineTo(yx + (12*units), yy - (8*units));
ctx.stroke();
}
// COPY //
ctx.font = italicType;
var string = this.Text.Scenes[this.CurrentScene-1].Intro;
this.WordWrap(ctx,string, x, y + (25*units),lineHeight,this.TextWidth*units);
var string = this.Text.Scenes[this.CurrentScene-1].Task;
if (string!=="") {
this.WordWrap(ctx,string, x, y + (25*units) + introOffset,lineHeight,this.TextWidth*units);
// TASK DOT //
var dx = x - (10*units);
var dy = y + (22*units) + introOffset;
ctx.beginPath();
ctx.moveTo(dx, dy - (2*units));
ctx.lineTo(dx + (2*units), dy);
ctx.lineTo(dx, dy + (2*units));
ctx.lineTo(dx - (2*units), dy);
ctx.closePath();
ctx.fill();
var size = 5;
ctx.beginPath();
ctx.moveTo(dx, dy - (size*units));
ctx.lineTo(dx + (size*units), dy);
ctx.lineTo(dx, dy + (size*units));
ctx.lineTo(dx - (size*units), dy);
ctx.closePath();
ctx.stroke();
}
}
}
AnimateButton() {
this._AnimateCount += 1;
if (this._AnimateCount>60) {
this.DelayTo(this,-this.AnimatePolarity,0.3,0,"AnimatePolarity");
this._AnimateCount = 0;
}
}
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) );
}
}
LineCount( context , text, fitWidth) {
fitWidth = fitWidth || 0;
if (fitWidth <= 0) {
return 1;
}
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;
}
currentLine++;
words = words.splice(idx-1);
idx = 1;
}
else
{idx++;}
}
return currentLine;
}
NumberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
//-------------------------------------------------------------------------------------------
// TWEEN
//-------------------------------------------------------------------------------------------
DelayTo(panel,destination,t,delay,v){
var offsetTween = new window.TWEEN.Tween({x: panel[""+v]});
offsetTween.to({x: destination}, t*1000);
offsetTween.onUpdate(function () {
panel[""+v] = this.x;
});
offsetTween.onComplete(function() {
if (v=="OffsetY") {
if (destination!==0) {
panel.Open = false;
}
}
});
offsetTween.easing(window.TWEEN.Easing.Exponential.InOut);
offsetTween.delay(delay);
offsetTween.start(this.LastVisualTick);
}
//-------------------------------------------------------------------------------------------
// INTERACTION
//-------------------------------------------------------------------------------------------
OpenSplash() {
this.SplashOpen = true;
this.DelayTo(this.Offset2,0,1,0,"x");
if (App.Stage) {
if (App.MainScene.Header.DropDown) {
App.MainScene.Header.ClosePanel();
}
}
if (this.Open) {
this.ClosePanel();
}
}
CloseSplash() {
this.SplashOpen = false;
this.DelayTo(this.Offset2,-1,0.6,0,"x");
}
OpenPanel() {
if (App.Blocks.length) {
App.Stage.MainScene.ResetScene();
}
App.MainScene.ZoomButtons.ZoomReset(false);
this.OptionsInteract = false;
// WHICH TUTORIAL //
if (!App.PointerInputManager.TouchAssumed) {
this.Text = App.L10n.UI.Tutorial;
this._TutKeys = true;
} else {
this.Text = App.L10n.UI.TutorialTouch;
this._TutKeys = false;
}
this.CurrentScene = 1;
this.TotalScenes = this.Text.Scenes.length;
this.Open = true;
this.CountIntroLines();
this.DelayTo(this.Offset,this.TextWidth + 20,1,0,"x");
}
ClosePanel() {
this.Open = false;
App.MainScene.TutorialHotspots.Points = [];
this.WatchedBlocks = [];
this.DelayTo(this.Offset,-20,0.5,0,"x");
}
NextScene() {
var t = 0.4;
this.DelayTo(this.Offset,-20,t,0,"x");
var that = this;
setTimeout(function(){
if ((that.CurrentScene<that.TotalScenes)) {
that.CurrentScene += 1;
that.CountIntroLines();
that.DelayTo(that.Offset,that.TextWidth + 20,t,0,"x");
}
},(t*1000));
}
Skip() {
App.SkipTutorial = true;
}
UpdateHotspots() {
var ctx = this.Ctx;
var units = App.Unit;
var header = App.MainScene.Header;
var menuH = (header.Height * header.Rows)*units;
var itemWidth = App.Width / (header.ItemsPerPage+1);
var hotspots = [];
var itemX;
// IF KEYBOARD TUTORIAL //
if (this._TutKeys) {
switch (this.CurrentScene) {
case 1: // CREATE TONE
if (!this.WatchedBlocks[0]) {
if (header.DropDown && header.MenuItems[0].Selected) {
if (header.MenuItems[0].CurrentPage===0) {
itemX = this.GutterCheck(0,itemWidth,header.MenuItems[0],units);
hotspots.push(new Point(itemX,menuH + (header.DropDown*units)));
}
} else {
hotspots.push(new Point(header.MenuItems[0].Position.x,menuH));
}
}
break;
case 2: // CREATE KEYBOARD
if (!this.WatchedBlocks[1]) {
if (header.DropDown && header.MenuItems[3].Selected) {
if (header.MenuItems[3].CurrentPage === 0) {
itemX = this.GutterCheck(0,itemWidth,header.MenuItems[3],units);
hotspots.push(new Point(itemX, menuH + (header.DropDown * units)));
}
} else {
hotspots.push(new Point(header.MenuItems[3].Position.x, menuH));
}
}
break;
case 3: // CREATE CHOPPER
if (!this.WatchedBlocks[4]) {
if (header.DropDown && header.MenuItems[1].Selected) {
if (header.MenuItems[1].CurrentPage === 0) {
itemX = this.GutterCheck(3,itemWidth,header.MenuItems[1],units);
hotspots.push(new Point(itemX, menuH + (header.DropDown * units)));
}
} else {
hotspots.push(new Point(header.MenuItems[1].Position.x, menuH));
}
}
break;
case 4: // CHOPPER OPTIONS
if (this.WatchedBlocks[3]) {
if (!App.MainScene.IsDraggingABlock) {
var blockPos = new Point(this.WatchedBlocks[3].Position.x,this.WatchedBlocks[3].Position.y + 2);
blockPos = App.Metrics.PointOnGrid(blockPos);
hotspots.push(new Point(blockPos.x, blockPos.y + (6*units)));
}
}
break;
case 5: // TRASH KEYBOARD
if (this.WatchedBlocks[1]) {
if (!App.MainScene.IsDraggingABlock) {
var blockPos = new Point(this.WatchedBlocks[1].Position.x,this.WatchedBlocks[1].Position.y + 2);
blockPos = App.Metrics.PointOnGrid(blockPos);
hotspots.push(new Point(blockPos.x, blockPos.y + (6*units)));
}
hotspots.push(new Point(App.Width - (46*units),App.Height - (30*units)));
}
break;
case 6: // CREATE PARTICLE EMITTER
if (!this.WatchedBlocks[5]) {
if (header.DropDown && header.MenuItems[2].Selected) {
if (header.MenuItems[2].CurrentPage === 0) {
itemX = this.GutterCheck(0,itemWidth,header.MenuItems[2],units);
hotspots.push(new Point(itemX, menuH + (header.DropDown * units)));
}
} else {
hotspots.push(new Point(header.MenuItems[2].Position.x, menuH));
}
}
if (!this.WatchedBlocks[5] || App.MainScene.IsDraggingABlock) {
var blockPos = new Point(this.WatchedBlocks[0].Position.x,this.WatchedBlocks[0].Position.y + 12);
blockPos = App.Metrics.PointOnGrid(blockPos);
hotspots.push(new Point(blockPos.x, blockPos.y));
}
break;
case 7: // CREATE POWER
if (!this.WatchedBlocks[6]) {
if (header.DropDown && header.MenuItems[2].Selected) {
if (header.MenuItems[2].CurrentPage === 0) {
itemX = this.GutterCheck(1,itemWidth,header.MenuItems[2],units);
hotspots.push(new Point(itemX, menuH + (header.DropDown * units)));
}
} else {
hotspots.push(new Point(header.MenuItems[2].Position.x, menuH));
}
}
break;
default:
break;
}
}
// IF TOUCHSCREEN TUTORIAL //
else {
switch (this.CurrentScene) {
case 1: // CREATE TONE
if (!this.WatchedBlocks[0]) {
if (header.DropDown && header.MenuItems[0].Selected) {
if (header.MenuItems[0].CurrentPage===0) {
itemX = this.GutterCheck(0,itemWidth,header.MenuItems[0],units);
hotspots.push(new Point(itemX,menuH + (header.DropDown*units)));
}
} else {
hotspots.push(new Point(header.MenuItems[0].Position.x,menuH));
}
}
break;
case 2: // CREATE PARTICLE EMITTER
if (!this.WatchedBlocks[5]) {
if (header.DropDown && header.MenuItems[2].Selected) {
if (header.MenuItems[2].CurrentPage === 0) {
itemX = this.GutterCheck(0,itemWidth,header.MenuItems[2],units);
hotspots.push(new Point(itemX, menuH + (header.DropDown * units)));
}
} else {
hotspots.push(new Point(header.MenuItems[2].Position.x, menuH));
}
}
if (!this.WatchedBlocks[5] || App.MainScene.IsDraggingABlock) {
var blockPos = new Point(this.WatchedBlocks[0].Position.x,this.WatchedBlocks[0].Position.y + 12);
blockPos = App.Metrics.PointOnGrid(blockPos);
hotspots.push(new Point(blockPos.x, blockPos.y));
}
break;
case 3: // CREATE POWER
if (!this.WatchedBlocks[6]) {
if (header.DropDown && header.MenuItems[2].Selected) {
if (header.MenuItems[2].CurrentPage === 0) {
itemX = this.GutterCheck(1,itemWidth,header.MenuItems[2],units);
hotspots.push(new Point(itemX, menuH + (header.DropDown * units)));
}
} else {
hotspots.push(new Point(header.MenuItems[2].Position.x, menuH));
}
}
break;
case 4: // CREATE CHOPPER
if (!this.WatchedBlocks[4]) {
if (header.DropDown && header.MenuItems[1].Selected) {
if (header.MenuItems[1].CurrentPage === 0) {
itemX = this.GutterCheck(3,itemWidth,header.MenuItems[1],units);
hotspots.push(new Point(itemX, menuH + (header.DropDown * units)));
}
} else {
hotspots.push(new Point(header.MenuItems[1].Position.x, menuH));
}
}
break;
case 5: // CHOPPER OPTIONS
if (this.WatchedBlocks[3]) {
if (!App.MainScene.IsDraggingABlock) {
var blockPos = new Point(this.WatchedBlocks[3].Position.x,this.WatchedBlocks[3].Position.y + 2);
blockPos = App.Metrics.PointOnGrid(blockPos);
hotspots.push(new Point(blockPos.x, blockPos.y + (6*units)));
}
}
break;
default:
break;
}
}
App.MainScene.TutorialHotspots.Points = hotspots;
}
GutterCheck(n,w,cat,units) {
if (cat.Pages===0) {
return ((w * (n+0.5)) + (20*units));
} else {
return (w * (n+1));
}
}
SplashMouseDown(point) {
this.HitTests(point);
if (this.SplashOpen) {
if (this._RollOvers[0]) { // TOUR //
this.OpenPanel();
}
if (this._RollOvers[1]) {
this.Skip();
}
this.CloseSplash();
}
}
MouseDown(point) {
this.HitTests(point);
if (this._RollOvers[2]) { // SKIP 2 //
this.ClosePanel();
this.Skip();
}
}
MouseUp(point) {
}
MouseMove(point) {
this.HitTests(point);
}
HitTests(point) {
var ctx = this.Ctx;
var units = App.Unit;
var x = App.Width - (this.Offset.x*units);
var y = (App.Height *0.5) + (this.Offset.y*units) - (20*units);
var btnY = 50*units;
var lineHeight = this._LineHeight*units;
var introOffset = (this.IntroLines+2) * lineHeight;
var taskOffset = (this.TaskLines) * lineHeight;
var padding = 60*units;
var iconY = (App.Height*0.5) + (20*units);
this._RollOvers[0] = Dimensions.hitRect((App.Width*0.5) - (padding*2), iconY - (20*units),(padding*2),60*units, point.x, point.y); // tour
this._RollOvers[1] = Dimensions.hitRect((App.Width*0.5), iconY - (20*units),(padding*2),60*units, point.x, point.y); // skip
if (this.CurrentScene < this.TotalScenes) {
this._RollOvers[2] = Dimensions.hitRect(x - (10*units), y + btnY + introOffset + taskOffset - (10*units),(40*units) + this._SkipBtnWidth,40*units, point.x, point.y); // skip
} else {
taskOffset = (this.TaskLines-2) * lineHeight;
this._RollOvers[2] = Dimensions.hitRect(x - (10*units), y + btnY + introOffset + taskOffset - (10*units),(40*units) + this._DoneBtnWidth,40*units, point.x, point.y); // done
}
this.Hover = false;
if (this.Open && this._RollOvers[2]) {
this.Hover = true;
}
if (this.SplashOpen && (this._RollOvers[0] || this._RollOvers[1])) {
this.Hover = true;
}
}
//-------------------------------------------------------------------------------------------
// RESIZE
//-------------------------------------------------------------------------------------------
Resize() {
if (this.Text) {
if (this.Open) {
this.CountIntroLines();
}
}
}
CountIntroLines() {
var units = App.Unit;
this.Ctx.font = App.Metrics.TxtMid;
this._SkipBtnWidth = this.Ctx.measureText(this.Text.SkipButton.toUpperCase()).width;
this._DoneBtnWidth = this.Ctx.measureText(this.Text.DoneButton.toUpperCase()).width;
var scene = this.Text.Scenes[this.CurrentScene-1];
this.Ctx.font = App.Metrics.TxtItalic3;
this.IntroLines = this.LineCount(this.Ctx,scene.Intro,this.TextWidth*units);
this.TaskLines = this.LineCount(this.Ctx,scene.Task,this.TextWidth*units);
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.